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/ObjCARCUtil.h"
31 #include "llvm/Analysis/ProfileSummaryInfo.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/IntrinsicLowering.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineJumpTableInfo.h"
38 #include "llvm/CodeGen/MachineLoopInfo.h"
39 #include "llvm/CodeGen/MachineModuleInfo.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/TargetLowering.h"
42 #include "llvm/CodeGen/WinEHFuncInfo.h"
43 #include "llvm/IR/CallingConv.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/DiagnosticInfo.h"
47 #include "llvm/IR/EHPersonalities.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 /// Returns true if a CC can dynamically exclude a register from the list of
108 /// callee-saved-registers (TargetRegistryInfo::getCalleeSavedRegs()) based on
109 /// the return registers.
110 static bool shouldDisableRetRegFromCSR(CallingConv::ID CC) {
111   switch (CC) {
112   default:
113     return false;
114   case CallingConv::X86_RegCall:
115   case CallingConv::PreserveMost:
116   case CallingConv::PreserveAll:
117     return true;
118   }
119 }
120 
121 /// Returns true if a CC can dynamically exclude a register from the list of
122 /// callee-saved-registers (TargetRegistryInfo::getCalleeSavedRegs()) based on
123 /// the parameters.
124 static bool shouldDisableArgRegFromCSR(CallingConv::ID CC) {
125   return CC == CallingConv::X86_RegCall;
126 }
127 
128 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
129                                      const X86Subtarget &STI)
130     : TargetLowering(TM), Subtarget(STI) {
131   bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
132   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
133 
134   // Set up the TargetLowering object.
135 
136   // X86 is weird. It always uses i8 for shift amounts and setcc results.
137   setBooleanContents(ZeroOrOneBooleanContent);
138   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
139   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
140 
141   // For 64-bit, since we have so many registers, use the ILP scheduler.
142   // For 32-bit, use the register pressure specific scheduling.
143   // For Atom, always use ILP scheduling.
144   if (Subtarget.isAtom())
145     setSchedulingPreference(Sched::ILP);
146   else if (Subtarget.is64Bit())
147     setSchedulingPreference(Sched::ILP);
148   else
149     setSchedulingPreference(Sched::RegPressure);
150   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
151   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
152 
153   // Bypass expensive divides and use cheaper ones.
154   if (TM.getOptLevel() >= CodeGenOpt::Default) {
155     if (Subtarget.hasSlowDivide32())
156       addBypassSlowDiv(32, 8);
157     if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
158       addBypassSlowDiv(64, 32);
159   }
160 
161   // Setup Windows compiler runtime calls.
162   if (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()) {
163     static const struct {
164       const RTLIB::Libcall Op;
165       const char * const Name;
166       const CallingConv::ID CC;
167     } LibraryCalls[] = {
168       { RTLIB::SDIV_I64, "_alldiv", CallingConv::X86_StdCall },
169       { RTLIB::UDIV_I64, "_aulldiv", CallingConv::X86_StdCall },
170       { RTLIB::SREM_I64, "_allrem", CallingConv::X86_StdCall },
171       { RTLIB::UREM_I64, "_aullrem", CallingConv::X86_StdCall },
172       { RTLIB::MUL_I64, "_allmul", CallingConv::X86_StdCall },
173     };
174 
175     for (const auto &LC : LibraryCalls) {
176       setLibcallName(LC.Op, LC.Name);
177       setLibcallCallingConv(LC.Op, LC.CC);
178     }
179   }
180 
181   if (Subtarget.getTargetTriple().isOSMSVCRT()) {
182     // MSVCRT doesn't have powi; fall back to pow
183     setLibcallName(RTLIB::POWI_F32, nullptr);
184     setLibcallName(RTLIB::POWI_F64, nullptr);
185   }
186 
187   // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
188   // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
189   // FIXME: Should we be limiting the atomic size on other configs? Default is
190   // 1024.
191   if (!Subtarget.canUseCMPXCHG8B())
192     setMaxAtomicSizeInBitsSupported(32);
193 
194   setMaxDivRemBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
195 
196   setMaxLargeFPConvertBitWidthSupported(128);
197 
198   // Set up the register classes.
199   addRegisterClass(MVT::i8, &X86::GR8RegClass);
200   addRegisterClass(MVT::i16, &X86::GR16RegClass);
201   addRegisterClass(MVT::i32, &X86::GR32RegClass);
202   if (Subtarget.is64Bit())
203     addRegisterClass(MVT::i64, &X86::GR64RegClass);
204 
205   for (MVT VT : MVT::integer_valuetypes())
206     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
207 
208   // We don't accept any truncstore of integer registers.
209   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
210   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
211   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
212   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
213   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
214   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
215 
216   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
217 
218   // SETOEQ and SETUNE require checking two conditions.
219   for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
220     setCondCodeAction(ISD::SETOEQ, VT, Expand);
221     setCondCodeAction(ISD::SETUNE, VT, Expand);
222   }
223 
224   // Integer absolute.
225   if (Subtarget.canUseCMOV()) {
226     setOperationAction(ISD::ABS            , MVT::i16  , Custom);
227     setOperationAction(ISD::ABS            , MVT::i32  , Custom);
228     if (Subtarget.is64Bit())
229       setOperationAction(ISD::ABS          , MVT::i64  , Custom);
230   }
231 
232   // Absolute difference.
233   for (auto Op : {ISD::ABDS, ISD::ABDU}) {
234     setOperationAction(Op                  , MVT::i8   , Custom);
235     setOperationAction(Op                  , MVT::i16  , Custom);
236     setOperationAction(Op                  , MVT::i32  , Custom);
237     if (Subtarget.is64Bit())
238      setOperationAction(Op                 , MVT::i64  , Custom);
239   }
240 
241   // Signed saturation subtraction.
242   setOperationAction(ISD::SSUBSAT          , MVT::i8   , Custom);
243   setOperationAction(ISD::SSUBSAT          , MVT::i16  , Custom);
244   setOperationAction(ISD::SSUBSAT          , MVT::i32  , Custom);
245   if (Subtarget.is64Bit())
246     setOperationAction(ISD::SSUBSAT        , MVT::i64  , Custom);
247 
248   // Funnel shifts.
249   for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
250     // For slow shld targets we only lower for code size.
251     LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
252 
253     setOperationAction(ShiftOp             , MVT::i8   , Custom);
254     setOperationAction(ShiftOp             , MVT::i16  , Custom);
255     setOperationAction(ShiftOp             , MVT::i32  , ShiftDoubleAction);
256     if (Subtarget.is64Bit())
257       setOperationAction(ShiftOp           , MVT::i64  , ShiftDoubleAction);
258   }
259 
260   if (!Subtarget.useSoftFloat()) {
261     // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
262     // operation.
263     setOperationAction(ISD::UINT_TO_FP,        MVT::i8, Promote);
264     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
265     setOperationAction(ISD::UINT_TO_FP,        MVT::i16, Promote);
266     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
267     // We have an algorithm for SSE2, and we turn this into a 64-bit
268     // FILD or VCVTUSI2SS/SD for other targets.
269     setOperationAction(ISD::UINT_TO_FP,        MVT::i32, Custom);
270     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
271     // We have an algorithm for SSE2->double, and we turn this into a
272     // 64-bit FILD followed by conditional FADD for other targets.
273     setOperationAction(ISD::UINT_TO_FP,        MVT::i64, Custom);
274     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
275 
276     // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
277     // this operation.
278     setOperationAction(ISD::SINT_TO_FP,        MVT::i8, Promote);
279     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
280     // SSE has no i16 to fp conversion, only i32. We promote in the handler
281     // to allow f80 to use i16 and f64 to use i16 with sse1 only
282     setOperationAction(ISD::SINT_TO_FP,        MVT::i16, Custom);
283     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
284     // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
285     setOperationAction(ISD::SINT_TO_FP,        MVT::i32, Custom);
286     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
287     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
288     // are Legal, f80 is custom lowered.
289     setOperationAction(ISD::SINT_TO_FP,        MVT::i64, Custom);
290     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
291 
292     // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293     // this operation.
294     setOperationAction(ISD::FP_TO_SINT,        MVT::i8,  Promote);
295     // FIXME: This doesn't generate invalid exception when it should. PR44019.
296     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8,  Promote);
297     setOperationAction(ISD::FP_TO_SINT,        MVT::i16, Custom);
298     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
299     setOperationAction(ISD::FP_TO_SINT,        MVT::i32, Custom);
300     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
301     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
302     // are Legal, f80 is custom lowered.
303     setOperationAction(ISD::FP_TO_SINT,        MVT::i64, Custom);
304     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
305 
306     // Handle FP_TO_UINT by promoting the destination to a larger signed
307     // conversion.
308     setOperationAction(ISD::FP_TO_UINT,        MVT::i8,  Promote);
309     // FIXME: This doesn't generate invalid exception when it should. PR44019.
310     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8,  Promote);
311     setOperationAction(ISD::FP_TO_UINT,        MVT::i16, Promote);
312     // FIXME: This doesn't generate invalid exception when it should. PR44019.
313     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
314     setOperationAction(ISD::FP_TO_UINT,        MVT::i32, Custom);
315     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
316     setOperationAction(ISD::FP_TO_UINT,        MVT::i64, Custom);
317     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
318 
319     setOperationAction(ISD::LRINT,             MVT::f32, Custom);
320     setOperationAction(ISD::LRINT,             MVT::f64, Custom);
321     setOperationAction(ISD::LLRINT,            MVT::f32, Custom);
322     setOperationAction(ISD::LLRINT,            MVT::f64, Custom);
323 
324     if (!Subtarget.is64Bit()) {
325       setOperationAction(ISD::LRINT,  MVT::i64, Custom);
326       setOperationAction(ISD::LLRINT, MVT::i64, Custom);
327     }
328   }
329 
330   if (Subtarget.hasSSE2()) {
331     // Custom lowering for saturating float to int conversions.
332     // We handle promotion to larger result types manually.
333     for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
334       setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
335       setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
336     }
337     if (Subtarget.is64Bit()) {
338       setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
339       setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
340     }
341   }
342 
343   // Handle address space casts between mixed sized pointers.
344   setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
345   setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
346 
347   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
348   if (!Subtarget.hasSSE2()) {
349     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
350     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
351     if (Subtarget.is64Bit()) {
352       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
353       // Without SSE, i64->f64 goes through memory.
354       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
355     }
356   } else if (!Subtarget.is64Bit())
357     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
358 
359   // Scalar integer divide and remainder are lowered to use operations that
360   // produce two results, to match the available instructions. This exposes
361   // the two-result form to trivial CSE, which is able to combine x/y and x%y
362   // into a single instruction.
363   //
364   // Scalar integer multiply-high is also lowered to use two-result
365   // operations, to match the available instructions. However, plain multiply
366   // (low) operations are left as Legal, as there are single-result
367   // instructions for this in x86. Using the two-result multiply instructions
368   // when both high and low results are needed must be arranged by dagcombine.
369   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
370     setOperationAction(ISD::MULHS, VT, Expand);
371     setOperationAction(ISD::MULHU, VT, Expand);
372     setOperationAction(ISD::SDIV, VT, Expand);
373     setOperationAction(ISD::UDIV, VT, Expand);
374     setOperationAction(ISD::SREM, VT, Expand);
375     setOperationAction(ISD::UREM, VT, Expand);
376   }
377 
378   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
379   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
380   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
381                    MVT::i8,  MVT::i16, MVT::i32, MVT::i64 }) {
382     setOperationAction(ISD::BR_CC,     VT, Expand);
383     setOperationAction(ISD::SELECT_CC, VT, Expand);
384   }
385   if (Subtarget.is64Bit())
386     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
387   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
388   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
389   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
390 
391   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
392   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
393   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
394   setOperationAction(ISD::FREM             , MVT::f128 , Expand);
395 
396   if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
397     setOperationAction(ISD::GET_ROUNDING   , MVT::i32  , Custom);
398     setOperationAction(ISD::SET_ROUNDING   , MVT::Other, Custom);
399     setOperationAction(ISD::GET_FPENV_MEM  , MVT::Other, Custom);
400     setOperationAction(ISD::SET_FPENV_MEM  , MVT::Other, Custom);
401     setOperationAction(ISD::RESET_FPENV    , MVT::Other, Custom);
402   }
403 
404   // Promote the i8 variants and force them on up to i32 which has a shorter
405   // encoding.
406   setOperationPromotedToType(ISD::CTTZ           , MVT::i8   , MVT::i32);
407   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
408   // Promoted i16. tzcntw has a false dependency on Intel CPUs. For BSF, we emit
409   // a REP prefix to encode it as TZCNT for modern CPUs so it makes sense to
410   // promote that too.
411   setOperationPromotedToType(ISD::CTTZ           , MVT::i16  , MVT::i32);
412   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , MVT::i32);
413 
414   if (!Subtarget.hasBMI()) {
415     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
416     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Legal);
417     if (Subtarget.is64Bit()) {
418       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
419       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
420     }
421   }
422 
423   if (Subtarget.hasLZCNT()) {
424     // When promoting the i8 variants, force them to i32 for a shorter
425     // encoding.
426     setOperationPromotedToType(ISD::CTLZ           , MVT::i8   , MVT::i32);
427     setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
428   } else {
429     for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
430       if (VT == MVT::i64 && !Subtarget.is64Bit())
431         continue;
432       setOperationAction(ISD::CTLZ           , VT, Custom);
433       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
434     }
435   }
436 
437   for (auto Op : {ISD::FP16_TO_FP, ISD::STRICT_FP16_TO_FP, ISD::FP_TO_FP16,
438                   ISD::STRICT_FP_TO_FP16}) {
439     // Special handling for half-precision floating point conversions.
440     // If we don't have F16C support, then lower half float conversions
441     // into library calls.
442     setOperationAction(
443         Op, MVT::f32,
444         (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
445     // There's never any support for operations beyond MVT::f32.
446     setOperationAction(Op, MVT::f64, Expand);
447     setOperationAction(Op, MVT::f80, Expand);
448     setOperationAction(Op, MVT::f128, Expand);
449   }
450 
451   for (MVT VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
452     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
453     setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
454     setTruncStoreAction(VT, MVT::f16, Expand);
455     setTruncStoreAction(VT, MVT::bf16, Expand);
456 
457     setOperationAction(ISD::BF16_TO_FP, VT, Expand);
458     setOperationAction(ISD::FP_TO_BF16, VT, Custom);
459   }
460 
461   setOperationAction(ISD::PARITY, MVT::i8, Custom);
462   setOperationAction(ISD::PARITY, MVT::i16, Custom);
463   setOperationAction(ISD::PARITY, MVT::i32, Custom);
464   if (Subtarget.is64Bit())
465     setOperationAction(ISD::PARITY, MVT::i64, Custom);
466   if (Subtarget.hasPOPCNT()) {
467     setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
468     // popcntw is longer to encode than popcntl and also has a false dependency
469     // on the dest that popcntl hasn't had since Cannon Lake.
470     setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
471   } else {
472     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
473     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
474     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
475     if (Subtarget.is64Bit())
476       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
477     else
478       setOperationAction(ISD::CTPOP        , MVT::i64  , Custom);
479   }
480 
481   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
482 
483   if (!Subtarget.hasMOVBE())
484     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
485 
486   // X86 wants to expand cmov itself.
487   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
488     setOperationAction(ISD::SELECT, VT, Custom);
489     setOperationAction(ISD::SETCC, VT, Custom);
490     setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
491     setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
492   }
493   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
494     if (VT == MVT::i64 && !Subtarget.is64Bit())
495       continue;
496     setOperationAction(ISD::SELECT, VT, Custom);
497     setOperationAction(ISD::SETCC,  VT, Custom);
498   }
499 
500   // Custom action for SELECT MMX and expand action for SELECT_CC MMX
501   setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
502   setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
503 
504   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
505   // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
506   // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
507   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
508   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
509   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
510   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
511     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
512 
513   // Darwin ABI issue.
514   for (auto VT : { MVT::i32, MVT::i64 }) {
515     if (VT == MVT::i64 && !Subtarget.is64Bit())
516       continue;
517     setOperationAction(ISD::ConstantPool    , VT, Custom);
518     setOperationAction(ISD::JumpTable       , VT, Custom);
519     setOperationAction(ISD::GlobalAddress   , VT, Custom);
520     setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
521     setOperationAction(ISD::ExternalSymbol  , VT, Custom);
522     setOperationAction(ISD::BlockAddress    , VT, Custom);
523   }
524 
525   // 64-bit shl, sra, srl (iff 32-bit x86)
526   for (auto VT : { MVT::i32, MVT::i64 }) {
527     if (VT == MVT::i64 && !Subtarget.is64Bit())
528       continue;
529     setOperationAction(ISD::SHL_PARTS, VT, Custom);
530     setOperationAction(ISD::SRA_PARTS, VT, Custom);
531     setOperationAction(ISD::SRL_PARTS, VT, Custom);
532   }
533 
534   if (Subtarget.hasSSEPrefetch() || Subtarget.hasThreeDNow())
535     setOperationAction(ISD::PREFETCH      , MVT::Other, Custom);
536 
537   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
538 
539   // Expand certain atomics
540   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
541     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
542     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
543     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
544     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
545     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
546     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
547     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
548   }
549 
550   if (!Subtarget.is64Bit())
551     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
552 
553   if (Subtarget.canUseCMPXCHG16B())
554     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
555 
556   // FIXME - use subtarget debug flags
557   if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
558       !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
559       TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
560     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
561   }
562 
563   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
564   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
565 
566   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
567   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
568 
569   setOperationAction(ISD::TRAP, MVT::Other, Legal);
570   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
571   if (Subtarget.isTargetPS())
572     setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand);
573   else
574     setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
575 
576   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
577   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
578   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
579   bool Is64Bit = Subtarget.is64Bit();
580   setOperationAction(ISD::VAARG,  MVT::Other, Is64Bit ? Custom : Expand);
581   setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
582 
583   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
584   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
585 
586   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
587 
588   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
589   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
590   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
591 
592   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
593 
594   auto setF16Action = [&] (MVT VT, LegalizeAction Action) {
595     setOperationAction(ISD::FABS, VT, Action);
596     setOperationAction(ISD::FNEG, VT, Action);
597     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
598     setOperationAction(ISD::FREM, VT, Action);
599     setOperationAction(ISD::FMA, VT, Action);
600     setOperationAction(ISD::FMINNUM, VT, Action);
601     setOperationAction(ISD::FMAXNUM, VT, Action);
602     setOperationAction(ISD::FMINIMUM, VT, Action);
603     setOperationAction(ISD::FMAXIMUM, VT, Action);
604     setOperationAction(ISD::FSIN, VT, Action);
605     setOperationAction(ISD::FCOS, VT, Action);
606     setOperationAction(ISD::FSINCOS, VT, Action);
607     setOperationAction(ISD::FSQRT, VT, Action);
608     setOperationAction(ISD::FPOW, VT, Action);
609     setOperationAction(ISD::FLOG, VT, Action);
610     setOperationAction(ISD::FLOG2, VT, Action);
611     setOperationAction(ISD::FLOG10, VT, Action);
612     setOperationAction(ISD::FEXP, VT, Action);
613     setOperationAction(ISD::FEXP2, VT, Action);
614     setOperationAction(ISD::FCEIL, VT, Action);
615     setOperationAction(ISD::FFLOOR, VT, Action);
616     setOperationAction(ISD::FNEARBYINT, VT, Action);
617     setOperationAction(ISD::FRINT, VT, Action);
618     setOperationAction(ISD::BR_CC, VT, Action);
619     setOperationAction(ISD::SETCC, VT, Action);
620     setOperationAction(ISD::SELECT, VT, Custom);
621     setOperationAction(ISD::SELECT_CC, VT, Action);
622     setOperationAction(ISD::FROUND, VT, Action);
623     setOperationAction(ISD::FROUNDEVEN, VT, Action);
624     setOperationAction(ISD::FTRUNC, VT, Action);
625     setOperationAction(ISD::FLDEXP, VT, Action);
626   };
627 
628   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
629     // f16, f32 and f64 use SSE.
630     // Set up the FP register classes.
631     addRegisterClass(MVT::f16, Subtarget.hasAVX512() ? &X86::FR16XRegClass
632                                                      : &X86::FR16RegClass);
633     addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
634                                                      : &X86::FR32RegClass);
635     addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
636                                                      : &X86::FR64RegClass);
637 
638     // Disable f32->f64 extload as we can only generate this in one instruction
639     // under optsize. So its easier to pattern match (fpext (load)) for that
640     // case instead of needing to emit 2 instructions for extload in the
641     // non-optsize case.
642     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
643 
644     for (auto VT : { MVT::f32, MVT::f64 }) {
645       // Use ANDPD to simulate FABS.
646       setOperationAction(ISD::FABS, VT, Custom);
647 
648       // Use XORP to simulate FNEG.
649       setOperationAction(ISD::FNEG, VT, Custom);
650 
651       // Use ANDPD and ORPD to simulate FCOPYSIGN.
652       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
653 
654       // These might be better off as horizontal vector ops.
655       setOperationAction(ISD::FADD, VT, Custom);
656       setOperationAction(ISD::FSUB, VT, Custom);
657 
658       // We don't support sin/cos/fmod
659       setOperationAction(ISD::FSIN   , VT, Expand);
660       setOperationAction(ISD::FCOS   , VT, Expand);
661       setOperationAction(ISD::FSINCOS, VT, Expand);
662     }
663 
664     // Half type will be promoted by default.
665     setF16Action(MVT::f16, Promote);
666     setOperationAction(ISD::FADD, MVT::f16, Promote);
667     setOperationAction(ISD::FSUB, MVT::f16, Promote);
668     setOperationAction(ISD::FMUL, MVT::f16, Promote);
669     setOperationAction(ISD::FDIV, MVT::f16, Promote);
670     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
671     setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
672     setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
673 
674     setOperationAction(ISD::STRICT_FADD, MVT::f16, Promote);
675     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Promote);
676     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Promote);
677     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Promote);
678     setOperationAction(ISD::STRICT_FMA, MVT::f16, Promote);
679     setOperationAction(ISD::STRICT_FMINNUM, MVT::f16, Promote);
680     setOperationAction(ISD::STRICT_FMAXNUM, MVT::f16, Promote);
681     setOperationAction(ISD::STRICT_FMINIMUM, MVT::f16, Promote);
682     setOperationAction(ISD::STRICT_FMAXIMUM, MVT::f16, Promote);
683     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Promote);
684     setOperationAction(ISD::STRICT_FPOW, MVT::f16, Promote);
685     setOperationAction(ISD::STRICT_FLDEXP, MVT::f16, Promote);
686     setOperationAction(ISD::STRICT_FLOG, MVT::f16, Promote);
687     setOperationAction(ISD::STRICT_FLOG2, MVT::f16, Promote);
688     setOperationAction(ISD::STRICT_FLOG10, MVT::f16, Promote);
689     setOperationAction(ISD::STRICT_FEXP, MVT::f16, Promote);
690     setOperationAction(ISD::STRICT_FEXP2, MVT::f16, Promote);
691     setOperationAction(ISD::STRICT_FCEIL, MVT::f16, Promote);
692     setOperationAction(ISD::STRICT_FFLOOR, MVT::f16, Promote);
693     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f16, Promote);
694     setOperationAction(ISD::STRICT_FRINT, MVT::f16, Promote);
695     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Promote);
696     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Promote);
697     setOperationAction(ISD::STRICT_FROUND, MVT::f16, Promote);
698     setOperationAction(ISD::STRICT_FROUNDEVEN, MVT::f16, Promote);
699     setOperationAction(ISD::STRICT_FTRUNC, MVT::f16, Promote);
700     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
701     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
702     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
703 
704     setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
705     setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
706 
707     // Lower this to MOVMSK plus an AND.
708     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
709     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
710 
711   } else if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1() &&
712              (UseX87 || Is64Bit)) {
713     // Use SSE for f32, x87 for f64.
714     // Set up the FP register classes.
715     addRegisterClass(MVT::f32, &X86::FR32RegClass);
716     if (UseX87)
717       addRegisterClass(MVT::f64, &X86::RFP64RegClass);
718 
719     // Use ANDPS to simulate FABS.
720     setOperationAction(ISD::FABS , MVT::f32, Custom);
721 
722     // Use XORP to simulate FNEG.
723     setOperationAction(ISD::FNEG , MVT::f32, Custom);
724 
725     if (UseX87)
726       setOperationAction(ISD::UNDEF, MVT::f64, Expand);
727 
728     // Use ANDPS and ORPS to simulate FCOPYSIGN.
729     if (UseX87)
730       setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
731     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
732 
733     // We don't support sin/cos/fmod
734     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
735     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
736     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
737 
738     if (UseX87) {
739       // Always expand sin/cos functions even though x87 has an instruction.
740       setOperationAction(ISD::FSIN, MVT::f64, Expand);
741       setOperationAction(ISD::FCOS, MVT::f64, Expand);
742       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
743     }
744   } else if (UseX87) {
745     // f32 and f64 in x87.
746     // Set up the FP register classes.
747     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
748     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
749 
750     for (auto VT : { MVT::f32, MVT::f64 }) {
751       setOperationAction(ISD::UNDEF,     VT, Expand);
752       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
753 
754       // Always expand sin/cos functions even though x87 has an instruction.
755       setOperationAction(ISD::FSIN   , VT, Expand);
756       setOperationAction(ISD::FCOS   , VT, Expand);
757       setOperationAction(ISD::FSINCOS, VT, Expand);
758     }
759   }
760 
761   // Expand FP32 immediates into loads from the stack, save special cases.
762   if (isTypeLegal(MVT::f32)) {
763     if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
764       addLegalFPImmediate(APFloat(+0.0f)); // FLD0
765       addLegalFPImmediate(APFloat(+1.0f)); // FLD1
766       addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
767       addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
768     } else // SSE immediates.
769       addLegalFPImmediate(APFloat(+0.0f)); // xorps
770   }
771   // Expand FP64 immediates into loads from the stack, save special cases.
772   if (isTypeLegal(MVT::f64)) {
773     if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
774       addLegalFPImmediate(APFloat(+0.0)); // FLD0
775       addLegalFPImmediate(APFloat(+1.0)); // FLD1
776       addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
777       addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
778     } else // SSE immediates.
779       addLegalFPImmediate(APFloat(+0.0)); // xorpd
780   }
781   // Support fp16 0 immediate.
782   if (isTypeLegal(MVT::f16))
783     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
784 
785   // Handle constrained floating-point operations of scalar.
786   setOperationAction(ISD::STRICT_FADD,      MVT::f32, Legal);
787   setOperationAction(ISD::STRICT_FADD,      MVT::f64, Legal);
788   setOperationAction(ISD::STRICT_FSUB,      MVT::f32, Legal);
789   setOperationAction(ISD::STRICT_FSUB,      MVT::f64, Legal);
790   setOperationAction(ISD::STRICT_FMUL,      MVT::f32, Legal);
791   setOperationAction(ISD::STRICT_FMUL,      MVT::f64, Legal);
792   setOperationAction(ISD::STRICT_FDIV,      MVT::f32, Legal);
793   setOperationAction(ISD::STRICT_FDIV,      MVT::f64, Legal);
794   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f32, Legal);
795   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f64, Legal);
796   setOperationAction(ISD::STRICT_FSQRT,     MVT::f32, Legal);
797   setOperationAction(ISD::STRICT_FSQRT,     MVT::f64, Legal);
798 
799   // We don't support FMA.
800   setOperationAction(ISD::FMA, MVT::f64, Expand);
801   setOperationAction(ISD::FMA, MVT::f32, Expand);
802 
803   // f80 always uses X87.
804   if (UseX87) {
805     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
806     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
807     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
808     {
809       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
810       addLegalFPImmediate(TmpFlt);  // FLD0
811       TmpFlt.changeSign();
812       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
813 
814       bool ignored;
815       APFloat TmpFlt2(+1.0);
816       TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
817                       &ignored);
818       addLegalFPImmediate(TmpFlt2);  // FLD1
819       TmpFlt2.changeSign();
820       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
821     }
822 
823     // Always expand sin/cos functions even though x87 has an instruction.
824     setOperationAction(ISD::FSIN   , MVT::f80, Expand);
825     setOperationAction(ISD::FCOS   , MVT::f80, Expand);
826     setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
827 
828     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
829     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
830     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
831     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
832     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
833     setOperationAction(ISD::FMA, MVT::f80, Expand);
834     setOperationAction(ISD::LROUND, MVT::f80, Expand);
835     setOperationAction(ISD::LLROUND, MVT::f80, Expand);
836     setOperationAction(ISD::LRINT, MVT::f80, Custom);
837     setOperationAction(ISD::LLRINT, MVT::f80, Custom);
838 
839     // Handle constrained floating-point operations of scalar.
840     setOperationAction(ISD::STRICT_FADD     , MVT::f80, Legal);
841     setOperationAction(ISD::STRICT_FSUB     , MVT::f80, Legal);
842     setOperationAction(ISD::STRICT_FMUL     , MVT::f80, Legal);
843     setOperationAction(ISD::STRICT_FDIV     , MVT::f80, Legal);
844     setOperationAction(ISD::STRICT_FSQRT    , MVT::f80, Legal);
845     if (isTypeLegal(MVT::f16)) {
846       setOperationAction(ISD::FP_EXTEND, MVT::f80, Custom);
847       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Custom);
848     } else {
849       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
850     }
851     // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
852     // as Custom.
853     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
854   }
855 
856   // f128 uses xmm registers, but most operations require libcalls.
857   if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
858     addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
859                                                    : &X86::VR128RegClass);
860 
861     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
862 
863     setOperationAction(ISD::FADD,        MVT::f128, LibCall);
864     setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
865     setOperationAction(ISD::FSUB,        MVT::f128, LibCall);
866     setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
867     setOperationAction(ISD::FDIV,        MVT::f128, LibCall);
868     setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
869     setOperationAction(ISD::FMUL,        MVT::f128, LibCall);
870     setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
871     setOperationAction(ISD::FMA,         MVT::f128, LibCall);
872     setOperationAction(ISD::STRICT_FMA,  MVT::f128, LibCall);
873 
874     setOperationAction(ISD::FABS, MVT::f128, Custom);
875     setOperationAction(ISD::FNEG, MVT::f128, Custom);
876     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
877 
878     setOperationAction(ISD::FSIN,         MVT::f128, LibCall);
879     setOperationAction(ISD::STRICT_FSIN,  MVT::f128, LibCall);
880     setOperationAction(ISD::FCOS,         MVT::f128, LibCall);
881     setOperationAction(ISD::STRICT_FCOS,  MVT::f128, LibCall);
882     setOperationAction(ISD::FSINCOS,      MVT::f128, LibCall);
883     // No STRICT_FSINCOS
884     setOperationAction(ISD::FSQRT,        MVT::f128, LibCall);
885     setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
886 
887     setOperationAction(ISD::FP_EXTEND,        MVT::f128, Custom);
888     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
889     // We need to custom handle any FP_ROUND with an f128 input, but
890     // LegalizeDAG uses the result type to know when to run a custom handler.
891     // So we have to list all legal floating point result types here.
892     if (isTypeLegal(MVT::f32)) {
893       setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
894       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
895     }
896     if (isTypeLegal(MVT::f64)) {
897       setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
898       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
899     }
900     if (isTypeLegal(MVT::f80)) {
901       setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
902       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
903     }
904 
905     setOperationAction(ISD::SETCC, MVT::f128, Custom);
906 
907     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
908     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
909     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
910     setTruncStoreAction(MVT::f128, MVT::f32, Expand);
911     setTruncStoreAction(MVT::f128, MVT::f64, Expand);
912     setTruncStoreAction(MVT::f128, MVT::f80, Expand);
913   }
914 
915   // Always use a library call for pow.
916   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
917   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
918   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
919   setOperationAction(ISD::FPOW             , MVT::f128 , Expand);
920 
921   setOperationAction(ISD::FLOG, MVT::f80, Expand);
922   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
923   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
924   setOperationAction(ISD::FEXP, MVT::f80, Expand);
925   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
926   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
927   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
928 
929   // Some FP actions are always expanded for vector types.
930   for (auto VT : { MVT::v8f16, MVT::v16f16, MVT::v32f16,
931                    MVT::v4f32, MVT::v8f32,  MVT::v16f32,
932                    MVT::v2f64, MVT::v4f64,  MVT::v8f64 }) {
933     setOperationAction(ISD::FSIN,      VT, Expand);
934     setOperationAction(ISD::FSINCOS,   VT, Expand);
935     setOperationAction(ISD::FCOS,      VT, Expand);
936     setOperationAction(ISD::FREM,      VT, Expand);
937     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
938     setOperationAction(ISD::FPOW,      VT, Expand);
939     setOperationAction(ISD::FLOG,      VT, Expand);
940     setOperationAction(ISD::FLOG2,     VT, Expand);
941     setOperationAction(ISD::FLOG10,    VT, Expand);
942     setOperationAction(ISD::FEXP,      VT, Expand);
943     setOperationAction(ISD::FEXP2,     VT, Expand);
944   }
945 
946   // First set operation action for all vector types to either promote
947   // (for widening) or expand (for scalarization). Then we will selectively
948   // turn on ones that can be effectively codegen'd.
949   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
950     setOperationAction(ISD::SDIV, VT, Expand);
951     setOperationAction(ISD::UDIV, VT, Expand);
952     setOperationAction(ISD::SREM, VT, Expand);
953     setOperationAction(ISD::UREM, VT, Expand);
954     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
955     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
956     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
957     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
958     setOperationAction(ISD::FMA,  VT, Expand);
959     setOperationAction(ISD::FFLOOR, VT, Expand);
960     setOperationAction(ISD::FCEIL, VT, Expand);
961     setOperationAction(ISD::FTRUNC, VT, Expand);
962     setOperationAction(ISD::FRINT, VT, Expand);
963     setOperationAction(ISD::FNEARBYINT, VT, Expand);
964     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
965     setOperationAction(ISD::MULHS, VT, Expand);
966     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
967     setOperationAction(ISD::MULHU, VT, Expand);
968     setOperationAction(ISD::SDIVREM, VT, Expand);
969     setOperationAction(ISD::UDIVREM, VT, Expand);
970     setOperationAction(ISD::CTPOP, VT, Expand);
971     setOperationAction(ISD::CTTZ, VT, Expand);
972     setOperationAction(ISD::CTLZ, VT, Expand);
973     setOperationAction(ISD::ROTL, VT, Expand);
974     setOperationAction(ISD::ROTR, VT, Expand);
975     setOperationAction(ISD::BSWAP, VT, Expand);
976     setOperationAction(ISD::SETCC, VT, Expand);
977     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
978     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
979     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
980     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
981     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
982     setOperationAction(ISD::TRUNCATE, VT, Expand);
983     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
984     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
985     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
986     setOperationAction(ISD::SELECT_CC, VT, Expand);
987     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
988       setTruncStoreAction(InnerVT, VT, Expand);
989 
990       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
991       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
992 
993       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
994       // types, we have to deal with them whether we ask for Expansion or not.
995       // Setting Expand causes its own optimisation problems though, so leave
996       // them legal.
997       if (VT.getVectorElementType() == MVT::i1)
998         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
999 
1000       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
1001       // split/scalarized right now.
1002       if (VT.getVectorElementType() == MVT::f16 ||
1003           VT.getVectorElementType() == MVT::bf16)
1004         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1005     }
1006   }
1007 
1008   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
1009   // with -msoft-float, disable use of MMX as well.
1010   if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
1011     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
1012     // No operations on x86mmx supported, everything uses intrinsics.
1013   }
1014 
1015   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
1016     addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1017                                                     : &X86::VR128RegClass);
1018 
1019     setOperationAction(ISD::FMAXIMUM,           MVT::f32, Custom);
1020     setOperationAction(ISD::FMINIMUM,           MVT::f32, Custom);
1021 
1022     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
1023     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
1024     setOperationAction(ISD::FCOPYSIGN,          MVT::v4f32, Custom);
1025     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
1026     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
1027     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1028     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1029     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
1030 
1031     setOperationAction(ISD::LOAD,               MVT::v2f32, Custom);
1032     setOperationAction(ISD::STORE,              MVT::v2f32, Custom);
1033 
1034     setOperationAction(ISD::STRICT_FADD,        MVT::v4f32, Legal);
1035     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f32, Legal);
1036     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f32, Legal);
1037     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f32, Legal);
1038     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f32, Legal);
1039   }
1040 
1041   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
1042     addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1043                                                     : &X86::VR128RegClass);
1044 
1045     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
1046     // registers cannot be used even for integer operations.
1047     addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
1048                                                     : &X86::VR128RegClass);
1049     addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1050                                                     : &X86::VR128RegClass);
1051     addRegisterClass(MVT::v8f16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1052                                                     : &X86::VR128RegClass);
1053     addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1054                                                     : &X86::VR128RegClass);
1055     addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1056                                                     : &X86::VR128RegClass);
1057 
1058     for (auto VT : { MVT::f64, MVT::v4f32, MVT::v2f64 }) {
1059       setOperationAction(ISD::FMAXIMUM, VT, Custom);
1060       setOperationAction(ISD::FMINIMUM, VT, Custom);
1061     }
1062 
1063     for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
1064                      MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
1065       setOperationAction(ISD::SDIV, VT, Custom);
1066       setOperationAction(ISD::SREM, VT, Custom);
1067       setOperationAction(ISD::UDIV, VT, Custom);
1068       setOperationAction(ISD::UREM, VT, Custom);
1069     }
1070 
1071     setOperationAction(ISD::MUL,                MVT::v2i8,  Custom);
1072     setOperationAction(ISD::MUL,                MVT::v4i8,  Custom);
1073     setOperationAction(ISD::MUL,                MVT::v8i8,  Custom);
1074 
1075     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
1076     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
1077     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
1078     setOperationAction(ISD::MULHU,              MVT::v4i32, Custom);
1079     setOperationAction(ISD::MULHS,              MVT::v4i32, Custom);
1080     setOperationAction(ISD::MULHU,              MVT::v16i8, Custom);
1081     setOperationAction(ISD::MULHS,              MVT::v16i8, Custom);
1082     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
1083     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
1084     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
1085     setOperationAction(ISD::AVGCEILU,           MVT::v16i8, Legal);
1086     setOperationAction(ISD::AVGCEILU,           MVT::v8i16, Legal);
1087 
1088     setOperationAction(ISD::SMULO,              MVT::v16i8, Custom);
1089     setOperationAction(ISD::UMULO,              MVT::v16i8, Custom);
1090     setOperationAction(ISD::UMULO,              MVT::v2i32, Custom);
1091 
1092     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
1093     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
1094     setOperationAction(ISD::FCOPYSIGN,          MVT::v2f64, Custom);
1095 
1096     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1097       setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
1098       setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
1099       setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
1100       setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
1101     }
1102 
1103     setOperationAction(ISD::ABDU,               MVT::v16i8, Custom);
1104     setOperationAction(ISD::ABDS,               MVT::v16i8, Custom);
1105     setOperationAction(ISD::ABDU,               MVT::v8i16, Custom);
1106     setOperationAction(ISD::ABDS,               MVT::v8i16, Custom);
1107     setOperationAction(ISD::ABDU,               MVT::v4i32, Custom);
1108     setOperationAction(ISD::ABDS,               MVT::v4i32, Custom);
1109 
1110     setOperationAction(ISD::UADDSAT,            MVT::v16i8, Legal);
1111     setOperationAction(ISD::SADDSAT,            MVT::v16i8, Legal);
1112     setOperationAction(ISD::USUBSAT,            MVT::v16i8, Legal);
1113     setOperationAction(ISD::SSUBSAT,            MVT::v16i8, Legal);
1114     setOperationAction(ISD::UADDSAT,            MVT::v8i16, Legal);
1115     setOperationAction(ISD::SADDSAT,            MVT::v8i16, Legal);
1116     setOperationAction(ISD::USUBSAT,            MVT::v8i16, Legal);
1117     setOperationAction(ISD::SSUBSAT,            MVT::v8i16, Legal);
1118     setOperationAction(ISD::USUBSAT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::USUBSAT,            MVT::v2i64, Custom);
1120 
1121     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1122     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1123     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1124     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1125 
1126     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1127       setOperationAction(ISD::SETCC,              VT, Custom);
1128       setOperationAction(ISD::CTPOP,              VT, Custom);
1129       setOperationAction(ISD::ABS,                VT, Custom);
1130 
1131       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1132       // setcc all the way to isel and prefer SETGT in some isel patterns.
1133       setCondCodeAction(ISD::SETLT, VT, Custom);
1134       setCondCodeAction(ISD::SETLE, VT, Custom);
1135     }
1136 
1137     setOperationAction(ISD::SETCC,          MVT::v2f64, Custom);
1138     setOperationAction(ISD::SETCC,          MVT::v4f32, Custom);
1139     setOperationAction(ISD::STRICT_FSETCC,  MVT::v2f64, Custom);
1140     setOperationAction(ISD::STRICT_FSETCC,  MVT::v4f32, Custom);
1141     setOperationAction(ISD::STRICT_FSETCCS, MVT::v2f64, Custom);
1142     setOperationAction(ISD::STRICT_FSETCCS, MVT::v4f32, Custom);
1143 
1144     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1145       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1146       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1147       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1148       setOperationAction(ISD::VSELECT,            VT, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1150     }
1151 
1152     for (auto VT : { MVT::v8f16, MVT::v2f64, MVT::v2i64 }) {
1153       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1154       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1155       setOperationAction(ISD::VSELECT,            VT, Custom);
1156 
1157       if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1158         continue;
1159 
1160       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1161       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1162     }
1163     setF16Action(MVT::v8f16, Expand);
1164     setOperationAction(ISD::FADD, MVT::v8f16, Expand);
1165     setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
1166     setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
1167     setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
1168 
1169     // Custom lower v2i64 and v2f64 selects.
1170     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1171     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1172     setOperationAction(ISD::SELECT,             MVT::v4i32, Custom);
1173     setOperationAction(ISD::SELECT,             MVT::v8i16, Custom);
1174     setOperationAction(ISD::SELECT,             MVT::v8f16, Custom);
1175     setOperationAction(ISD::SELECT,             MVT::v16i8, Custom);
1176 
1177     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Custom);
1178     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Custom);
1179     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
1180     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i32, Custom);
1181     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v4i32, Custom);
1182     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v2i32, Custom);
1183 
1184     // Custom legalize these to avoid over promotion or custom promotion.
1185     for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1186       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
1187       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
1188       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1189       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1190     }
1191 
1192     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Custom);
1193     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v4i32, Custom);
1194     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
1195     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2i32, Custom);
1196 
1197     setOperationAction(ISD::UINT_TO_FP,         MVT::v2i32, Custom);
1198     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2i32, Custom);
1199 
1200     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
1201     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v4i32, Custom);
1202 
1203     // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1204     setOperationAction(ISD::SINT_TO_FP,         MVT::v2f32, Custom);
1205     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2f32, Custom);
1206     setOperationAction(ISD::UINT_TO_FP,         MVT::v2f32, Custom);
1207     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2f32, Custom);
1208 
1209     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1210     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v2f32, Custom);
1211     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1212     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v2f32, Custom);
1213 
1214     // We want to legalize this to an f64 load rather than an i64 load on
1215     // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1216     // store.
1217     setOperationAction(ISD::LOAD,               MVT::v2i32, Custom);
1218     setOperationAction(ISD::LOAD,               MVT::v4i16, Custom);
1219     setOperationAction(ISD::LOAD,               MVT::v8i8,  Custom);
1220     setOperationAction(ISD::STORE,              MVT::v2i32, Custom);
1221     setOperationAction(ISD::STORE,              MVT::v4i16, Custom);
1222     setOperationAction(ISD::STORE,              MVT::v8i8,  Custom);
1223 
1224     // Add 32-bit vector stores to help vectorization opportunities.
1225     setOperationAction(ISD::STORE,              MVT::v2i16, Custom);
1226     setOperationAction(ISD::STORE,              MVT::v4i8,  Custom);
1227 
1228     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1229     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1230     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1231     if (!Subtarget.hasAVX512())
1232       setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1233 
1234     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1235     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1236     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1237 
1238     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1239 
1240     setOperationAction(ISD::TRUNCATE,    MVT::v2i8,  Custom);
1241     setOperationAction(ISD::TRUNCATE,    MVT::v2i16, Custom);
1242     setOperationAction(ISD::TRUNCATE,    MVT::v2i32, Custom);
1243     setOperationAction(ISD::TRUNCATE,    MVT::v2i64, Custom);
1244     setOperationAction(ISD::TRUNCATE,    MVT::v4i8,  Custom);
1245     setOperationAction(ISD::TRUNCATE,    MVT::v4i16, Custom);
1246     setOperationAction(ISD::TRUNCATE,    MVT::v4i32, Custom);
1247     setOperationAction(ISD::TRUNCATE,    MVT::v4i64, Custom);
1248     setOperationAction(ISD::TRUNCATE,    MVT::v8i8,  Custom);
1249     setOperationAction(ISD::TRUNCATE,    MVT::v8i16, Custom);
1250     setOperationAction(ISD::TRUNCATE,    MVT::v8i32, Custom);
1251     setOperationAction(ISD::TRUNCATE,    MVT::v8i64, Custom);
1252     setOperationAction(ISD::TRUNCATE,    MVT::v16i8, Custom);
1253     setOperationAction(ISD::TRUNCATE,    MVT::v16i16, Custom);
1254     setOperationAction(ISD::TRUNCATE,    MVT::v16i32, Custom);
1255     setOperationAction(ISD::TRUNCATE,    MVT::v16i64, Custom);
1256 
1257     // In the customized shift lowering, the legal v4i32/v2i64 cases
1258     // in AVX2 will be recognized.
1259     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1260       setOperationAction(ISD::SRL,              VT, Custom);
1261       setOperationAction(ISD::SHL,              VT, Custom);
1262       setOperationAction(ISD::SRA,              VT, Custom);
1263       if (VT == MVT::v2i64) continue;
1264       setOperationAction(ISD::ROTL,             VT, Custom);
1265       setOperationAction(ISD::ROTR,             VT, Custom);
1266       setOperationAction(ISD::FSHL,             VT, Custom);
1267       setOperationAction(ISD::FSHR,             VT, Custom);
1268     }
1269 
1270     setOperationAction(ISD::STRICT_FSQRT,       MVT::v2f64, Legal);
1271     setOperationAction(ISD::STRICT_FADD,        MVT::v2f64, Legal);
1272     setOperationAction(ISD::STRICT_FSUB,        MVT::v2f64, Legal);
1273     setOperationAction(ISD::STRICT_FMUL,        MVT::v2f64, Legal);
1274     setOperationAction(ISD::STRICT_FDIV,        MVT::v2f64, Legal);
1275   }
1276 
1277   if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1278     setOperationAction(ISD::ABS,                MVT::v16i8, Legal);
1279     setOperationAction(ISD::ABS,                MVT::v8i16, Legal);
1280     setOperationAction(ISD::ABS,                MVT::v4i32, Legal);
1281     setOperationAction(ISD::BITREVERSE,         MVT::v16i8, Custom);
1282     setOperationAction(ISD::CTLZ,               MVT::v16i8, Custom);
1283     setOperationAction(ISD::CTLZ,               MVT::v8i16, Custom);
1284     setOperationAction(ISD::CTLZ,               MVT::v4i32, Custom);
1285     setOperationAction(ISD::CTLZ,               MVT::v2i64, Custom);
1286 
1287     // These might be better off as horizontal vector ops.
1288     setOperationAction(ISD::ADD,                MVT::i16, Custom);
1289     setOperationAction(ISD::ADD,                MVT::i32, Custom);
1290     setOperationAction(ISD::SUB,                MVT::i16, Custom);
1291     setOperationAction(ISD::SUB,                MVT::i32, Custom);
1292   }
1293 
1294   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1295     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1296       setOperationAction(ISD::FFLOOR,            RoundedTy,  Legal);
1297       setOperationAction(ISD::STRICT_FFLOOR,     RoundedTy,  Legal);
1298       setOperationAction(ISD::FCEIL,             RoundedTy,  Legal);
1299       setOperationAction(ISD::STRICT_FCEIL,      RoundedTy,  Legal);
1300       setOperationAction(ISD::FTRUNC,            RoundedTy,  Legal);
1301       setOperationAction(ISD::STRICT_FTRUNC,     RoundedTy,  Legal);
1302       setOperationAction(ISD::FRINT,             RoundedTy,  Legal);
1303       setOperationAction(ISD::STRICT_FRINT,      RoundedTy,  Legal);
1304       setOperationAction(ISD::FNEARBYINT,        RoundedTy,  Legal);
1305       setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy,  Legal);
1306       setOperationAction(ISD::FROUNDEVEN,        RoundedTy,  Legal);
1307       setOperationAction(ISD::STRICT_FROUNDEVEN, RoundedTy,  Legal);
1308 
1309       setOperationAction(ISD::FROUND,            RoundedTy,  Custom);
1310     }
1311 
1312     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
1313     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
1314     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
1315     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
1316     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
1317     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
1318     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
1319     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
1320 
1321     for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1322       setOperationAction(ISD::ABDS,             VT, Custom);
1323       setOperationAction(ISD::ABDU,             VT, Custom);
1324     }
1325 
1326     setOperationAction(ISD::UADDSAT,            MVT::v4i32, Custom);
1327     setOperationAction(ISD::SADDSAT,            MVT::v2i64, Custom);
1328     setOperationAction(ISD::SSUBSAT,            MVT::v2i64, Custom);
1329 
1330     // FIXME: Do we need to handle scalar-to-vector here?
1331     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1332     setOperationAction(ISD::SMULO,              MVT::v2i32, Custom);
1333 
1334     // We directly match byte blends in the backend as they match the VSELECT
1335     // condition form.
1336     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1337 
1338     // SSE41 brings specific instructions for doing vector sign extend even in
1339     // cases where we don't have SRA.
1340     for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1341       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1342       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1343     }
1344 
1345     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1346     for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1347       setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8,  Legal);
1348       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8,  Legal);
1349       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8,  Legal);
1350       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1351       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1352       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1353     }
1354 
1355     if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1356       // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1357       // do the pre and post work in the vector domain.
1358       setOperationAction(ISD::UINT_TO_FP,        MVT::v4i64, Custom);
1359       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1360       // We need to mark SINT_TO_FP as Custom even though we want to expand it
1361       // so that DAG combine doesn't try to turn it into uint_to_fp.
1362       setOperationAction(ISD::SINT_TO_FP,        MVT::v4i64, Custom);
1363       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1364     }
1365   }
1366 
1367   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1368     setOperationAction(ISD::UADDSAT,            MVT::v2i64, Custom);
1369   }
1370 
1371   if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1372     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1373                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1374       setOperationAction(ISD::ROTL, VT, Custom);
1375       setOperationAction(ISD::ROTR, VT, Custom);
1376     }
1377 
1378     // XOP can efficiently perform BITREVERSE with VPPERM.
1379     for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1380       setOperationAction(ISD::BITREVERSE, VT, Custom);
1381 
1382     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1383                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1384       setOperationAction(ISD::BITREVERSE, VT, Custom);
1385   }
1386 
1387   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1388     bool HasInt256 = Subtarget.hasInt256();
1389 
1390     addRegisterClass(MVT::v32i8,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1391                                                      : &X86::VR256RegClass);
1392     addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1393                                                      : &X86::VR256RegClass);
1394     addRegisterClass(MVT::v16f16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1395                                                      : &X86::VR256RegClass);
1396     addRegisterClass(MVT::v8i32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1397                                                      : &X86::VR256RegClass);
1398     addRegisterClass(MVT::v8f32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1399                                                      : &X86::VR256RegClass);
1400     addRegisterClass(MVT::v4i64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1401                                                      : &X86::VR256RegClass);
1402     addRegisterClass(MVT::v4f64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1403                                                      : &X86::VR256RegClass);
1404 
1405     for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1406       setOperationAction(ISD::FFLOOR,            VT, Legal);
1407       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1408       setOperationAction(ISD::FCEIL,             VT, Legal);
1409       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1410       setOperationAction(ISD::FTRUNC,            VT, Legal);
1411       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1412       setOperationAction(ISD::FRINT,             VT, Legal);
1413       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1414       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1415       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1416       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1417       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1418 
1419       setOperationAction(ISD::FROUND,            VT, Custom);
1420 
1421       setOperationAction(ISD::FNEG,              VT, Custom);
1422       setOperationAction(ISD::FABS,              VT, Custom);
1423       setOperationAction(ISD::FCOPYSIGN,         VT, Custom);
1424 
1425       setOperationAction(ISD::FMAXIMUM,          VT, Custom);
1426       setOperationAction(ISD::FMINIMUM,          VT, Custom);
1427     }
1428 
1429     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1430     // even though v8i16 is a legal type.
1431     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i16, MVT::v8i32);
1432     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i16, MVT::v8i32);
1433     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1434     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1435     setOperationAction(ISD::FP_TO_SINT,                MVT::v8i32, Custom);
1436     setOperationAction(ISD::FP_TO_UINT,                MVT::v8i32, Custom);
1437     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v8i32, Custom);
1438 
1439     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Custom);
1440     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i32, Custom);
1441     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Expand);
1442     setOperationAction(ISD::FP_ROUND,           MVT::v8f16, Expand);
1443     setOperationAction(ISD::FP_EXTEND,          MVT::v4f64, Custom);
1444     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Custom);
1445 
1446     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v4f32, Legal);
1447     setOperationAction(ISD::STRICT_FADD,        MVT::v8f32, Legal);
1448     setOperationAction(ISD::STRICT_FADD,        MVT::v4f64, Legal);
1449     setOperationAction(ISD::STRICT_FSUB,        MVT::v8f32, Legal);
1450     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f64, Legal);
1451     setOperationAction(ISD::STRICT_FMUL,        MVT::v8f32, Legal);
1452     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f64, Legal);
1453     setOperationAction(ISD::STRICT_FDIV,        MVT::v8f32, Legal);
1454     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f64, Legal);
1455     setOperationAction(ISD::STRICT_FSQRT,       MVT::v8f32, Legal);
1456     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f64, Legal);
1457 
1458     if (!Subtarget.hasAVX512())
1459       setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1460 
1461     // In the customized shift lowering, the legal v8i32/v4i64 cases
1462     // in AVX2 will be recognized.
1463     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1464       setOperationAction(ISD::SRL,             VT, Custom);
1465       setOperationAction(ISD::SHL,             VT, Custom);
1466       setOperationAction(ISD::SRA,             VT, Custom);
1467       setOperationAction(ISD::ABDS,            VT, Custom);
1468       setOperationAction(ISD::ABDU,            VT, Custom);
1469       if (VT == MVT::v4i64) continue;
1470       setOperationAction(ISD::ROTL,            VT, Custom);
1471       setOperationAction(ISD::ROTR,            VT, Custom);
1472       setOperationAction(ISD::FSHL,            VT, Custom);
1473       setOperationAction(ISD::FSHR,            VT, Custom);
1474     }
1475 
1476     // These types need custom splitting if their input is a 128-bit vector.
1477     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i64,  Custom);
1478     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i32, Custom);
1479     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i64,  Custom);
1480     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i32, Custom);
1481 
1482     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1483     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1484     setOperationAction(ISD::SELECT,            MVT::v8i32, Custom);
1485     setOperationAction(ISD::SELECT,            MVT::v16i16, Custom);
1486     setOperationAction(ISD::SELECT,            MVT::v16f16, Custom);
1487     setOperationAction(ISD::SELECT,            MVT::v32i8, Custom);
1488     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1489 
1490     for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1491       setOperationAction(ISD::SIGN_EXTEND,     VT, Custom);
1492       setOperationAction(ISD::ZERO_EXTEND,     VT, Custom);
1493       setOperationAction(ISD::ANY_EXTEND,      VT, Custom);
1494     }
1495 
1496     setOperationAction(ISD::TRUNCATE,          MVT::v32i8, Custom);
1497     setOperationAction(ISD::TRUNCATE,          MVT::v32i16, Custom);
1498     setOperationAction(ISD::TRUNCATE,          MVT::v32i32, Custom);
1499     setOperationAction(ISD::TRUNCATE,          MVT::v32i64, Custom);
1500 
1501     setOperationAction(ISD::BITREVERSE,        MVT::v32i8, Custom);
1502 
1503     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1504       setOperationAction(ISD::SETCC,           VT, Custom);
1505       setOperationAction(ISD::CTPOP,           VT, Custom);
1506       setOperationAction(ISD::CTLZ,            VT, Custom);
1507 
1508       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1509       // setcc all the way to isel and prefer SETGT in some isel patterns.
1510       setCondCodeAction(ISD::SETLT, VT, Custom);
1511       setCondCodeAction(ISD::SETLE, VT, Custom);
1512     }
1513 
1514     setOperationAction(ISD::SETCC,          MVT::v4f64, Custom);
1515     setOperationAction(ISD::SETCC,          MVT::v8f32, Custom);
1516     setOperationAction(ISD::STRICT_FSETCC,  MVT::v4f64, Custom);
1517     setOperationAction(ISD::STRICT_FSETCC,  MVT::v8f32, Custom);
1518     setOperationAction(ISD::STRICT_FSETCCS, MVT::v4f64, Custom);
1519     setOperationAction(ISD::STRICT_FSETCCS, MVT::v8f32, Custom);
1520 
1521     if (Subtarget.hasAnyFMA()) {
1522       for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1523                        MVT::v2f64, MVT::v4f64 }) {
1524         setOperationAction(ISD::FMA, VT, Legal);
1525         setOperationAction(ISD::STRICT_FMA, VT, Legal);
1526       }
1527     }
1528 
1529     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1530       setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1531       setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1532     }
1533 
1534     setOperationAction(ISD::MUL,       MVT::v4i64,  Custom);
1535     setOperationAction(ISD::MUL,       MVT::v8i32,  HasInt256 ? Legal : Custom);
1536     setOperationAction(ISD::MUL,       MVT::v16i16, HasInt256 ? Legal : Custom);
1537     setOperationAction(ISD::MUL,       MVT::v32i8,  Custom);
1538 
1539     setOperationAction(ISD::MULHU,     MVT::v8i32,  Custom);
1540     setOperationAction(ISD::MULHS,     MVT::v8i32,  Custom);
1541     setOperationAction(ISD::MULHU,     MVT::v16i16, HasInt256 ? Legal : Custom);
1542     setOperationAction(ISD::MULHS,     MVT::v16i16, HasInt256 ? Legal : Custom);
1543     setOperationAction(ISD::MULHU,     MVT::v32i8,  Custom);
1544     setOperationAction(ISD::MULHS,     MVT::v32i8,  Custom);
1545     setOperationAction(ISD::AVGCEILU,  MVT::v16i16, HasInt256 ? Legal : Custom);
1546     setOperationAction(ISD::AVGCEILU,  MVT::v32i8,  HasInt256 ? Legal : Custom);
1547 
1548     setOperationAction(ISD::SMULO,     MVT::v32i8, Custom);
1549     setOperationAction(ISD::UMULO,     MVT::v32i8, Custom);
1550 
1551     setOperationAction(ISD::ABS,       MVT::v4i64,  Custom);
1552     setOperationAction(ISD::SMAX,      MVT::v4i64,  Custom);
1553     setOperationAction(ISD::UMAX,      MVT::v4i64,  Custom);
1554     setOperationAction(ISD::SMIN,      MVT::v4i64,  Custom);
1555     setOperationAction(ISD::UMIN,      MVT::v4i64,  Custom);
1556 
1557     setOperationAction(ISD::UADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1558     setOperationAction(ISD::SADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1559     setOperationAction(ISD::USUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1560     setOperationAction(ISD::SSUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1561     setOperationAction(ISD::UADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1562     setOperationAction(ISD::SADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1563     setOperationAction(ISD::USUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1564     setOperationAction(ISD::SSUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1565     setOperationAction(ISD::UADDSAT,   MVT::v8i32, Custom);
1566     setOperationAction(ISD::USUBSAT,   MVT::v8i32, Custom);
1567     setOperationAction(ISD::UADDSAT,   MVT::v4i64, Custom);
1568     setOperationAction(ISD::USUBSAT,   MVT::v4i64, Custom);
1569 
1570     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1571       setOperationAction(ISD::ABS,  VT, HasInt256 ? Legal : Custom);
1572       setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1573       setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1574       setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1575       setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1576     }
1577 
1578     for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1579       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1580       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1581     }
1582 
1583     if (HasInt256) {
1584       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1585       // when we have a 256bit-wide blend with immediate.
1586       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1587       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1588 
1589       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1590       for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1591         setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1592         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i8,  Legal);
1593         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i8,  Legal);
1594         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i16, Legal);
1595         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i16, Legal);
1596         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i32, Legal);
1597       }
1598     }
1599 
1600     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1601                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1602       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1603       setOperationAction(ISD::MSTORE, VT, Legal);
1604     }
1605 
1606     // Extract subvector is special because the value type
1607     // (result) is 128-bit but the source is 256-bit wide.
1608     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1609                      MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1610       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1611     }
1612 
1613     // Custom lower several nodes for 256-bit types.
1614     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1615                     MVT::v16f16, MVT::v8f32, MVT::v4f64 }) {
1616       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1617       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1618       setOperationAction(ISD::VSELECT,            VT, Custom);
1619       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1620       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1621       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1622       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1623       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1624       setOperationAction(ISD::STORE,              VT, Custom);
1625     }
1626     setF16Action(MVT::v16f16, Expand);
1627     setOperationAction(ISD::FADD, MVT::v16f16, Expand);
1628     setOperationAction(ISD::FSUB, MVT::v16f16, Expand);
1629     setOperationAction(ISD::FMUL, MVT::v16f16, Expand);
1630     setOperationAction(ISD::FDIV, MVT::v16f16, Expand);
1631 
1632     if (HasInt256) {
1633       setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1634 
1635       // Custom legalize 2x32 to get a little better code.
1636       setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1637       setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1638 
1639       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1640                        MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1641         setOperationAction(ISD::MGATHER,  VT, Custom);
1642     }
1643   }
1644 
1645   if (!Subtarget.useSoftFloat() && !Subtarget.hasFP16() &&
1646       Subtarget.hasF16C()) {
1647     for (MVT VT : { MVT::f16, MVT::v2f16, MVT::v4f16, MVT::v8f16 }) {
1648       setOperationAction(ISD::FP_ROUND,           VT, Custom);
1649       setOperationAction(ISD::STRICT_FP_ROUND,    VT, Custom);
1650     }
1651     for (MVT VT : { MVT::f32, MVT::v2f32, MVT::v4f32, MVT::v8f32 }) {
1652       setOperationAction(ISD::FP_EXTEND,          VT, Custom);
1653       setOperationAction(ISD::STRICT_FP_EXTEND,   VT, Custom);
1654     }
1655     for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1656       setOperationPromotedToType(Opc, MVT::v8f16, MVT::v8f32);
1657       setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1658     }
1659   }
1660 
1661   // This block controls legalization of the mask vector sizes that are
1662   // available with AVX512. 512-bit vectors are in a separate block controlled
1663   // by useAVX512Regs.
1664   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1665     addRegisterClass(MVT::v1i1,   &X86::VK1RegClass);
1666     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1667     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1668     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1669     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1670 
1671     setOperationAction(ISD::SELECT,             MVT::v1i1, Custom);
1672     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1673     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i1, Custom);
1674 
1675     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i1,  MVT::v8i32);
1676     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i1,  MVT::v8i32);
1677     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v4i1,  MVT::v4i32);
1678     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v4i1,  MVT::v4i32);
1679     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1,  MVT::v8i32);
1680     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1,  MVT::v8i32);
1681     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1,  MVT::v4i32);
1682     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1,  MVT::v4i32);
1683     setOperationAction(ISD::FP_TO_SINT,                MVT::v2i1,  Custom);
1684     setOperationAction(ISD::FP_TO_UINT,                MVT::v2i1,  Custom);
1685     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v2i1,  Custom);
1686     setOperationAction(ISD::STRICT_FP_TO_UINT,         MVT::v2i1,  Custom);
1687 
1688     // There is no byte sized k-register load or store without AVX512DQ.
1689     if (!Subtarget.hasDQI()) {
1690       setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1691       setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1692       setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1693       setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1694 
1695       setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1696       setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1697       setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1698       setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1699     }
1700 
1701     // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1702     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1703       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1704       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1705       setOperationAction(ISD::ANY_EXTEND,  VT, Custom);
1706     }
1707 
1708     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1709       setOperationAction(ISD::VSELECT,          VT, Expand);
1710 
1711     for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1712       setOperationAction(ISD::SETCC,            VT, Custom);
1713       setOperationAction(ISD::SELECT,           VT, Custom);
1714       setOperationAction(ISD::TRUNCATE,         VT, Custom);
1715 
1716       setOperationAction(ISD::BUILD_VECTOR,     VT, Custom);
1717       setOperationAction(ISD::CONCAT_VECTORS,   VT, Custom);
1718       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1719       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1720       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1721       setOperationAction(ISD::VECTOR_SHUFFLE,   VT,  Custom);
1722     }
1723 
1724     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1725       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1726   }
1727 
1728   // This block controls legalization for 512-bit operations with 8/16/32/64 bit
1729   // elements. 512-bits can be disabled based on prefer-vector-width and
1730   // required-vector-width function attributes.
1731   if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1732     bool HasBWI = Subtarget.hasBWI();
1733 
1734     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1735     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1736     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1737     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1738     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1739     addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1740     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1741 
1742     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1743       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8,  Legal);
1744       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1745       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i8,   Legal);
1746       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i16,  Legal);
1747       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i32,  Legal);
1748       if (HasBWI)
1749         setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1750     }
1751 
1752     for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1753       setOperationAction(ISD::FMAXIMUM, VT, Custom);
1754       setOperationAction(ISD::FMINIMUM, VT, Custom);
1755       setOperationAction(ISD::FNEG,  VT, Custom);
1756       setOperationAction(ISD::FABS,  VT, Custom);
1757       setOperationAction(ISD::FMA,   VT, Legal);
1758       setOperationAction(ISD::STRICT_FMA, VT, Legal);
1759       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1760     }
1761 
1762     for (MVT VT : { MVT::v16i1, MVT::v16i8 }) {
1763       setOperationPromotedToType(ISD::FP_TO_SINT       , VT, MVT::v16i32);
1764       setOperationPromotedToType(ISD::FP_TO_UINT       , VT, MVT::v16i32);
1765       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1766       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1767     }
1768 
1769     for (MVT VT : { MVT::v16i16, MVT::v16i32 }) {
1770       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
1771       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
1772       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1773       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1774     }
1775 
1776     setOperationAction(ISD::SINT_TO_FP,        MVT::v16i32, Custom);
1777     setOperationAction(ISD::UINT_TO_FP,        MVT::v16i32, Custom);
1778     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Custom);
1779     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Custom);
1780     setOperationAction(ISD::FP_EXTEND,         MVT::v8f64,  Custom);
1781     setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v8f64,  Custom);
1782 
1783     setOperationAction(ISD::STRICT_FADD,      MVT::v16f32, Legal);
1784     setOperationAction(ISD::STRICT_FADD,      MVT::v8f64,  Legal);
1785     setOperationAction(ISD::STRICT_FSUB,      MVT::v16f32, Legal);
1786     setOperationAction(ISD::STRICT_FSUB,      MVT::v8f64,  Legal);
1787     setOperationAction(ISD::STRICT_FMUL,      MVT::v16f32, Legal);
1788     setOperationAction(ISD::STRICT_FMUL,      MVT::v8f64,  Legal);
1789     setOperationAction(ISD::STRICT_FDIV,      MVT::v16f32, Legal);
1790     setOperationAction(ISD::STRICT_FDIV,      MVT::v8f64,  Legal);
1791     setOperationAction(ISD::STRICT_FSQRT,     MVT::v16f32, Legal);
1792     setOperationAction(ISD::STRICT_FSQRT,     MVT::v8f64,  Legal);
1793     setOperationAction(ISD::STRICT_FP_ROUND,  MVT::v8f32,  Legal);
1794 
1795     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1796     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1797     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1798     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1799     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1800     if (HasBWI)
1801       setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1802 
1803     // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1804     // to 512-bit rather than use the AVX2 instructions so that we can use
1805     // k-masks.
1806     if (!Subtarget.hasVLX()) {
1807       for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1808            MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1809         setOperationAction(ISD::MLOAD,  VT, Custom);
1810         setOperationAction(ISD::MSTORE, VT, Custom);
1811       }
1812     }
1813 
1814     setOperationAction(ISD::TRUNCATE,    MVT::v8i32,  Legal);
1815     setOperationAction(ISD::TRUNCATE,    MVT::v16i16, Legal);
1816     setOperationAction(ISD::TRUNCATE,    MVT::v32i8,  HasBWI ? Legal : Custom);
1817     setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1818     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1819     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
1820     setOperationAction(ISD::ANY_EXTEND,  MVT::v32i16, Custom);
1821     setOperationAction(ISD::ANY_EXTEND,  MVT::v16i32, Custom);
1822     setOperationAction(ISD::ANY_EXTEND,  MVT::v8i64,  Custom);
1823     setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1824     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1825     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
1826 
1827     if (HasBWI) {
1828       // Extends from v64i1 masks to 512-bit vectors.
1829       setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1830       setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1831       setOperationAction(ISD::ANY_EXTEND,         MVT::v64i8, Custom);
1832     }
1833 
1834     for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1835       setOperationAction(ISD::FFLOOR,            VT, Legal);
1836       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1837       setOperationAction(ISD::FCEIL,             VT, Legal);
1838       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1839       setOperationAction(ISD::FTRUNC,            VT, Legal);
1840       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1841       setOperationAction(ISD::FRINT,             VT, Legal);
1842       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1843       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1844       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1845       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1846       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1847 
1848       setOperationAction(ISD::FROUND,            VT, Custom);
1849     }
1850 
1851     for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1852       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1853       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1854     }
1855 
1856     setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1857     setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1858     setOperationAction(ISD::ADD, MVT::v64i8,  HasBWI ? Legal : Custom);
1859     setOperationAction(ISD::SUB, MVT::v64i8,  HasBWI ? Legal : Custom);
1860 
1861     setOperationAction(ISD::MUL, MVT::v8i64,  Custom);
1862     setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1863     setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1864     setOperationAction(ISD::MUL, MVT::v64i8,  Custom);
1865 
1866     setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1867     setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1868     setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1869     setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1870     setOperationAction(ISD::MULHS, MVT::v64i8,  Custom);
1871     setOperationAction(ISD::MULHU, MVT::v64i8,  Custom);
1872     setOperationAction(ISD::AVGCEILU, MVT::v32i16, HasBWI ? Legal : Custom);
1873     setOperationAction(ISD::AVGCEILU, MVT::v64i8,  HasBWI ? Legal : Custom);
1874 
1875     setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
1876     setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
1877 
1878     setOperationAction(ISD::BITREVERSE, MVT::v64i8,  Custom);
1879 
1880     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1881       setOperationAction(ISD::SRL,              VT, Custom);
1882       setOperationAction(ISD::SHL,              VT, Custom);
1883       setOperationAction(ISD::SRA,              VT, Custom);
1884       setOperationAction(ISD::ROTL,             VT, Custom);
1885       setOperationAction(ISD::ROTR,             VT, Custom);
1886       setOperationAction(ISD::SETCC,            VT, Custom);
1887       setOperationAction(ISD::ABDS,             VT, Custom);
1888       setOperationAction(ISD::ABDU,             VT, Custom);
1889 
1890       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1891       // setcc all the way to isel and prefer SETGT in some isel patterns.
1892       setCondCodeAction(ISD::SETLT, VT, Custom);
1893       setCondCodeAction(ISD::SETLE, VT, Custom);
1894     }
1895 
1896     setOperationAction(ISD::SETCC,          MVT::v8f64, Custom);
1897     setOperationAction(ISD::SETCC,          MVT::v16f32, Custom);
1898     setOperationAction(ISD::STRICT_FSETCC,  MVT::v8f64, Custom);
1899     setOperationAction(ISD::STRICT_FSETCC,  MVT::v16f32, Custom);
1900     setOperationAction(ISD::STRICT_FSETCCS, MVT::v8f64, Custom);
1901     setOperationAction(ISD::STRICT_FSETCCS, MVT::v16f32, Custom);
1902 
1903     for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1904       setOperationAction(ISD::SMAX,             VT, Legal);
1905       setOperationAction(ISD::UMAX,             VT, Legal);
1906       setOperationAction(ISD::SMIN,             VT, Legal);
1907       setOperationAction(ISD::UMIN,             VT, Legal);
1908       setOperationAction(ISD::ABS,              VT, Legal);
1909       setOperationAction(ISD::CTPOP,            VT, Custom);
1910     }
1911 
1912     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1913       setOperationAction(ISD::ABS,     VT, HasBWI ? Legal : Custom);
1914       setOperationAction(ISD::CTPOP,   VT, Subtarget.hasBITALG() ? Legal : Custom);
1915       setOperationAction(ISD::CTLZ,    VT, Custom);
1916       setOperationAction(ISD::SMAX,    VT, HasBWI ? Legal : Custom);
1917       setOperationAction(ISD::UMAX,    VT, HasBWI ? Legal : Custom);
1918       setOperationAction(ISD::SMIN,    VT, HasBWI ? Legal : Custom);
1919       setOperationAction(ISD::UMIN,    VT, HasBWI ? Legal : Custom);
1920       setOperationAction(ISD::UADDSAT, VT, HasBWI ? Legal : Custom);
1921       setOperationAction(ISD::SADDSAT, VT, HasBWI ? Legal : Custom);
1922       setOperationAction(ISD::USUBSAT, VT, HasBWI ? Legal : Custom);
1923       setOperationAction(ISD::SSUBSAT, VT, HasBWI ? Legal : Custom);
1924     }
1925 
1926     setOperationAction(ISD::FSHL,       MVT::v64i8, Custom);
1927     setOperationAction(ISD::FSHR,       MVT::v64i8, Custom);
1928     setOperationAction(ISD::FSHL,      MVT::v32i16, Custom);
1929     setOperationAction(ISD::FSHR,      MVT::v32i16, Custom);
1930     setOperationAction(ISD::FSHL,      MVT::v16i32, Custom);
1931     setOperationAction(ISD::FSHR,      MVT::v16i32, Custom);
1932 
1933     if (Subtarget.hasDQI()) {
1934       for (auto Opc : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
1935                        ISD::STRICT_UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1936                        ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT})
1937         setOperationAction(Opc,           MVT::v8i64, Custom);
1938       setOperationAction(ISD::MUL,        MVT::v8i64, Legal);
1939     }
1940 
1941     if (Subtarget.hasCDI()) {
1942       // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1943       for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1944         setOperationAction(ISD::CTLZ,            VT, Legal);
1945       }
1946     } // Subtarget.hasCDI()
1947 
1948     if (Subtarget.hasVPOPCNTDQ()) {
1949       for (auto VT : { MVT::v16i32, MVT::v8i64 })
1950         setOperationAction(ISD::CTPOP, VT, Legal);
1951     }
1952 
1953     // Extract subvector is special because the value type
1954     // (result) is 256-bit but the source is 512-bit wide.
1955     // 128-bit was made Legal under AVX1.
1956     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1957                      MVT::v16f16, MVT::v8f32, MVT::v4f64 })
1958       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1959 
1960     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
1961                      MVT::v32f16, MVT::v16f32, MVT::v8f64 }) {
1962       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1963       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1964       setOperationAction(ISD::SELECT,             VT, Custom);
1965       setOperationAction(ISD::VSELECT,            VT, Custom);
1966       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1967       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1968       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1969       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1970       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1971     }
1972     setF16Action(MVT::v32f16, Expand);
1973     setOperationAction(ISD::FP_ROUND, MVT::v16f16, Custom);
1974     setOperationAction(ISD::STRICT_FP_ROUND, MVT::v16f16, Custom);
1975     setOperationAction(ISD::FP_EXTEND, MVT::v16f32, Custom);
1976     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v16f32, Custom);
1977     for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1978       setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1979       setOperationPromotedToType(Opc, MVT::v32f16, MVT::v32f32);
1980     }
1981 
1982     for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1983       setOperationAction(ISD::MLOAD,               VT, Legal);
1984       setOperationAction(ISD::MSTORE,              VT, Legal);
1985       setOperationAction(ISD::MGATHER,             VT, Custom);
1986       setOperationAction(ISD::MSCATTER,            VT, Custom);
1987     }
1988     if (HasBWI) {
1989       for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1990         setOperationAction(ISD::MLOAD,        VT, Legal);
1991         setOperationAction(ISD::MSTORE,       VT, Legal);
1992       }
1993     } else {
1994       setOperationAction(ISD::STORE, MVT::v32i16, Custom);
1995       setOperationAction(ISD::STORE, MVT::v64i8,  Custom);
1996     }
1997 
1998     if (Subtarget.hasVBMI2()) {
1999       for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
2000                        MVT::v16i16, MVT::v8i32, MVT::v4i64,
2001                        MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
2002         setOperationAction(ISD::FSHL, VT, Custom);
2003         setOperationAction(ISD::FSHR, VT, Custom);
2004       }
2005 
2006       setOperationAction(ISD::ROTL, MVT::v32i16, Custom);
2007       setOperationAction(ISD::ROTR, MVT::v8i16,  Custom);
2008       setOperationAction(ISD::ROTR, MVT::v16i16, Custom);
2009       setOperationAction(ISD::ROTR, MVT::v32i16, Custom);
2010     }
2011   }// useAVX512Regs
2012 
2013   // This block controls legalization for operations that don't have
2014   // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
2015   // narrower widths.
2016   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
2017     // These operations are handled on non-VLX by artificially widening in
2018     // isel patterns.
2019 
2020     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v8i32, Custom);
2021     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v4i32, Custom);
2022     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v2i32, Custom);
2023 
2024     if (Subtarget.hasDQI()) {
2025       // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
2026       // v2f32 UINT_TO_FP is already custom under SSE2.
2027       assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
2028              isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&
2029              "Unexpected operation action!");
2030       // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
2031       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f32, Custom);
2032       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f32, Custom);
2033       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
2034       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
2035     }
2036 
2037     for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
2038       setOperationAction(ISD::SMAX, VT, Legal);
2039       setOperationAction(ISD::UMAX, VT, Legal);
2040       setOperationAction(ISD::SMIN, VT, Legal);
2041       setOperationAction(ISD::UMIN, VT, Legal);
2042       setOperationAction(ISD::ABS,  VT, Legal);
2043     }
2044 
2045     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2046       setOperationAction(ISD::ROTL,     VT, Custom);
2047       setOperationAction(ISD::ROTR,     VT, Custom);
2048     }
2049 
2050     // Custom legalize 2x32 to get a little better code.
2051     setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
2052     setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
2053 
2054     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
2055                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
2056       setOperationAction(ISD::MSCATTER, VT, Custom);
2057 
2058     if (Subtarget.hasDQI()) {
2059       for (auto Opc : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
2060                        ISD::STRICT_UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
2061                        ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT}) {
2062         setOperationAction(Opc, MVT::v2i64, Custom);
2063         setOperationAction(Opc, MVT::v4i64, Custom);
2064       }
2065       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
2066       setOperationAction(ISD::MUL, MVT::v4i64, Legal);
2067     }
2068 
2069     if (Subtarget.hasCDI()) {
2070       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2071         setOperationAction(ISD::CTLZ,            VT, Legal);
2072       }
2073     } // Subtarget.hasCDI()
2074 
2075     if (Subtarget.hasVPOPCNTDQ()) {
2076       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
2077         setOperationAction(ISD::CTPOP, VT, Legal);
2078     }
2079   }
2080 
2081   // This block control legalization of v32i1/v64i1 which are available with
2082   // AVX512BW..
2083   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
2084     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
2085     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
2086 
2087     for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
2088       setOperationAction(ISD::VSELECT,            VT, Expand);
2089       setOperationAction(ISD::TRUNCATE,           VT, Custom);
2090       setOperationAction(ISD::SETCC,              VT, Custom);
2091       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2092       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
2093       setOperationAction(ISD::SELECT,             VT, Custom);
2094       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
2095       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
2096       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
2097       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
2098     }
2099 
2100     for (auto VT : { MVT::v16i1, MVT::v32i1 })
2101       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
2102 
2103     // Extends from v32i1 masks to 256-bit vectors.
2104     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
2105     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
2106     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i8, Custom);
2107 
2108     for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
2109       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
2110       setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
2111     }
2112 
2113     // These operations are handled on non-VLX by artificially widening in
2114     // isel patterns.
2115     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
2116 
2117     if (Subtarget.hasBITALG()) {
2118       for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
2119         setOperationAction(ISD::CTPOP, VT, Legal);
2120     }
2121   }
2122 
2123   if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
2124     auto setGroup = [&] (MVT VT) {
2125       setOperationAction(ISD::FADD,               VT, Legal);
2126       setOperationAction(ISD::STRICT_FADD,        VT, Legal);
2127       setOperationAction(ISD::FSUB,               VT, Legal);
2128       setOperationAction(ISD::STRICT_FSUB,        VT, Legal);
2129       setOperationAction(ISD::FMUL,               VT, Legal);
2130       setOperationAction(ISD::STRICT_FMUL,        VT, Legal);
2131       setOperationAction(ISD::FDIV,               VT, Legal);
2132       setOperationAction(ISD::STRICT_FDIV,        VT, Legal);
2133       setOperationAction(ISD::FSQRT,              VT, Legal);
2134       setOperationAction(ISD::STRICT_FSQRT,       VT, Legal);
2135 
2136       setOperationAction(ISD::FFLOOR,             VT, Legal);
2137       setOperationAction(ISD::STRICT_FFLOOR,      VT, Legal);
2138       setOperationAction(ISD::FCEIL,              VT, Legal);
2139       setOperationAction(ISD::STRICT_FCEIL,       VT, Legal);
2140       setOperationAction(ISD::FTRUNC,             VT, Legal);
2141       setOperationAction(ISD::STRICT_FTRUNC,      VT, Legal);
2142       setOperationAction(ISD::FRINT,              VT, Legal);
2143       setOperationAction(ISD::STRICT_FRINT,       VT, Legal);
2144       setOperationAction(ISD::FNEARBYINT,         VT, Legal);
2145       setOperationAction(ISD::STRICT_FNEARBYINT,  VT, Legal);
2146 
2147       setOperationAction(ISD::FROUND,             VT, Custom);
2148 
2149       setOperationAction(ISD::LOAD,               VT, Legal);
2150       setOperationAction(ISD::STORE,              VT, Legal);
2151 
2152       setOperationAction(ISD::FMA,                VT, Legal);
2153       setOperationAction(ISD::STRICT_FMA,         VT, Legal);
2154       setOperationAction(ISD::VSELECT,            VT, Legal);
2155       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
2156       setOperationAction(ISD::SELECT,             VT, Custom);
2157 
2158       setOperationAction(ISD::FNEG,               VT, Custom);
2159       setOperationAction(ISD::FABS,               VT, Custom);
2160       setOperationAction(ISD::FCOPYSIGN,          VT, Custom);
2161       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2162       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
2163 
2164       setOperationAction(ISD::SETCC,              VT, Custom);
2165       setOperationAction(ISD::STRICT_FSETCC,      VT, Custom);
2166       setOperationAction(ISD::STRICT_FSETCCS,     VT, Custom);
2167     };
2168 
2169     // AVX512_FP16 scalar operations
2170     setGroup(MVT::f16);
2171     setOperationAction(ISD::FREM,                 MVT::f16, Promote);
2172     setOperationAction(ISD::STRICT_FREM,          MVT::f16, Promote);
2173     setOperationAction(ISD::SELECT_CC,            MVT::f16, Expand);
2174     setOperationAction(ISD::BR_CC,                MVT::f16, Expand);
2175     setOperationAction(ISD::STRICT_FROUND,        MVT::f16, Promote);
2176     setOperationAction(ISD::FROUNDEVEN,           MVT::f16, Legal);
2177     setOperationAction(ISD::STRICT_FROUNDEVEN,    MVT::f16, Legal);
2178     setOperationAction(ISD::FP_ROUND,             MVT::f16, Custom);
2179     setOperationAction(ISD::STRICT_FP_ROUND,      MVT::f16, Custom);
2180     setOperationAction(ISD::FMAXIMUM,             MVT::f16, Custom);
2181     setOperationAction(ISD::FMINIMUM,             MVT::f16, Custom);
2182     setOperationAction(ISD::FP_EXTEND,            MVT::f32, Legal);
2183     setOperationAction(ISD::STRICT_FP_EXTEND,     MVT::f32, Legal);
2184 
2185     setCondCodeAction(ISD::SETOEQ, MVT::f16, Expand);
2186     setCondCodeAction(ISD::SETUNE, MVT::f16, Expand);
2187 
2188     if (Subtarget.useAVX512Regs()) {
2189       setGroup(MVT::v32f16);
2190       setOperationAction(ISD::SCALAR_TO_VECTOR,       MVT::v32f16, Custom);
2191       setOperationAction(ISD::SINT_TO_FP,             MVT::v32i16, Legal);
2192       setOperationAction(ISD::STRICT_SINT_TO_FP,      MVT::v32i16, Legal);
2193       setOperationAction(ISD::UINT_TO_FP,             MVT::v32i16, Legal);
2194       setOperationAction(ISD::STRICT_UINT_TO_FP,      MVT::v32i16, Legal);
2195       setOperationAction(ISD::FP_ROUND,               MVT::v16f16, Legal);
2196       setOperationAction(ISD::STRICT_FP_ROUND,        MVT::v16f16, Legal);
2197       setOperationAction(ISD::FP_EXTEND,              MVT::v16f32, Custom);
2198       setOperationAction(ISD::STRICT_FP_EXTEND,       MVT::v16f32, Legal);
2199       setOperationAction(ISD::FP_EXTEND,              MVT::v8f64,  Custom);
2200       setOperationAction(ISD::STRICT_FP_EXTEND,       MVT::v8f64,  Legal);
2201       setOperationAction(ISD::INSERT_VECTOR_ELT,      MVT::v32f16, Custom);
2202 
2203       setOperationAction(ISD::FP_TO_SINT,             MVT::v32i16, Custom);
2204       setOperationAction(ISD::STRICT_FP_TO_SINT,      MVT::v32i16, Custom);
2205       setOperationAction(ISD::FP_TO_UINT,             MVT::v32i16, Custom);
2206       setOperationAction(ISD::STRICT_FP_TO_UINT,      MVT::v32i16, Custom);
2207       setOperationPromotedToType(ISD::FP_TO_SINT,     MVT::v32i8,  MVT::v32i16);
2208       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i8,
2209                                  MVT::v32i16);
2210       setOperationPromotedToType(ISD::FP_TO_UINT,     MVT::v32i8,  MVT::v32i16);
2211       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i8,
2212                                  MVT::v32i16);
2213       setOperationPromotedToType(ISD::FP_TO_SINT,     MVT::v32i1,  MVT::v32i16);
2214       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i1,
2215                                  MVT::v32i16);
2216       setOperationPromotedToType(ISD::FP_TO_UINT,     MVT::v32i1,  MVT::v32i16);
2217       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i1,
2218                                  MVT::v32i16);
2219 
2220       setOperationAction(ISD::EXTRACT_SUBVECTOR,      MVT::v16f16, Legal);
2221       setOperationAction(ISD::INSERT_SUBVECTOR,       MVT::v32f16, Legal);
2222       setOperationAction(ISD::CONCAT_VECTORS,         MVT::v32f16, Custom);
2223 
2224       setLoadExtAction(ISD::EXTLOAD, MVT::v8f64,  MVT::v8f16,  Legal);
2225       setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2226     }
2227 
2228     if (Subtarget.hasVLX()) {
2229       setGroup(MVT::v8f16);
2230       setGroup(MVT::v16f16);
2231 
2232       setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8f16,  Legal);
2233       setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16f16, Custom);
2234       setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Legal);
2235       setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v16i16, Legal);
2236       setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16,  Legal);
2237       setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i16,  Legal);
2238       setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Legal);
2239       setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v16i16, Legal);
2240       setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16,  Legal);
2241       setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v8i16,  Legal);
2242 
2243       setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
2244       setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v8i16, Custom);
2245       setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Custom);
2246       setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v8i16, Custom);
2247       setOperationAction(ISD::FP_ROUND,           MVT::v8f16, Legal);
2248       setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v8f16, Legal);
2249       setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Custom);
2250       setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v8f32, Legal);
2251       setOperationAction(ISD::FP_EXTEND,          MVT::v4f64, Custom);
2252       setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Legal);
2253 
2254       // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2255       setOperationAction(ISD::INSERT_VECTOR_ELT,    MVT::v8f16,  Custom);
2256       setOperationAction(ISD::INSERT_VECTOR_ELT,    MVT::v16f16, Custom);
2257 
2258       setOperationAction(ISD::EXTRACT_SUBVECTOR,    MVT::v8f16, Legal);
2259       setOperationAction(ISD::INSERT_SUBVECTOR,     MVT::v16f16, Legal);
2260       setOperationAction(ISD::CONCAT_VECTORS,       MVT::v16f16, Custom);
2261 
2262       setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2263       setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2264       setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2265       setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2266 
2267       // Need to custom widen these to prevent scalarization.
2268       setOperationAction(ISD::LOAD,  MVT::v4f16, Custom);
2269       setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2270     }
2271   }
2272 
2273   if (!Subtarget.useSoftFloat() &&
2274       (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16())) {
2275     addRegisterClass(MVT::v8bf16, Subtarget.hasAVX512() ? &X86::VR128XRegClass
2276                                                         : &X86::VR128RegClass);
2277     addRegisterClass(MVT::v16bf16, Subtarget.hasAVX512() ? &X86::VR256XRegClass
2278                                                          : &X86::VR256RegClass);
2279     // We set the type action of bf16 to TypeSoftPromoteHalf, but we don't
2280     // provide the method to promote BUILD_VECTOR and INSERT_VECTOR_ELT.
2281     // Set the operation action Custom to do the customization later.
2282     setOperationAction(ISD::BUILD_VECTOR, MVT::bf16, Custom);
2283     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::bf16, Custom);
2284     for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2285       setF16Action(VT, Expand);
2286       setOperationAction(ISD::FADD, VT, Expand);
2287       setOperationAction(ISD::FSUB, VT, Expand);
2288       setOperationAction(ISD::FMUL, VT, Expand);
2289       setOperationAction(ISD::FDIV, VT, Expand);
2290       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
2291       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
2292     }
2293     setOperationAction(ISD::FP_ROUND, MVT::v8bf16, Custom);
2294     addLegalFPImmediate(APFloat::getZero(APFloat::BFloat()));
2295   }
2296 
2297   if (!Subtarget.useSoftFloat() && Subtarget.hasBF16()) {
2298     addRegisterClass(MVT::v32bf16, &X86::VR512RegClass);
2299     setF16Action(MVT::v32bf16, Expand);
2300     setOperationAction(ISD::FADD, MVT::v32bf16, Expand);
2301     setOperationAction(ISD::FSUB, MVT::v32bf16, Expand);
2302     setOperationAction(ISD::FMUL, MVT::v32bf16, Expand);
2303     setOperationAction(ISD::FDIV, MVT::v32bf16, Expand);
2304     setOperationAction(ISD::BUILD_VECTOR, MVT::v32bf16, Custom);
2305     setOperationAction(ISD::FP_ROUND, MVT::v16bf16, Custom);
2306     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32bf16, Custom);
2307   }
2308 
2309   if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2310     setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
2311     setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2312     setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2313     setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
2314     setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2315 
2316     setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
2317     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2318     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2319     setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
2320     setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2321 
2322     if (Subtarget.hasBWI()) {
2323       setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
2324       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
2325     }
2326 
2327     if (Subtarget.hasFP16()) {
2328       // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2329       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f16, Custom);
2330       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f16, Custom);
2331       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f16, Custom);
2332       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f16, Custom);
2333       setOperationAction(ISD::FP_TO_SINT,        MVT::v4f16, Custom);
2334       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f16, Custom);
2335       setOperationAction(ISD::FP_TO_UINT,        MVT::v4f16, Custom);
2336       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f16, Custom);
2337       // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2338       setOperationAction(ISD::SINT_TO_FP,        MVT::v2f16, Custom);
2339       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f16, Custom);
2340       setOperationAction(ISD::UINT_TO_FP,        MVT::v2f16, Custom);
2341       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f16, Custom);
2342       setOperationAction(ISD::SINT_TO_FP,        MVT::v4f16, Custom);
2343       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f16, Custom);
2344       setOperationAction(ISD::UINT_TO_FP,        MVT::v4f16, Custom);
2345       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f16, Custom);
2346       // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2347       setOperationAction(ISD::FP_ROUND,          MVT::v2f16, Custom);
2348       setOperationAction(ISD::STRICT_FP_ROUND,   MVT::v2f16, Custom);
2349       setOperationAction(ISD::FP_ROUND,          MVT::v4f16, Custom);
2350       setOperationAction(ISD::STRICT_FP_ROUND,   MVT::v4f16, Custom);
2351       // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2352       setOperationAction(ISD::FP_EXTEND,         MVT::v2f16, Custom);
2353       setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v2f16, Custom);
2354       setOperationAction(ISD::FP_EXTEND,         MVT::v4f16, Custom);
2355       setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v4f16, Custom);
2356     }
2357   }
2358 
2359   if (Subtarget.hasAMXTILE()) {
2360     addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2361   }
2362 
2363   // We want to custom lower some of our intrinsics.
2364   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
2365   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
2366   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
2367   if (!Subtarget.is64Bit()) {
2368     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
2369   }
2370 
2371   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2372   // handle type legalization for these operations here.
2373   //
2374   // FIXME: We really should do custom legalization for addition and
2375   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
2376   // than generic legalization for 64-bit multiplication-with-overflow, though.
2377   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2378     if (VT == MVT::i64 && !Subtarget.is64Bit())
2379       continue;
2380     // Add/Sub/Mul with overflow operations are custom lowered.
2381     setOperationAction(ISD::SADDO, VT, Custom);
2382     setOperationAction(ISD::UADDO, VT, Custom);
2383     setOperationAction(ISD::SSUBO, VT, Custom);
2384     setOperationAction(ISD::USUBO, VT, Custom);
2385     setOperationAction(ISD::SMULO, VT, Custom);
2386     setOperationAction(ISD::UMULO, VT, Custom);
2387 
2388     // Support carry in as value rather than glue.
2389     setOperationAction(ISD::UADDO_CARRY, VT, Custom);
2390     setOperationAction(ISD::USUBO_CARRY, VT, Custom);
2391     setOperationAction(ISD::SETCCCARRY, VT, Custom);
2392     setOperationAction(ISD::SADDO_CARRY, VT, Custom);
2393     setOperationAction(ISD::SSUBO_CARRY, VT, Custom);
2394   }
2395 
2396   if (!Subtarget.is64Bit()) {
2397     // These libcalls are not available in 32-bit.
2398     setLibcallName(RTLIB::SHL_I128, nullptr);
2399     setLibcallName(RTLIB::SRL_I128, nullptr);
2400     setLibcallName(RTLIB::SRA_I128, nullptr);
2401     setLibcallName(RTLIB::MUL_I128, nullptr);
2402     // The MULO libcall is not part of libgcc, only compiler-rt.
2403     setLibcallName(RTLIB::MULO_I64, nullptr);
2404   }
2405   // The MULO libcall is not part of libgcc, only compiler-rt.
2406   setLibcallName(RTLIB::MULO_I128, nullptr);
2407 
2408   // Combine sin / cos into _sincos_stret if it is available.
2409   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
2410       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
2411     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
2412     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
2413   }
2414 
2415   if (Subtarget.isTargetWin64()) {
2416     setOperationAction(ISD::SDIV, MVT::i128, Custom);
2417     setOperationAction(ISD::UDIV, MVT::i128, Custom);
2418     setOperationAction(ISD::SREM, MVT::i128, Custom);
2419     setOperationAction(ISD::UREM, MVT::i128, Custom);
2420     setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
2421     setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
2422     setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
2423     setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
2424     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
2425     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
2426     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
2427     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
2428   }
2429 
2430   // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2431   // is. We should promote the value to 64-bits to solve this.
2432   // This is what the CRT headers do - `fmodf` is an inline header
2433   // function casting to f64 and calling `fmod`.
2434   if (Subtarget.is32Bit() &&
2435       (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2436     for (ISD::NodeType Op :
2437          {ISD::FCEIL,  ISD::STRICT_FCEIL,
2438           ISD::FCOS,   ISD::STRICT_FCOS,
2439           ISD::FEXP,   ISD::STRICT_FEXP,
2440           ISD::FFLOOR, ISD::STRICT_FFLOOR,
2441           ISD::FREM,   ISD::STRICT_FREM,
2442           ISD::FLOG,   ISD::STRICT_FLOG,
2443           ISD::FLOG10, ISD::STRICT_FLOG10,
2444           ISD::FPOW,   ISD::STRICT_FPOW,
2445           ISD::FSIN,   ISD::STRICT_FSIN})
2446       if (isOperationExpand(Op, MVT::f32))
2447         setOperationAction(Op, MVT::f32, Promote);
2448 
2449   // We have target-specific dag combine patterns for the following nodes:
2450   setTargetDAGCombine({ISD::VECTOR_SHUFFLE,
2451                        ISD::SCALAR_TO_VECTOR,
2452                        ISD::INSERT_VECTOR_ELT,
2453                        ISD::EXTRACT_VECTOR_ELT,
2454                        ISD::CONCAT_VECTORS,
2455                        ISD::INSERT_SUBVECTOR,
2456                        ISD::EXTRACT_SUBVECTOR,
2457                        ISD::BITCAST,
2458                        ISD::VSELECT,
2459                        ISD::SELECT,
2460                        ISD::SHL,
2461                        ISD::SRA,
2462                        ISD::SRL,
2463                        ISD::OR,
2464                        ISD::AND,
2465                        ISD::ADD,
2466                        ISD::FADD,
2467                        ISD::FSUB,
2468                        ISD::FNEG,
2469                        ISD::FMA,
2470                        ISD::STRICT_FMA,
2471                        ISD::FMINNUM,
2472                        ISD::FMAXNUM,
2473                        ISD::SUB,
2474                        ISD::LOAD,
2475                        ISD::MLOAD,
2476                        ISD::STORE,
2477                        ISD::MSTORE,
2478                        ISD::TRUNCATE,
2479                        ISD::ZERO_EXTEND,
2480                        ISD::ANY_EXTEND,
2481                        ISD::SIGN_EXTEND,
2482                        ISD::SIGN_EXTEND_INREG,
2483                        ISD::ANY_EXTEND_VECTOR_INREG,
2484                        ISD::SIGN_EXTEND_VECTOR_INREG,
2485                        ISD::ZERO_EXTEND_VECTOR_INREG,
2486                        ISD::SINT_TO_FP,
2487                        ISD::UINT_TO_FP,
2488                        ISD::STRICT_SINT_TO_FP,
2489                        ISD::STRICT_UINT_TO_FP,
2490                        ISD::SETCC,
2491                        ISD::MUL,
2492                        ISD::XOR,
2493                        ISD::MSCATTER,
2494                        ISD::MGATHER,
2495                        ISD::FP16_TO_FP,
2496                        ISD::FP_EXTEND,
2497                        ISD::STRICT_FP_EXTEND,
2498                        ISD::FP_ROUND,
2499                        ISD::STRICT_FP_ROUND});
2500 
2501   computeRegisterProperties(Subtarget.getRegisterInfo());
2502 
2503   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2504   MaxStoresPerMemsetOptSize = 8;
2505   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2506   MaxStoresPerMemcpyOptSize = 4;
2507   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2508   MaxStoresPerMemmoveOptSize = 4;
2509 
2510   // TODO: These control memcmp expansion in CGP and could be raised higher, but
2511   // that needs to benchmarked and balanced with the potential use of vector
2512   // load/store types (PR33329, PR33914).
2513   MaxLoadsPerMemcmp = 2;
2514   MaxLoadsPerMemcmpOptSize = 2;
2515 
2516   // Default loop alignment, which can be overridden by -align-loops.
2517   setPrefLoopAlignment(Align(16));
2518 
2519   // An out-of-order CPU can speculatively execute past a predictable branch,
2520   // but a conditional move could be stalled by an expensive earlier operation.
2521   PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2522   EnableExtLdPromotion = true;
2523   setPrefFunctionAlignment(Align(16));
2524 
2525   verifyIntrinsicTables();
2526 
2527   // Default to having -disable-strictnode-mutation on
2528   IsStrictFPEnabled = true;
2529 }
2530 
2531 // This has so far only been implemented for 64-bit MachO.
2532 bool X86TargetLowering::useLoadStackGuardNode() const {
2533   return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2534 }
2535 
2536 bool X86TargetLowering::useStackGuardXorFP() const {
2537   // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2538   return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2539 }
2540 
2541 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2542                                                const SDLoc &DL) const {
2543   EVT PtrTy = getPointerTy(DAG.getDataLayout());
2544   unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2545   MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2546   return SDValue(Node, 0);
2547 }
2548 
2549 TargetLoweringBase::LegalizeTypeAction
2550 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2551   if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2552       !Subtarget.hasBWI())
2553     return TypeSplitVector;
2554 
2555   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2556       !Subtarget.hasF16C() && VT.getVectorElementType() == MVT::f16)
2557     return TypeSplitVector;
2558 
2559   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2560       VT.getVectorElementType() != MVT::i1)
2561     return TypeWidenVector;
2562 
2563   return TargetLoweringBase::getPreferredVectorAction(VT);
2564 }
2565 
2566 static std::pair<MVT, unsigned>
2567 handleMaskRegisterForCallingConv(unsigned NumElts, CallingConv::ID CC,
2568                                  const X86Subtarget &Subtarget) {
2569   // v2i1/v4i1/v8i1/v16i1 all pass in xmm registers unless the calling
2570   // convention is one that uses k registers.
2571   if (NumElts == 2)
2572     return {MVT::v2i64, 1};
2573   if (NumElts == 4)
2574     return {MVT::v4i32, 1};
2575   if (NumElts == 8 && CC != CallingConv::X86_RegCall &&
2576       CC != CallingConv::Intel_OCL_BI)
2577     return {MVT::v8i16, 1};
2578   if (NumElts == 16 && CC != CallingConv::X86_RegCall &&
2579       CC != CallingConv::Intel_OCL_BI)
2580     return {MVT::v16i8, 1};
2581   // v32i1 passes in ymm unless we have BWI and the calling convention is
2582   // regcall.
2583   if (NumElts == 32 && (!Subtarget.hasBWI() || CC != CallingConv::X86_RegCall))
2584     return {MVT::v32i8, 1};
2585   // Split v64i1 vectors if we don't have v64i8 available.
2586   if (NumElts == 64 && Subtarget.hasBWI() && CC != CallingConv::X86_RegCall) {
2587     if (Subtarget.useAVX512Regs())
2588       return {MVT::v64i8, 1};
2589     return {MVT::v32i8, 2};
2590   }
2591 
2592   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2593   if (!isPowerOf2_32(NumElts) || (NumElts == 64 && !Subtarget.hasBWI()) ||
2594       NumElts > 64)
2595     return {MVT::i8, NumElts};
2596 
2597   return {MVT::INVALID_SIMPLE_VALUE_TYPE, 0};
2598 }
2599 
2600 MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
2601                                                      CallingConv::ID CC,
2602                                                      EVT VT) const {
2603   if (VT.isVector()) {
2604     if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512()) {
2605       unsigned NumElts = VT.getVectorNumElements();
2606 
2607       MVT RegisterVT;
2608       unsigned NumRegisters;
2609       std::tie(RegisterVT, NumRegisters) =
2610           handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2611       if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2612         return RegisterVT;
2613     }
2614 
2615     if (VT.getVectorElementType() == MVT::f16 && VT.getVectorNumElements() < 8)
2616       return MVT::v8f16;
2617   }
2618 
2619   // We will use more GPRs for f64 and f80 on 32 bits when x87 is disabled.
2620   if ((VT == MVT::f64 || VT == MVT::f80) && !Subtarget.is64Bit() &&
2621       !Subtarget.hasX87())
2622     return MVT::i32;
2623 
2624   if (VT.isVector() && VT.getVectorElementType() == MVT::bf16)
2625     return getRegisterTypeForCallingConv(Context, CC,
2626                                          VT.changeVectorElementType(MVT::f16));
2627 
2628   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
2629 }
2630 
2631 unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
2632                                                           CallingConv::ID CC,
2633                                                           EVT VT) const {
2634   if (VT.isVector()) {
2635     if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512()) {
2636       unsigned NumElts = VT.getVectorNumElements();
2637 
2638       MVT RegisterVT;
2639       unsigned NumRegisters;
2640       std::tie(RegisterVT, NumRegisters) =
2641           handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2642       if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2643         return NumRegisters;
2644     }
2645 
2646     if (VT.getVectorElementType() == MVT::f16 && VT.getVectorNumElements() < 8)
2647       return 1;
2648   }
2649 
2650   // We have to split f64 to 2 registers and f80 to 3 registers on 32 bits if
2651   // x87 is disabled.
2652   if (!Subtarget.is64Bit() && !Subtarget.hasX87()) {
2653     if (VT == MVT::f64)
2654       return 2;
2655     if (VT == MVT::f80)
2656       return 3;
2657   }
2658 
2659   if (VT.isVector() && VT.getVectorElementType() == MVT::bf16)
2660     return getNumRegistersForCallingConv(Context, CC,
2661                                          VT.changeVectorElementType(MVT::f16));
2662 
2663   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
2664 }
2665 
2666 unsigned X86TargetLowering::getVectorTypeBreakdownForCallingConv(
2667     LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
2668     unsigned &NumIntermediates, MVT &RegisterVT) const {
2669   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2670   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2671       Subtarget.hasAVX512() &&
2672       (!isPowerOf2_32(VT.getVectorNumElements()) ||
2673        (VT.getVectorNumElements() == 64 && !Subtarget.hasBWI()) ||
2674        VT.getVectorNumElements() > 64)) {
2675     RegisterVT = MVT::i8;
2676     IntermediateVT = MVT::i1;
2677     NumIntermediates = VT.getVectorNumElements();
2678     return NumIntermediates;
2679   }
2680 
2681   // Split v64i1 vectors if we don't have v64i8 available.
2682   if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2683       CC != CallingConv::X86_RegCall) {
2684     RegisterVT = MVT::v32i8;
2685     IntermediateVT = MVT::v32i1;
2686     NumIntermediates = 2;
2687     return 2;
2688   }
2689 
2690   // Split vNbf16 vectors according to vNf16.
2691   if (VT.isVector() && VT.getVectorElementType() == MVT::bf16)
2692     VT = VT.changeVectorElementType(MVT::f16);
2693 
2694   return TargetLowering::getVectorTypeBreakdownForCallingConv(Context, CC, VT, IntermediateVT,
2695                                               NumIntermediates, RegisterVT);
2696 }
2697 
2698 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
2699                                           LLVMContext& Context,
2700                                           EVT VT) const {
2701   if (!VT.isVector())
2702     return MVT::i8;
2703 
2704   if (Subtarget.hasAVX512()) {
2705     // Figure out what this type will be legalized to.
2706     EVT LegalVT = VT;
2707     while (getTypeAction(Context, LegalVT) != TypeLegal)
2708       LegalVT = getTypeToTransformTo(Context, LegalVT);
2709 
2710     // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
2711     if (LegalVT.getSimpleVT().is512BitVector())
2712       return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2713 
2714     if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
2715       // If we legalized to less than a 512-bit vector, then we will use a vXi1
2716       // compare for vXi32/vXi64 for sure. If we have BWI we will also support
2717       // vXi16/vXi8.
2718       MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
2719       if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
2720         return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2721     }
2722   }
2723 
2724   return VT.changeVectorElementTypeToInteger();
2725 }
2726 
2727 /// Helper for getByValTypeAlignment to determine
2728 /// the desired ByVal argument alignment.
2729 static void getMaxByValAlign(Type *Ty, Align &MaxAlign) {
2730   if (MaxAlign == 16)
2731     return;
2732   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2733     if (VTy->getPrimitiveSizeInBits().getFixedValue() == 128)
2734       MaxAlign = Align(16);
2735   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2736     Align EltAlign;
2737     getMaxByValAlign(ATy->getElementType(), EltAlign);
2738     if (EltAlign > MaxAlign)
2739       MaxAlign = EltAlign;
2740   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2741     for (auto *EltTy : STy->elements()) {
2742       Align EltAlign;
2743       getMaxByValAlign(EltTy, EltAlign);
2744       if (EltAlign > MaxAlign)
2745         MaxAlign = EltAlign;
2746       if (MaxAlign == 16)
2747         break;
2748     }
2749   }
2750 }
2751 
2752 /// Return the desired alignment for ByVal aggregate
2753 /// function arguments in the caller parameter area. For X86, aggregates
2754 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2755 /// are at 4-byte boundaries.
2756 uint64_t X86TargetLowering::getByValTypeAlignment(Type *Ty,
2757                                                   const DataLayout &DL) const {
2758   if (Subtarget.is64Bit()) {
2759     // Max of 8 and alignment of type.
2760     Align TyAlign = DL.getABITypeAlign(Ty);
2761     if (TyAlign > 8)
2762       return TyAlign.value();
2763     return 8;
2764   }
2765 
2766   Align Alignment(4);
2767   if (Subtarget.hasSSE1())
2768     getMaxByValAlign(Ty, Alignment);
2769   return Alignment.value();
2770 }
2771 
2772 /// It returns EVT::Other if the type should be determined using generic
2773 /// target-independent logic.
2774 /// For vector ops we check that the overall size isn't larger than our
2775 /// preferred vector width.
2776 EVT X86TargetLowering::getOptimalMemOpType(
2777     const MemOp &Op, const AttributeList &FuncAttributes) const {
2778   if (!FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
2779     if (Op.size() >= 16 &&
2780         (!Subtarget.isUnalignedMem16Slow() || Op.isAligned(Align(16)))) {
2781       // FIXME: Check if unaligned 64-byte accesses are slow.
2782       if (Op.size() >= 64 && Subtarget.hasAVX512() &&
2783           (Subtarget.getPreferVectorWidth() >= 512)) {
2784         return Subtarget.hasBWI() ? MVT::v64i8 : MVT::v16i32;
2785       }
2786       // FIXME: Check if unaligned 32-byte accesses are slow.
2787       if (Op.size() >= 32 && Subtarget.hasAVX() &&
2788           Subtarget.useLight256BitInstructions()) {
2789         // Although this isn't a well-supported type for AVX1, we'll let
2790         // legalization and shuffle lowering produce the optimal codegen. If we
2791         // choose an optimal type with a vector element larger than a byte,
2792         // getMemsetStores() may create an intermediate splat (using an integer
2793         // multiply) before we splat as a vector.
2794         return MVT::v32i8;
2795       }
2796       if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2797         return MVT::v16i8;
2798       // TODO: Can SSE1 handle a byte vector?
2799       // If we have SSE1 registers we should be able to use them.
2800       if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2801           (Subtarget.getPreferVectorWidth() >= 128))
2802         return MVT::v4f32;
2803     } else if (((Op.isMemcpy() && !Op.isMemcpyStrSrc()) || Op.isZeroMemset()) &&
2804                Op.size() >= 8 && !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2805       // Do not use f64 to lower memcpy if source is string constant. It's
2806       // better to use i32 to avoid the loads.
2807       // Also, do not use f64 to lower memset unless this is a memset of zeros.
2808       // The gymnastics of splatting a byte value into an XMM register and then
2809       // only using 8-byte stores (because this is a CPU with slow unaligned
2810       // 16-byte accesses) makes that a loser.
2811       return MVT::f64;
2812     }
2813   }
2814   // This is a compromise. If we reach here, unaligned accesses may be slow on
2815   // this target. However, creating smaller, aligned accesses could be even
2816   // slower and would certainly be a lot more code.
2817   if (Subtarget.is64Bit() && Op.size() >= 8)
2818     return MVT::i64;
2819   return MVT::i32;
2820 }
2821 
2822 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2823   if (VT == MVT::f32)
2824     return Subtarget.hasSSE1();
2825   if (VT == MVT::f64)
2826     return Subtarget.hasSSE2();
2827   return true;
2828 }
2829 
2830 static bool isBitAligned(Align Alignment, uint64_t SizeInBits) {
2831   return (8 * Alignment.value()) % SizeInBits == 0;
2832 }
2833 
2834 bool X86TargetLowering::isMemoryAccessFast(EVT VT, Align Alignment) const {
2835   if (isBitAligned(Alignment, VT.getSizeInBits()))
2836     return true;
2837   switch (VT.getSizeInBits()) {
2838   default:
2839     // 8-byte and under are always assumed to be fast.
2840     return true;
2841   case 128:
2842     return !Subtarget.isUnalignedMem16Slow();
2843   case 256:
2844     return !Subtarget.isUnalignedMem32Slow();
2845     // TODO: What about AVX-512 (512-bit) accesses?
2846   }
2847 }
2848 
2849 bool X86TargetLowering::allowsMisalignedMemoryAccesses(
2850     EVT VT, unsigned, Align Alignment, MachineMemOperand::Flags Flags,
2851     unsigned *Fast) const {
2852   if (Fast)
2853     *Fast = isMemoryAccessFast(VT, Alignment);
2854   // NonTemporal vector memory ops must be aligned.
2855   if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2856     // NT loads can only be vector aligned, so if its less aligned than the
2857     // minimum vector size (which we can split the vector down to), we might as
2858     // well use a regular unaligned vector load.
2859     // We don't have any NT loads pre-SSE41.
2860     if (!!(Flags & MachineMemOperand::MOLoad))
2861       return (Alignment < 16 || !Subtarget.hasSSE41());
2862     return false;
2863   }
2864   // Misaligned accesses of any size are always allowed.
2865   return true;
2866 }
2867 
2868 bool X86TargetLowering::allowsMemoryAccess(LLVMContext &Context,
2869                                            const DataLayout &DL, EVT VT,
2870                                            unsigned AddrSpace, Align Alignment,
2871                                            MachineMemOperand::Flags Flags,
2872                                            unsigned *Fast) const {
2873   if (Fast)
2874     *Fast = isMemoryAccessFast(VT, Alignment);
2875   if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2876     if (allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags,
2877                                        /*Fast=*/nullptr))
2878       return true;
2879     // NonTemporal vector memory ops are special, and must be aligned.
2880     if (!isBitAligned(Alignment, VT.getSizeInBits()))
2881       return false;
2882     switch (VT.getSizeInBits()) {
2883     case 128:
2884       if (!!(Flags & MachineMemOperand::MOLoad) && Subtarget.hasSSE41())
2885         return true;
2886       if (!!(Flags & MachineMemOperand::MOStore) && Subtarget.hasSSE2())
2887         return true;
2888       return false;
2889     case 256:
2890       if (!!(Flags & MachineMemOperand::MOLoad) && Subtarget.hasAVX2())
2891         return true;
2892       if (!!(Flags & MachineMemOperand::MOStore) && Subtarget.hasAVX())
2893         return true;
2894       return false;
2895     case 512:
2896       if (Subtarget.hasAVX512())
2897         return true;
2898       return false;
2899     default:
2900       return false; // Don't have NonTemporal vector memory ops of this size.
2901     }
2902   }
2903   return true;
2904 }
2905 
2906 /// Return the entry encoding for a jump table in the
2907 /// current function.  The returned value is a member of the
2908 /// MachineJumpTableInfo::JTEntryKind enum.
2909 unsigned X86TargetLowering::getJumpTableEncoding() const {
2910   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2911   // symbol.
2912   if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2913     return MachineJumpTableInfo::EK_Custom32;
2914 
2915   // Otherwise, use the normal jump table encoding heuristics.
2916   return TargetLowering::getJumpTableEncoding();
2917 }
2918 
2919 bool X86TargetLowering::splitValueIntoRegisterParts(
2920     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
2921     unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
2922   bool IsABIRegCopy = CC.has_value();
2923   EVT ValueVT = Val.getValueType();
2924   if (IsABIRegCopy && ValueVT == MVT::bf16 && PartVT == MVT::f32) {
2925     unsigned ValueBits = ValueVT.getSizeInBits();
2926     unsigned PartBits = PartVT.getSizeInBits();
2927     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
2928     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
2929     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
2930     Parts[0] = Val;
2931     return true;
2932   }
2933   return false;
2934 }
2935 
2936 SDValue X86TargetLowering::joinRegisterPartsIntoValue(
2937     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
2938     MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
2939   bool IsABIRegCopy = CC.has_value();
2940   if (IsABIRegCopy && ValueVT == MVT::bf16 && PartVT == MVT::f32) {
2941     unsigned ValueBits = ValueVT.getSizeInBits();
2942     unsigned PartBits = PartVT.getSizeInBits();
2943     SDValue Val = Parts[0];
2944 
2945     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
2946     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
2947     Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
2948     return Val;
2949   }
2950   return SDValue();
2951 }
2952 
2953 bool X86TargetLowering::useSoftFloat() const {
2954   return Subtarget.useSoftFloat();
2955 }
2956 
2957 void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2958                                               ArgListTy &Args) const {
2959 
2960   // Only relabel X86-32 for C / Stdcall CCs.
2961   if (Subtarget.is64Bit())
2962     return;
2963   if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2964     return;
2965   unsigned ParamRegs = 0;
2966   if (auto *M = MF->getFunction().getParent())
2967     ParamRegs = M->getNumberRegisterParameters();
2968 
2969   // Mark the first N int arguments as having reg
2970   for (auto &Arg : Args) {
2971     Type *T = Arg.Ty;
2972     if (T->isIntOrPtrTy())
2973       if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2974         unsigned numRegs = 1;
2975         if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2976           numRegs = 2;
2977         if (ParamRegs < numRegs)
2978           return;
2979         ParamRegs -= numRegs;
2980         Arg.IsInReg = true;
2981       }
2982   }
2983 }
2984 
2985 const MCExpr *
2986 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2987                                              const MachineBasicBlock *MBB,
2988                                              unsigned uid,MCContext &Ctx) const{
2989   assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2990   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2991   // entries.
2992   return MCSymbolRefExpr::create(MBB->getSymbol(),
2993                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2994 }
2995 
2996 /// Returns relocation base for the given PIC jumptable.
2997 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2998                                                     SelectionDAG &DAG) const {
2999   if (!Subtarget.is64Bit())
3000     // This doesn't have SDLoc associated with it, but is not really the
3001     // same as a Register.
3002     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3003                        getPointerTy(DAG.getDataLayout()));
3004   return Table;
3005 }
3006 
3007 /// This returns the relocation base for the given PIC jumptable,
3008 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
3009 const MCExpr *X86TargetLowering::
3010 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
3011                              MCContext &Ctx) const {
3012   // X86-64 uses RIP relative addressing based on the jump table label.
3013   if (Subtarget.isPICStyleRIPRel())
3014     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3015 
3016   // Otherwise, the reference is relative to the PIC base.
3017   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3018 }
3019 
3020 std::pair<const TargetRegisterClass *, uint8_t>
3021 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
3022                                            MVT VT) const {
3023   const TargetRegisterClass *RRC = nullptr;
3024   uint8_t Cost = 1;
3025   switch (VT.SimpleTy) {
3026   default:
3027     return TargetLowering::findRepresentativeClass(TRI, VT);
3028   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
3029     RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
3030     break;
3031   case MVT::x86mmx:
3032     RRC = &X86::VR64RegClass;
3033     break;
3034   case MVT::f32: case MVT::f64:
3035   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
3036   case MVT::v4f32: case MVT::v2f64:
3037   case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
3038   case MVT::v8f32: case MVT::v4f64:
3039   case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
3040   case MVT::v16f32: case MVT::v8f64:
3041     RRC = &X86::VR128XRegClass;
3042     break;
3043   }
3044   return std::make_pair(RRC, Cost);
3045 }
3046 
3047 unsigned X86TargetLowering::getAddressSpace() const {
3048   if (Subtarget.is64Bit())
3049     return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
3050   return 256;
3051 }
3052 
3053 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
3054   return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
3055          (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
3056 }
3057 
3058 static Constant* SegmentOffset(IRBuilderBase &IRB,
3059                                int Offset, unsigned AddressSpace) {
3060   return ConstantExpr::getIntToPtr(
3061       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
3062       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
3063 }
3064 
3065 Value *X86TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
3066   // glibc, bionic, and Fuchsia have a special slot for the stack guard in
3067   // tcbhead_t; use it instead of the usual global variable (see
3068   // sysdeps/{i386,x86_64}/nptl/tls.h)
3069   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
3070     unsigned AddressSpace = getAddressSpace();
3071 
3072     // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
3073     if (Subtarget.isTargetFuchsia())
3074       return SegmentOffset(IRB, 0x10, AddressSpace);
3075 
3076     Module *M = IRB.GetInsertBlock()->getParent()->getParent();
3077     // Specially, some users may customize the base reg and offset.
3078     int Offset = M->getStackProtectorGuardOffset();
3079     // If we don't set -stack-protector-guard-offset value:
3080     // %fs:0x28, unless we're using a Kernel code model, in which case
3081     // it's %gs:0x28.  gs:0x14 on i386.
3082     if (Offset == INT_MAX)
3083       Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
3084 
3085     StringRef GuardReg = M->getStackProtectorGuardReg();
3086     if (GuardReg == "fs")
3087       AddressSpace = X86AS::FS;
3088     else if (GuardReg == "gs")
3089       AddressSpace = X86AS::GS;
3090 
3091     // Use symbol guard if user specify.
3092     StringRef GuardSymb = M->getStackProtectorGuardSymbol();
3093     if (!GuardSymb.empty()) {
3094       GlobalVariable *GV = M->getGlobalVariable(GuardSymb);
3095       if (!GV) {
3096         Type *Ty = Subtarget.is64Bit() ? Type::getInt64Ty(M->getContext())
3097                                        : Type::getInt32Ty(M->getContext());
3098         GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage,
3099                                 nullptr, GuardSymb, nullptr,
3100                                 GlobalValue::NotThreadLocal, AddressSpace);
3101         if (!Subtarget.isTargetDarwin())
3102           GV->setDSOLocal(M->getDirectAccessExternalData());
3103       }
3104       return GV;
3105     }
3106 
3107     return SegmentOffset(IRB, Offset, AddressSpace);
3108   }
3109   return TargetLowering::getIRStackGuard(IRB);
3110 }
3111 
3112 void X86TargetLowering::insertSSPDeclarations(Module &M) const {
3113   // MSVC CRT provides functionalities for stack protection.
3114   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
3115       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
3116     // MSVC CRT has a global variable holding security cookie.
3117     M.getOrInsertGlobal("__security_cookie",
3118                         Type::getInt8PtrTy(M.getContext()));
3119 
3120     // MSVC CRT has a function to validate security cookie.
3121     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
3122         "__security_check_cookie", Type::getVoidTy(M.getContext()),
3123         Type::getInt8PtrTy(M.getContext()));
3124     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
3125       F->setCallingConv(CallingConv::X86_FastCall);
3126       F->addParamAttr(0, Attribute::AttrKind::InReg);
3127     }
3128     return;
3129   }
3130 
3131   StringRef GuardMode = M.getStackProtectorGuard();
3132 
3133   // glibc, bionic, and Fuchsia have a special slot for the stack guard.
3134   if ((GuardMode == "tls" || GuardMode.empty()) &&
3135       hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
3136     return;
3137   TargetLowering::insertSSPDeclarations(M);
3138 }
3139 
3140 Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
3141   // MSVC CRT has a global variable holding security cookie.
3142   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
3143       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
3144     return M.getGlobalVariable("__security_cookie");
3145   }
3146   return TargetLowering::getSDagStackGuard(M);
3147 }
3148 
3149 Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
3150   // MSVC CRT has a function to validate security cookie.
3151   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
3152       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
3153     return M.getFunction("__security_check_cookie");
3154   }
3155   return TargetLowering::getSSPStackGuardCheck(M);
3156 }
3157 
3158 Value *
3159 X86TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
3160   if (Subtarget.getTargetTriple().isOSContiki())
3161     return getDefaultSafeStackPointerLocation(IRB, false);
3162 
3163   // Android provides a fixed TLS slot for the SafeStack pointer. See the
3164   // definition of TLS_SLOT_SAFESTACK in
3165   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
3166   if (Subtarget.isTargetAndroid()) {
3167     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
3168     // %gs:0x24 on i386
3169     int Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
3170     return SegmentOffset(IRB, Offset, getAddressSpace());
3171   }
3172 
3173   // Fuchsia is similar.
3174   if (Subtarget.isTargetFuchsia()) {
3175     // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
3176     return SegmentOffset(IRB, 0x18, getAddressSpace());
3177   }
3178 
3179   return TargetLowering::getSafeStackPointerLocation(IRB);
3180 }
3181 
3182 //===----------------------------------------------------------------------===//
3183 //               Return Value Calling Convention Implementation
3184 //===----------------------------------------------------------------------===//
3185 
3186 bool X86TargetLowering::CanLowerReturn(
3187     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3188     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3189   SmallVector<CCValAssign, 16> RVLocs;
3190   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3191   return CCInfo.CheckReturn(Outs, RetCC_X86);
3192 }
3193 
3194 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
3195   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
3196   return ScratchRegs;
3197 }
3198 
3199 ArrayRef<MCPhysReg> X86TargetLowering::getRoundingControlRegisters() const {
3200   // FIXME: We should def X86::FPCW for x87 as well. But it affects a lot of lit
3201   // tests at the moment, which is not what we expected.
3202   static const MCPhysReg RCRegs[] = {X86::MXCSR};
3203   return RCRegs;
3204 }
3205 
3206 /// Lowers masks values (v*i1) to the local register values
3207 /// \returns DAG node after lowering to register type
3208 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
3209                                const SDLoc &DL, SelectionDAG &DAG) {
3210   EVT ValVT = ValArg.getValueType();
3211 
3212   if (ValVT == MVT::v1i1)
3213     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ValLoc, ValArg,
3214                        DAG.getIntPtrConstant(0, DL));
3215 
3216   if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
3217       (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
3218     // Two stage lowering might be required
3219     // bitcast:   v8i1 -> i8 / v16i1 -> i16
3220     // anyextend: i8   -> i32 / i16   -> i32
3221     EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
3222     SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
3223     if (ValLoc == MVT::i32)
3224       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, DL, ValLoc, ValToCopy);
3225     return ValToCopy;
3226   }
3227 
3228   if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
3229       (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
3230     // One stage lowering is required
3231     // bitcast:   v32i1 -> i32 / v64i1 -> i64
3232     return DAG.getBitcast(ValLoc, ValArg);
3233   }
3234 
3235   return DAG.getNode(ISD::ANY_EXTEND, DL, ValLoc, ValArg);
3236 }
3237 
3238 /// Breaks v64i1 value into two registers and adds the new node to the DAG
3239 static void Passv64i1ArgInRegs(
3240     const SDLoc &DL, SelectionDAG &DAG, SDValue &Arg,
3241     SmallVectorImpl<std::pair<Register, SDValue>> &RegsToPass, CCValAssign &VA,
3242     CCValAssign &NextVA, const X86Subtarget &Subtarget) {
3243   assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
3244   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
3245   assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
3246   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
3247          "The value should reside in two registers");
3248 
3249   // Before splitting the value we cast it to i64
3250   Arg = DAG.getBitcast(MVT::i64, Arg);
3251 
3252   // Splitting the value into two i32 types
3253   SDValue Lo, Hi;
3254   std::tie(Lo, Hi) = DAG.SplitScalar(Arg, DL, MVT::i32, MVT::i32);
3255 
3256   // Attach the two i32 types into corresponding registers
3257   RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
3258   RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
3259 }
3260 
3261 SDValue
3262 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3263                                bool isVarArg,
3264                                const SmallVectorImpl<ISD::OutputArg> &Outs,
3265                                const SmallVectorImpl<SDValue> &OutVals,
3266                                const SDLoc &dl, SelectionDAG &DAG) const {
3267   MachineFunction &MF = DAG.getMachineFunction();
3268   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3269 
3270   // In some cases we need to disable registers from the default CSR list.
3271   // For example, when they are used as return registers (preserve_* and X86's
3272   // regcall) or for argument passing (X86's regcall).
3273   bool ShouldDisableCalleeSavedRegister =
3274       shouldDisableRetRegFromCSR(CallConv) ||
3275       MF.getFunction().hasFnAttribute("no_caller_saved_registers");
3276 
3277   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
3278     report_fatal_error("X86 interrupts may not return any value");
3279 
3280   SmallVector<CCValAssign, 16> RVLocs;
3281   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
3282   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
3283 
3284   SmallVector<std::pair<Register, SDValue>, 4> RetVals;
3285   for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
3286        ++I, ++OutsIndex) {
3287     CCValAssign &VA = RVLocs[I];
3288     assert(VA.isRegLoc() && "Can only return in registers!");
3289 
3290     // Add the register to the CalleeSaveDisableRegs list.
3291     if (ShouldDisableCalleeSavedRegister)
3292       MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
3293 
3294     SDValue ValToCopy = OutVals[OutsIndex];
3295     EVT ValVT = ValToCopy.getValueType();
3296 
3297     // Promote values to the appropriate types.
3298     if (VA.getLocInfo() == CCValAssign::SExt)
3299       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
3300     else if (VA.getLocInfo() == CCValAssign::ZExt)
3301       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
3302     else if (VA.getLocInfo() == CCValAssign::AExt) {
3303       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
3304         ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
3305       else
3306         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
3307     }
3308     else if (VA.getLocInfo() == CCValAssign::BCvt)
3309       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
3310 
3311     assert(VA.getLocInfo() != CCValAssign::FPExt &&
3312            "Unexpected FP-extend for return value.");
3313 
3314     // Report an error if we have attempted to return a value via an XMM
3315     // register and SSE was disabled.
3316     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3317       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3318       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3319     } else if (!Subtarget.hasSSE2() &&
3320                X86::FR64XRegClass.contains(VA.getLocReg()) &&
3321                ValVT == MVT::f64) {
3322       // When returning a double via an XMM register, report an error if SSE2 is
3323       // not enabled.
3324       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3325       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3326     }
3327 
3328     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
3329     // the RET instruction and handled by the FP Stackifier.
3330     if (VA.getLocReg() == X86::FP0 ||
3331         VA.getLocReg() == X86::FP1) {
3332       // If this is a copy from an xmm register to ST(0), use an FPExtend to
3333       // change the value to the FP stack register class.
3334       if (isScalarFPTypeInSSEReg(VA.getValVT()))
3335         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
3336       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
3337       // Don't emit a copytoreg.
3338       continue;
3339     }
3340 
3341     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
3342     // which is returned in RAX / RDX.
3343     if (Subtarget.is64Bit()) {
3344       if (ValVT == MVT::x86mmx) {
3345         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
3346           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
3347           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
3348                                   ValToCopy);
3349           // If we don't have SSE2 available, convert to v4f32 so the generated
3350           // register is legal.
3351           if (!Subtarget.hasSSE2())
3352             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
3353         }
3354       }
3355     }
3356 
3357     if (VA.needsCustom()) {
3358       assert(VA.getValVT() == MVT::v64i1 &&
3359              "Currently the only custom case is when we split v64i1 to 2 regs");
3360 
3361       Passv64i1ArgInRegs(dl, DAG, ValToCopy, RetVals, VA, RVLocs[++I],
3362                          Subtarget);
3363 
3364       // Add the second register to the CalleeSaveDisableRegs list.
3365       if (ShouldDisableCalleeSavedRegister)
3366         MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
3367     } else {
3368       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
3369     }
3370   }
3371 
3372   SDValue Glue;
3373   SmallVector<SDValue, 6> RetOps;
3374   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3375   // Operand #1 = Bytes To Pop
3376   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
3377                    MVT::i32));
3378 
3379   // Copy the result values into the output registers.
3380   for (auto &RetVal : RetVals) {
3381     if (RetVal.first == X86::FP0 || RetVal.first == X86::FP1) {
3382       RetOps.push_back(RetVal.second);
3383       continue; // Don't emit a copytoreg.
3384     }
3385 
3386     Chain = DAG.getCopyToReg(Chain, dl, RetVal.first, RetVal.second, Glue);
3387     Glue = Chain.getValue(1);
3388     RetOps.push_back(
3389         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
3390   }
3391 
3392   // Swift calling convention does not require we copy the sret argument
3393   // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
3394 
3395   // All x86 ABIs require that for returning structs by value we copy
3396   // the sret argument into %rax/%eax (depending on ABI) for the return.
3397   // We saved the argument into a virtual register in the entry block,
3398   // so now we copy the value out and into %rax/%eax.
3399   //
3400   // Checking Function.hasStructRetAttr() here is insufficient because the IR
3401   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
3402   // false, then an sret argument may be implicitly inserted in the SelDAG. In
3403   // either case FuncInfo->setSRetReturnReg() will have been called.
3404   if (Register SRetReg = FuncInfo->getSRetReturnReg()) {
3405     // When we have both sret and another return value, we should use the
3406     // original Chain stored in RetOps[0], instead of the current Chain updated
3407     // in the above loop. If we only have sret, RetOps[0] equals to Chain.
3408 
3409     // For the case of sret and another return value, we have
3410     //   Chain_0 at the function entry
3411     //   Chain_1 = getCopyToReg(Chain_0) in the above loop
3412     // If we use Chain_1 in getCopyFromReg, we will have
3413     //   Val = getCopyFromReg(Chain_1)
3414     //   Chain_2 = getCopyToReg(Chain_1, Val) from below
3415 
3416     // getCopyToReg(Chain_0) will be glued together with
3417     // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
3418     // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
3419     //   Data dependency from Unit B to Unit A due to usage of Val in
3420     //     getCopyToReg(Chain_1, Val)
3421     //   Chain dependency from Unit A to Unit B
3422 
3423     // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
3424     SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
3425                                      getPointerTy(MF.getDataLayout()));
3426 
3427     Register RetValReg
3428         = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
3429           X86::RAX : X86::EAX;
3430     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Glue);
3431     Glue = Chain.getValue(1);
3432 
3433     // RAX/EAX now acts like a return value.
3434     RetOps.push_back(
3435         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
3436 
3437     // Add the returned register to the CalleeSaveDisableRegs list. Don't do
3438     // this however for preserve_most/preserve_all to minimize the number of
3439     // callee-saved registers for these CCs.
3440     if (ShouldDisableCalleeSavedRegister &&
3441         CallConv != CallingConv::PreserveAll &&
3442         CallConv != CallingConv::PreserveMost)
3443       MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
3444   }
3445 
3446   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
3447   const MCPhysReg *I =
3448       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3449   if (I) {
3450     for (; *I; ++I) {
3451       if (X86::GR64RegClass.contains(*I))
3452         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3453       else
3454         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3455     }
3456   }
3457 
3458   RetOps[0] = Chain;  // Update chain.
3459 
3460   // Add the glue if we have it.
3461   if (Glue.getNode())
3462     RetOps.push_back(Glue);
3463 
3464   X86ISD::NodeType opcode = X86ISD::RET_GLUE;
3465   if (CallConv == CallingConv::X86_INTR)
3466     opcode = X86ISD::IRET;
3467   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
3468 }
3469 
3470 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3471   if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
3472     return false;
3473 
3474   SDValue TCChain = Chain;
3475   SDNode *Copy = *N->use_begin();
3476   if (Copy->getOpcode() == ISD::CopyToReg) {
3477     // If the copy has a glue operand, we conservatively assume it isn't safe to
3478     // perform a tail call.
3479     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3480       return false;
3481     TCChain = Copy->getOperand(0);
3482   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
3483     return false;
3484 
3485   bool HasRet = false;
3486   for (const SDNode *U : Copy->uses()) {
3487     if (U->getOpcode() != X86ISD::RET_GLUE)
3488       return false;
3489     // If we are returning more than one value, we can definitely
3490     // not make a tail call see PR19530
3491     if (U->getNumOperands() > 4)
3492       return false;
3493     if (U->getNumOperands() == 4 &&
3494         U->getOperand(U->getNumOperands() - 1).getValueType() != MVT::Glue)
3495       return false;
3496     HasRet = true;
3497   }
3498 
3499   if (!HasRet)
3500     return false;
3501 
3502   Chain = TCChain;
3503   return true;
3504 }
3505 
3506 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
3507                                            ISD::NodeType ExtendKind) const {
3508   MVT ReturnMVT = MVT::i32;
3509 
3510   bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
3511   if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
3512     // The ABI does not require i1, i8 or i16 to be extended.
3513     //
3514     // On Darwin, there is code in the wild relying on Clang's old behaviour of
3515     // always extending i8/i16 return values, so keep doing that for now.
3516     // (PR26665).
3517     ReturnMVT = MVT::i8;
3518   }
3519 
3520   EVT MinVT = getRegisterType(Context, ReturnMVT);
3521   return VT.bitsLT(MinVT) ? MinVT : VT;
3522 }
3523 
3524 /// Reads two 32 bit registers and creates a 64 bit mask value.
3525 /// \param VA The current 32 bit value that need to be assigned.
3526 /// \param NextVA The next 32 bit value that need to be assigned.
3527 /// \param Root The parent DAG node.
3528 /// \param [in,out] InGlue Represents SDvalue in the parent DAG node for
3529 ///                        glue purposes. In the case the DAG is already using
3530 ///                        physical register instead of virtual, we should glue
3531 ///                        our new SDValue to InGlue SDvalue.
3532 /// \return a new SDvalue of size 64bit.
3533 static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
3534                                 SDValue &Root, SelectionDAG &DAG,
3535                                 const SDLoc &DL, const X86Subtarget &Subtarget,
3536                                 SDValue *InGlue = nullptr) {
3537   assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
3538   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
3539   assert(VA.getValVT() == MVT::v64i1 &&
3540          "Expecting first location of 64 bit width type");
3541   assert(NextVA.getValVT() == VA.getValVT() &&
3542          "The locations should have the same type");
3543   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
3544          "The values should reside in two registers");
3545 
3546   SDValue Lo, Hi;
3547   SDValue ArgValueLo, ArgValueHi;
3548 
3549   MachineFunction &MF = DAG.getMachineFunction();
3550   const TargetRegisterClass *RC = &X86::GR32RegClass;
3551 
3552   // Read a 32 bit value from the registers.
3553   if (nullptr == InGlue) {
3554     // When no physical register is present,
3555     // create an intermediate virtual register.
3556     Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
3557     ArgValueLo = DAG.getCopyFromReg(Root, DL, Reg, MVT::i32);
3558     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3559     ArgValueHi = DAG.getCopyFromReg(Root, DL, Reg, MVT::i32);
3560   } else {
3561     // When a physical register is available read the value from it and glue
3562     // the reads together.
3563     ArgValueLo =
3564       DAG.getCopyFromReg(Root, DL, VA.getLocReg(), MVT::i32, *InGlue);
3565     *InGlue = ArgValueLo.getValue(2);
3566     ArgValueHi =
3567       DAG.getCopyFromReg(Root, DL, NextVA.getLocReg(), MVT::i32, *InGlue);
3568     *InGlue = ArgValueHi.getValue(2);
3569   }
3570 
3571   // Convert the i32 type into v32i1 type.
3572   Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
3573 
3574   // Convert the i32 type into v32i1 type.
3575   Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
3576 
3577   // Concatenate the two values together.
3578   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v64i1, Lo, Hi);
3579 }
3580 
3581 /// The function will lower a register of various sizes (8/16/32/64)
3582 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
3583 /// \returns a DAG node contains the operand after lowering to mask type.
3584 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
3585                                const EVT &ValLoc, const SDLoc &DL,
3586                                SelectionDAG &DAG) {
3587   SDValue ValReturned = ValArg;
3588 
3589   if (ValVT == MVT::v1i1)
3590     return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, ValReturned);
3591 
3592   if (ValVT == MVT::v64i1) {
3593     // In 32 bit machine, this case is handled by getv64i1Argument
3594     assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
3595     // In 64 bit machine, There is no need to truncate the value only bitcast
3596   } else {
3597     MVT MaskLenVT;
3598     switch (ValVT.getSimpleVT().SimpleTy) {
3599     case MVT::v8i1:
3600       MaskLenVT = MVT::i8;
3601       break;
3602     case MVT::v16i1:
3603       MaskLenVT = MVT::i16;
3604       break;
3605     case MVT::v32i1:
3606       MaskLenVT = MVT::i32;
3607       break;
3608     default:
3609       llvm_unreachable("Expecting a vector of i1 types");
3610     }
3611 
3612     ValReturned = DAG.getNode(ISD::TRUNCATE, DL, MaskLenVT, ValReturned);
3613   }
3614   return DAG.getBitcast(ValVT, ValReturned);
3615 }
3616 
3617 /// Lower the result values of a call into the
3618 /// appropriate copies out of appropriate physical registers.
3619 ///
3620 SDValue X86TargetLowering::LowerCallResult(
3621     SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
3622     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3623     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3624     uint32_t *RegMask) const {
3625 
3626   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3627   // Assign locations to each value returned by this call.
3628   SmallVector<CCValAssign, 16> RVLocs;
3629   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3630                  *DAG.getContext());
3631   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3632 
3633   // Copy all of the result registers out of their specified physreg.
3634   for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
3635        ++I, ++InsIndex) {
3636     CCValAssign &VA = RVLocs[I];
3637     EVT CopyVT = VA.getLocVT();
3638 
3639     // In some calling conventions we need to remove the used registers
3640     // from the register mask.
3641     if (RegMask) {
3642       for (MCPhysReg SubReg : TRI->subregs_inclusive(VA.getLocReg()))
3643         RegMask[SubReg / 32] &= ~(1u << (SubReg % 32));
3644     }
3645 
3646     // Report an error if there was an attempt to return FP values via XMM
3647     // registers.
3648     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3649       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3650       if (VA.getLocReg() == X86::XMM1)
3651         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3652       else
3653         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3654     } else if (!Subtarget.hasSSE2() &&
3655                X86::FR64XRegClass.contains(VA.getLocReg()) &&
3656                CopyVT == MVT::f64) {
3657       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3658       if (VA.getLocReg() == X86::XMM1)
3659         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3660       else
3661         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3662     }
3663 
3664     // If we prefer to use the value in xmm registers, copy it out as f80 and
3665     // use a truncate to move it from fp stack reg to xmm reg.
3666     bool RoundAfterCopy = false;
3667     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3668         isScalarFPTypeInSSEReg(VA.getValVT())) {
3669       if (!Subtarget.hasX87())
3670         report_fatal_error("X87 register return with X87 disabled");
3671       CopyVT = MVT::f80;
3672       RoundAfterCopy = (CopyVT != VA.getLocVT());
3673     }
3674 
3675     SDValue Val;
3676     if (VA.needsCustom()) {
3677       assert(VA.getValVT() == MVT::v64i1 &&
3678              "Currently the only custom case is when we split v64i1 to 2 regs");
3679       Val =
3680           getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InGlue);
3681     } else {
3682       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InGlue)
3683                   .getValue(1);
3684       Val = Chain.getValue(0);
3685       InGlue = Chain.getValue(2);
3686     }
3687 
3688     if (RoundAfterCopy)
3689       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
3690                         // This truncation won't change the value.
3691                         DAG.getIntPtrConstant(1, dl, /*isTarget=*/true));
3692 
3693     if (VA.isExtInLoc()) {
3694       if (VA.getValVT().isVector() &&
3695           VA.getValVT().getScalarType() == MVT::i1 &&
3696           ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3697            (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3698         // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3699         Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
3700       } else
3701         Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3702     }
3703 
3704     if (VA.getLocInfo() == CCValAssign::BCvt)
3705       Val = DAG.getBitcast(VA.getValVT(), Val);
3706 
3707     InVals.push_back(Val);
3708   }
3709 
3710   return Chain;
3711 }
3712 
3713 //===----------------------------------------------------------------------===//
3714 //                C & StdCall & Fast Calling Convention implementation
3715 //===----------------------------------------------------------------------===//
3716 //  StdCall calling convention seems to be standard for many Windows' API
3717 //  routines and around. It differs from C calling convention just a little:
3718 //  callee should clean up the stack, not caller. Symbols should be also
3719 //  decorated in some fancy way :) It doesn't support any vector arguments.
3720 //  For info on fast calling convention see Fast Calling Convention (tail call)
3721 //  implementation LowerX86_32FastCCCallTo.
3722 
3723 /// Determines whether Args, either a set of outgoing arguments to a call, or a
3724 /// set of incoming args of a call, contains an sret pointer that the callee
3725 /// pops
3726 template <typename T>
3727 static bool hasCalleePopSRet(const SmallVectorImpl<T> &Args,
3728                              const X86Subtarget &Subtarget) {
3729   // Not C++20 (yet), so no concepts available.
3730   static_assert(std::is_same_v<T, ISD::OutputArg> ||
3731                     std::is_same_v<T, ISD::InputArg>,
3732                 "requires ISD::OutputArg or ISD::InputArg");
3733 
3734   // Only 32-bit pops the sret.  It's a 64-bit world these days, so early-out
3735   // for most compilations.
3736   if (!Subtarget.is32Bit())
3737     return false;
3738 
3739   if (Args.empty())
3740     return false;
3741 
3742   // Most calls do not have an sret argument, check the arg next.
3743   const ISD::ArgFlagsTy &Flags = Args[0].Flags;
3744   if (!Flags.isSRet() || Flags.isInReg())
3745     return false;
3746 
3747   // The MSVCabi does not pop the sret.
3748   if (Subtarget.getTargetTriple().isOSMSVCRT())
3749     return false;
3750 
3751   // MCUs don't pop the sret
3752   if (Subtarget.isTargetMCU())
3753     return false;
3754 
3755   // Callee pops argument
3756   return true;
3757 }
3758 
3759 /// Make a copy of an aggregate at address specified by "Src" to address
3760 /// "Dst" with size and alignment information specified by the specific
3761 /// parameter attribute. The copy will be passed as a byval function parameter.
3762 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
3763                                          SDValue Chain, ISD::ArgFlagsTy Flags,
3764                                          SelectionDAG &DAG, const SDLoc &dl) {
3765   SDValue SizeNode = DAG.getIntPtrConstant(Flags.getByValSize(), dl);
3766 
3767   return DAG.getMemcpy(
3768       Chain, dl, Dst, Src, SizeNode, Flags.getNonZeroByValAlign(),
3769       /*isVolatile*/ false, /*AlwaysInline=*/true,
3770       /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
3771 }
3772 
3773 /// Return true if the calling convention is one that we can guarantee TCO for.
3774 static bool canGuaranteeTCO(CallingConv::ID CC) {
3775   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3776           CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
3777           CC == CallingConv::Tail || CC == CallingConv::SwiftTail);
3778 }
3779 
3780 /// Return true if we might ever do TCO for calls with this calling convention.
3781 static bool mayTailCallThisCC(CallingConv::ID CC) {
3782   switch (CC) {
3783   // C calling conventions:
3784   case CallingConv::C:
3785   case CallingConv::Win64:
3786   case CallingConv::X86_64_SysV:
3787   // Callee pop conventions:
3788   case CallingConv::X86_ThisCall:
3789   case CallingConv::X86_StdCall:
3790   case CallingConv::X86_VectorCall:
3791   case CallingConv::X86_FastCall:
3792   // Swift:
3793   case CallingConv::Swift:
3794     return true;
3795   default:
3796     return canGuaranteeTCO(CC);
3797   }
3798 }
3799 
3800 /// Return true if the function is being made into a tailcall target by
3801 /// changing its ABI.
3802 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
3803   return (GuaranteedTailCallOpt && canGuaranteeTCO(CC)) ||
3804          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
3805 }
3806 
3807 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3808   if (!CI->isTailCall())
3809     return false;
3810 
3811   CallingConv::ID CalleeCC = CI->getCallingConv();
3812   if (!mayTailCallThisCC(CalleeCC))
3813     return false;
3814 
3815   return true;
3816 }
3817 
3818 SDValue
3819 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
3820                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3821                                     const SDLoc &dl, SelectionDAG &DAG,
3822                                     const CCValAssign &VA,
3823                                     MachineFrameInfo &MFI, unsigned i) const {
3824   // Create the nodes corresponding to a load from this parameter slot.
3825   ISD::ArgFlagsTy Flags = Ins[i].Flags;
3826   bool AlwaysUseMutable = shouldGuaranteeTCO(
3827       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
3828   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
3829   EVT ValVT;
3830   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3831 
3832   // If value is passed by pointer we have address passed instead of the value
3833   // itself. No need to extend if the mask value and location share the same
3834   // absolute size.
3835   bool ExtendedInMem =
3836       VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
3837       VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
3838 
3839   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
3840     ValVT = VA.getLocVT();
3841   else
3842     ValVT = VA.getValVT();
3843 
3844   // FIXME: For now, all byval parameter objects are marked mutable. This can be
3845   // changed with more analysis.
3846   // In case of tail call optimization mark all arguments mutable. Since they
3847   // could be overwritten by lowering of arguments in case of a tail call.
3848   if (Flags.isByVal()) {
3849     unsigned Bytes = Flags.getByValSize();
3850     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3851 
3852     // FIXME: For now, all byval parameter objects are marked as aliasing. This
3853     // can be improved with deeper analysis.
3854     int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3855                                    /*isAliased=*/true);
3856     return DAG.getFrameIndex(FI, PtrVT);
3857   }
3858 
3859   EVT ArgVT = Ins[i].ArgVT;
3860 
3861   // If this is a vector that has been split into multiple parts, don't elide
3862   // the copy. The layout on the stack may not match the packed in-memory
3863   // layout.
3864   bool ScalarizedVector = ArgVT.isVector() && !VA.getLocVT().isVector();
3865 
3866   // This is an argument in memory. We might be able to perform copy elision.
3867   // If the argument is passed directly in memory without any extension, then we
3868   // can perform copy elision. Large vector types, for example, may be passed
3869   // indirectly by pointer.
3870   if (Flags.isCopyElisionCandidate() &&
3871       VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem &&
3872       !ScalarizedVector) {
3873     SDValue PartAddr;
3874     if (Ins[i].PartOffset == 0) {
3875       // If this is a one-part value or the first part of a multi-part value,
3876       // create a stack object for the entire argument value type and return a
3877       // load from our portion of it. This assumes that if the first part of an
3878       // argument is in memory, the rest will also be in memory.
3879       int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3880                                      /*IsImmutable=*/false);
3881       PartAddr = DAG.getFrameIndex(FI, PtrVT);
3882       return DAG.getLoad(
3883           ValVT, dl, Chain, PartAddr,
3884           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3885     }
3886 
3887     // This is not the first piece of an argument in memory. See if there is
3888     // already a fixed stack object including this offset. If so, assume it
3889     // was created by the PartOffset == 0 branch above and create a load from
3890     // the appropriate offset into it.
3891     int64_t PartBegin = VA.getLocMemOffset();
3892     int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3893     int FI = MFI.getObjectIndexBegin();
3894     for (; MFI.isFixedObjectIndex(FI); ++FI) {
3895       int64_t ObjBegin = MFI.getObjectOffset(FI);
3896       int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3897       if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3898         break;
3899     }
3900     if (MFI.isFixedObjectIndex(FI)) {
3901       SDValue Addr =
3902           DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3903                       DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3904       return DAG.getLoad(ValVT, dl, Chain, Addr,
3905                          MachinePointerInfo::getFixedStack(
3906                              DAG.getMachineFunction(), FI, Ins[i].PartOffset));
3907     }
3908   }
3909 
3910   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3911                                  VA.getLocMemOffset(), isImmutable);
3912 
3913   // Set SExt or ZExt flag.
3914   if (VA.getLocInfo() == CCValAssign::ZExt) {
3915     MFI.setObjectZExt(FI, true);
3916   } else if (VA.getLocInfo() == CCValAssign::SExt) {
3917     MFI.setObjectSExt(FI, true);
3918   }
3919 
3920   MaybeAlign Alignment;
3921   if (Subtarget.isTargetWindowsMSVC() && !Subtarget.is64Bit() &&
3922       ValVT != MVT::f80)
3923     Alignment = MaybeAlign(4);
3924   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3925   SDValue Val = DAG.getLoad(
3926       ValVT, dl, Chain, FIN,
3927       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3928       Alignment);
3929   return ExtendedInMem
3930              ? (VA.getValVT().isVector()
3931                     ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3932                     : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3933              : Val;
3934 }
3935 
3936 // FIXME: Get this from tablegen.
3937 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3938                                                 const X86Subtarget &Subtarget) {
3939   assert(Subtarget.is64Bit());
3940 
3941   if (Subtarget.isCallingConvWin64(CallConv)) {
3942     static const MCPhysReg GPR64ArgRegsWin64[] = {
3943       X86::RCX, X86::RDX, X86::R8,  X86::R9
3944     };
3945     return ArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3946   }
3947 
3948   static const MCPhysReg GPR64ArgRegs64Bit[] = {
3949     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3950   };
3951   return ArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3952 }
3953 
3954 // FIXME: Get this from tablegen.
3955 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3956                                                 CallingConv::ID CallConv,
3957                                                 const X86Subtarget &Subtarget) {
3958   assert(Subtarget.is64Bit());
3959   if (Subtarget.isCallingConvWin64(CallConv)) {
3960     // The XMM registers which might contain var arg parameters are shadowed
3961     // in their paired GPR.  So we only need to save the GPR to their home
3962     // slots.
3963     // TODO: __vectorcall will change this.
3964     return std::nullopt;
3965   }
3966 
3967   bool isSoftFloat = Subtarget.useSoftFloat();
3968   if (isSoftFloat || !Subtarget.hasSSE1())
3969     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3970     // registers.
3971     return std::nullopt;
3972 
3973   static const MCPhysReg XMMArgRegs64Bit[] = {
3974     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3975     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3976   };
3977   return ArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3978 }
3979 
3980 #ifndef NDEBUG
3981 static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3982   return llvm::is_sorted(
3983       ArgLocs, [](const CCValAssign &A, const CCValAssign &B) -> bool {
3984         return A.getValNo() < B.getValNo();
3985       });
3986 }
3987 #endif
3988 
3989 namespace {
3990 /// This is a helper class for lowering variable arguments parameters.
3991 class VarArgsLoweringHelper {
3992 public:
3993   VarArgsLoweringHelper(X86MachineFunctionInfo *FuncInfo, const SDLoc &Loc,
3994                         SelectionDAG &DAG, const X86Subtarget &Subtarget,
3995                         CallingConv::ID CallConv, CCState &CCInfo)
3996       : FuncInfo(FuncInfo), DL(Loc), DAG(DAG), Subtarget(Subtarget),
3997         TheMachineFunction(DAG.getMachineFunction()),
3998         TheFunction(TheMachineFunction.getFunction()),
3999         FrameInfo(TheMachineFunction.getFrameInfo()),
4000         FrameLowering(*Subtarget.getFrameLowering()),
4001         TargLowering(DAG.getTargetLoweringInfo()), CallConv(CallConv),
4002         CCInfo(CCInfo) {}
4003 
4004   // Lower variable arguments parameters.
4005   void lowerVarArgsParameters(SDValue &Chain, unsigned StackSize);
4006 
4007 private:
4008   void createVarArgAreaAndStoreRegisters(SDValue &Chain, unsigned StackSize);
4009 
4010   void forwardMustTailParameters(SDValue &Chain);
4011 
4012   bool is64Bit() const { return Subtarget.is64Bit(); }
4013   bool isWin64() const { return Subtarget.isCallingConvWin64(CallConv); }
4014 
4015   X86MachineFunctionInfo *FuncInfo;
4016   const SDLoc &DL;
4017   SelectionDAG &DAG;
4018   const X86Subtarget &Subtarget;
4019   MachineFunction &TheMachineFunction;
4020   const Function &TheFunction;
4021   MachineFrameInfo &FrameInfo;
4022   const TargetFrameLowering &FrameLowering;
4023   const TargetLowering &TargLowering;
4024   CallingConv::ID CallConv;
4025   CCState &CCInfo;
4026 };
4027 } // namespace
4028 
4029 void VarArgsLoweringHelper::createVarArgAreaAndStoreRegisters(
4030     SDValue &Chain, unsigned StackSize) {
4031   // If the function takes variable number of arguments, make a frame index for
4032   // the start of the first vararg value... for expansion of llvm.va_start. We
4033   // can skip this if there are no va_start calls.
4034   if (is64Bit() || (CallConv != CallingConv::X86_FastCall &&
4035                     CallConv != CallingConv::X86_ThisCall)) {
4036     FuncInfo->setVarArgsFrameIndex(
4037         FrameInfo.CreateFixedObject(1, StackSize, true));
4038   }
4039 
4040   // 64-bit calling conventions support varargs and register parameters, so we
4041   // have to do extra work to spill them in the prologue.
4042   if (is64Bit()) {
4043     // Find the first unallocated argument registers.
4044     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
4045     ArrayRef<MCPhysReg> ArgXMMs =
4046         get64BitArgumentXMMs(TheMachineFunction, CallConv, Subtarget);
4047     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
4048     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
4049 
4050     assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
4051            "SSE register cannot be used when SSE is disabled!");
4052 
4053     if (isWin64()) {
4054       // Get to the caller-allocated home save location.  Add 8 to account
4055       // for the return address.
4056       int HomeOffset = FrameLowering.getOffsetOfLocalArea() + 8;
4057       FuncInfo->setRegSaveFrameIndex(
4058           FrameInfo.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
4059       // Fixup to set vararg frame on shadow area (4 x i64).
4060       if (NumIntRegs < 4)
4061         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
4062     } else {
4063       // For X86-64, if there are vararg parameters that are passed via
4064       // registers, then we must store them to their spots on the stack so
4065       // they may be loaded by dereferencing the result of va_next.
4066       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
4067       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
4068       FuncInfo->setRegSaveFrameIndex(FrameInfo.CreateStackObject(
4069           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, Align(16), false));
4070     }
4071 
4072     SmallVector<SDValue, 6>
4073         LiveGPRs; // list of SDValue for GPR registers keeping live input value
4074     SmallVector<SDValue, 8> LiveXMMRegs; // list of SDValue for XMM registers
4075                                          // keeping live input value
4076     SDValue ALVal; // if applicable keeps SDValue for %al register
4077 
4078     // Gather all the live in physical registers.
4079     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
4080       Register GPR = TheMachineFunction.addLiveIn(Reg, &X86::GR64RegClass);
4081       LiveGPRs.push_back(DAG.getCopyFromReg(Chain, DL, GPR, MVT::i64));
4082     }
4083     const auto &AvailableXmms = ArgXMMs.slice(NumXMMRegs);
4084     if (!AvailableXmms.empty()) {
4085       Register AL = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
4086       ALVal = DAG.getCopyFromReg(Chain, DL, AL, MVT::i8);
4087       for (MCPhysReg Reg : AvailableXmms) {
4088         // FastRegisterAllocator spills virtual registers at basic
4089         // block boundary. That leads to usages of xmm registers
4090         // outside of check for %al. Pass physical registers to
4091         // VASTART_SAVE_XMM_REGS to avoid unneccessary spilling.
4092         TheMachineFunction.getRegInfo().addLiveIn(Reg);
4093         LiveXMMRegs.push_back(DAG.getRegister(Reg, MVT::v4f32));
4094       }
4095     }
4096 
4097     // Store the integer parameter registers.
4098     SmallVector<SDValue, 8> MemOps;
4099     SDValue RSFIN =
4100         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
4101                           TargLowering.getPointerTy(DAG.getDataLayout()));
4102     unsigned Offset = FuncInfo->getVarArgsGPOffset();
4103     for (SDValue Val : LiveGPRs) {
4104       SDValue FIN = DAG.getNode(ISD::ADD, DL,
4105                                 TargLowering.getPointerTy(DAG.getDataLayout()),
4106                                 RSFIN, DAG.getIntPtrConstant(Offset, DL));
4107       SDValue Store =
4108           DAG.getStore(Val.getValue(1), DL, Val, FIN,
4109                        MachinePointerInfo::getFixedStack(
4110                            DAG.getMachineFunction(),
4111                            FuncInfo->getRegSaveFrameIndex(), Offset));
4112       MemOps.push_back(Store);
4113       Offset += 8;
4114     }
4115 
4116     // Now store the XMM (fp + vector) parameter registers.
4117     if (!LiveXMMRegs.empty()) {
4118       SmallVector<SDValue, 12> SaveXMMOps;
4119       SaveXMMOps.push_back(Chain);
4120       SaveXMMOps.push_back(ALVal);
4121       SaveXMMOps.push_back(RSFIN);
4122       SaveXMMOps.push_back(
4123           DAG.getTargetConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32));
4124       llvm::append_range(SaveXMMOps, LiveXMMRegs);
4125       MachineMemOperand *StoreMMO =
4126           DAG.getMachineFunction().getMachineMemOperand(
4127               MachinePointerInfo::getFixedStack(
4128                   DAG.getMachineFunction(), FuncInfo->getRegSaveFrameIndex(),
4129                   Offset),
4130               MachineMemOperand::MOStore, 128, Align(16));
4131       MemOps.push_back(DAG.getMemIntrinsicNode(X86ISD::VASTART_SAVE_XMM_REGS,
4132                                                DL, DAG.getVTList(MVT::Other),
4133                                                SaveXMMOps, MVT::i8, StoreMMO));
4134     }
4135 
4136     if (!MemOps.empty())
4137       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4138   }
4139 }
4140 
4141 void VarArgsLoweringHelper::forwardMustTailParameters(SDValue &Chain) {
4142   // Find the largest legal vector type.
4143   MVT VecVT = MVT::Other;
4144   // FIXME: Only some x86_32 calling conventions support AVX512.
4145   if (Subtarget.useAVX512Regs() &&
4146       (is64Bit() || (CallConv == CallingConv::X86_VectorCall ||
4147                      CallConv == CallingConv::Intel_OCL_BI)))
4148     VecVT = MVT::v16f32;
4149   else if (Subtarget.hasAVX())
4150     VecVT = MVT::v8f32;
4151   else if (Subtarget.hasSSE2())
4152     VecVT = MVT::v4f32;
4153 
4154   // We forward some GPRs and some vector types.
4155   SmallVector<MVT, 2> RegParmTypes;
4156   MVT IntVT = is64Bit() ? MVT::i64 : MVT::i32;
4157   RegParmTypes.push_back(IntVT);
4158   if (VecVT != MVT::Other)
4159     RegParmTypes.push_back(VecVT);
4160 
4161   // Compute the set of forwarded registers. The rest are scratch.
4162   SmallVectorImpl<ForwardedRegister> &Forwards =
4163       FuncInfo->getForwardedMustTailRegParms();
4164   CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
4165 
4166   // Forward AL for SysV x86_64 targets, since it is used for varargs.
4167   if (is64Bit() && !isWin64() && !CCInfo.isAllocated(X86::AL)) {
4168     Register ALVReg = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
4169     Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
4170   }
4171 
4172   // Copy all forwards from physical to virtual registers.
4173   for (ForwardedRegister &FR : Forwards) {
4174     // FIXME: Can we use a less constrained schedule?
4175     SDValue RegVal = DAG.getCopyFromReg(Chain, DL, FR.VReg, FR.VT);
4176     FR.VReg = TheMachineFunction.getRegInfo().createVirtualRegister(
4177         TargLowering.getRegClassFor(FR.VT));
4178     Chain = DAG.getCopyToReg(Chain, DL, FR.VReg, RegVal);
4179   }
4180 }
4181 
4182 void VarArgsLoweringHelper::lowerVarArgsParameters(SDValue &Chain,
4183                                                    unsigned StackSize) {
4184   // Set FrameIndex to the 0xAAAAAAA value to mark unset state.
4185   // If necessary, it would be set into the correct value later.
4186   FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
4187   FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
4188 
4189   if (FrameInfo.hasVAStart())
4190     createVarArgAreaAndStoreRegisters(Chain, StackSize);
4191 
4192   if (FrameInfo.hasMustTailInVarArgFunc())
4193     forwardMustTailParameters(Chain);
4194 }
4195 
4196 SDValue X86TargetLowering::LowerFormalArguments(
4197     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
4198     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4199     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4200   MachineFunction &MF = DAG.getMachineFunction();
4201   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4202 
4203   const Function &F = MF.getFunction();
4204   if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
4205       F.getName() == "main")
4206     FuncInfo->setForceFramePointer(true);
4207 
4208   MachineFrameInfo &MFI = MF.getFrameInfo();
4209   bool Is64Bit = Subtarget.is64Bit();
4210   bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
4211 
4212   assert(
4213       !(IsVarArg && canGuaranteeTCO(CallConv)) &&
4214       "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
4215 
4216   // Assign locations to all of the incoming arguments.
4217   SmallVector<CCValAssign, 16> ArgLocs;
4218   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
4219 
4220   // Allocate shadow area for Win64.
4221   if (IsWin64)
4222     CCInfo.AllocateStack(32, Align(8));
4223 
4224   CCInfo.AnalyzeArguments(Ins, CC_X86);
4225 
4226   // In vectorcall calling convention a second pass is required for the HVA
4227   // types.
4228   if (CallingConv::X86_VectorCall == CallConv) {
4229     CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
4230   }
4231 
4232   // The next loop assumes that the locations are in the same order of the
4233   // input arguments.
4234   assert(isSortedByValueNo(ArgLocs) &&
4235          "Argument Location list must be sorted before lowering");
4236 
4237   SDValue ArgValue;
4238   for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
4239        ++I, ++InsIndex) {
4240     assert(InsIndex < Ins.size() && "Invalid Ins index");
4241     CCValAssign &VA = ArgLocs[I];
4242 
4243     if (VA.isRegLoc()) {
4244       EVT RegVT = VA.getLocVT();
4245       if (VA.needsCustom()) {
4246         assert(
4247             VA.getValVT() == MVT::v64i1 &&
4248             "Currently the only custom case is when we split v64i1 to 2 regs");
4249 
4250         // v64i1 values, in regcall calling convention, that are
4251         // compiled to 32 bit arch, are split up into two registers.
4252         ArgValue =
4253             getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
4254       } else {
4255         const TargetRegisterClass *RC;
4256         if (RegVT == MVT::i8)
4257           RC = &X86::GR8RegClass;
4258         else if (RegVT == MVT::i16)
4259           RC = &X86::GR16RegClass;
4260         else if (RegVT == MVT::i32)
4261           RC = &X86::GR32RegClass;
4262         else if (Is64Bit && RegVT == MVT::i64)
4263           RC = &X86::GR64RegClass;
4264         else if (RegVT == MVT::f16)
4265           RC = Subtarget.hasAVX512() ? &X86::FR16XRegClass : &X86::FR16RegClass;
4266         else if (RegVT == MVT::f32)
4267           RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
4268         else if (RegVT == MVT::f64)
4269           RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
4270         else if (RegVT == MVT::f80)
4271           RC = &X86::RFP80RegClass;
4272         else if (RegVT == MVT::f128)
4273           RC = &X86::VR128RegClass;
4274         else if (RegVT.is512BitVector())
4275           RC = &X86::VR512RegClass;
4276         else if (RegVT.is256BitVector())
4277           RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
4278         else if (RegVT.is128BitVector())
4279           RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
4280         else if (RegVT == MVT::x86mmx)
4281           RC = &X86::VR64RegClass;
4282         else if (RegVT == MVT::v1i1)
4283           RC = &X86::VK1RegClass;
4284         else if (RegVT == MVT::v8i1)
4285           RC = &X86::VK8RegClass;
4286         else if (RegVT == MVT::v16i1)
4287           RC = &X86::VK16RegClass;
4288         else if (RegVT == MVT::v32i1)
4289           RC = &X86::VK32RegClass;
4290         else if (RegVT == MVT::v64i1)
4291           RC = &X86::VK64RegClass;
4292         else
4293           llvm_unreachable("Unknown argument type!");
4294 
4295         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4296         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4297       }
4298 
4299       // If this is an 8 or 16-bit value, it is really passed promoted to 32
4300       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
4301       // right size.
4302       if (VA.getLocInfo() == CCValAssign::SExt)
4303         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4304                                DAG.getValueType(VA.getValVT()));
4305       else if (VA.getLocInfo() == CCValAssign::ZExt)
4306         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4307                                DAG.getValueType(VA.getValVT()));
4308       else if (VA.getLocInfo() == CCValAssign::BCvt)
4309         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
4310 
4311       if (VA.isExtInLoc()) {
4312         // Handle MMX values passed in XMM regs.
4313         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
4314           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
4315         else if (VA.getValVT().isVector() &&
4316                  VA.getValVT().getScalarType() == MVT::i1 &&
4317                  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
4318                   (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
4319           // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
4320           ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
4321         } else
4322           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4323       }
4324     } else {
4325       assert(VA.isMemLoc());
4326       ArgValue =
4327           LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
4328     }
4329 
4330     // If value is passed via pointer - do a load.
4331     if (VA.getLocInfo() == CCValAssign::Indirect &&
4332         !(Ins[I].Flags.isByVal() && VA.isRegLoc())) {
4333       ArgValue =
4334           DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
4335     }
4336 
4337     InVals.push_back(ArgValue);
4338   }
4339 
4340   for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
4341     if (Ins[I].Flags.isSwiftAsync()) {
4342       auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
4343       if (Subtarget.is64Bit())
4344         X86FI->setHasSwiftAsyncContext(true);
4345       else {
4346         int FI = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
4347         X86FI->setSwiftAsyncContextFrameIdx(FI);
4348         SDValue St = DAG.getStore(DAG.getEntryNode(), dl, InVals[I],
4349                                   DAG.getFrameIndex(FI, MVT::i32),
4350                                   MachinePointerInfo::getFixedStack(MF, FI));
4351         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, St, Chain);
4352       }
4353     }
4354 
4355     // Swift calling convention does not require we copy the sret argument
4356     // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
4357     if (CallConv == CallingConv::Swift || CallConv == CallingConv::SwiftTail)
4358       continue;
4359 
4360     // All x86 ABIs require that for returning structs by value we copy the
4361     // sret argument into %rax/%eax (depending on ABI) for the return. Save
4362     // the argument into a virtual register so that we can access it from the
4363     // return points.
4364     if (Ins[I].Flags.isSRet()) {
4365       assert(!FuncInfo->getSRetReturnReg() &&
4366              "SRet return has already been set");
4367       MVT PtrTy = getPointerTy(DAG.getDataLayout());
4368       Register Reg =
4369           MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
4370       FuncInfo->setSRetReturnReg(Reg);
4371       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
4372       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
4373       break;
4374     }
4375   }
4376 
4377   unsigned StackSize = CCInfo.getStackSize();
4378   // Align stack specially for tail calls.
4379   if (shouldGuaranteeTCO(CallConv,
4380                          MF.getTarget().Options.GuaranteedTailCallOpt))
4381     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
4382 
4383   if (IsVarArg)
4384     VarArgsLoweringHelper(FuncInfo, dl, DAG, Subtarget, CallConv, CCInfo)
4385         .lowerVarArgsParameters(Chain, StackSize);
4386 
4387   // Some CCs need callee pop.
4388   if (X86::isCalleePop(CallConv, Is64Bit, IsVarArg,
4389                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
4390     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
4391   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
4392     // X86 interrupts must pop the error code (and the alignment padding) if
4393     // present.
4394     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
4395   } else {
4396     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
4397     // If this is an sret function, the return should pop the hidden pointer.
4398     if (!canGuaranteeTCO(CallConv) && hasCalleePopSRet(Ins, Subtarget))
4399       FuncInfo->setBytesToPopOnReturn(4);
4400   }
4401 
4402   if (!Is64Bit) {
4403     // RegSaveFrameIndex is X86-64 only.
4404     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
4405   }
4406 
4407   FuncInfo->setArgumentStackSize(StackSize);
4408 
4409   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
4410     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
4411     if (Personality == EHPersonality::CoreCLR) {
4412       assert(Is64Bit);
4413       // TODO: Add a mechanism to frame lowering that will allow us to indicate
4414       // that we'd prefer this slot be allocated towards the bottom of the frame
4415       // (i.e. near the stack pointer after allocating the frame).  Every
4416       // funclet needs a copy of this slot in its (mostly empty) frame, and the
4417       // offset from the bottom of this and each funclet's frame must be the
4418       // same, so the size of funclets' (mostly empty) frames is dictated by
4419       // how far this slot is from the bottom (since they allocate just enough
4420       // space to accommodate holding this slot at the correct offset).
4421       int PSPSymFI = MFI.CreateStackObject(8, Align(8), /*isSpillSlot=*/false);
4422       EHInfo->PSPSymFrameIdx = PSPSymFI;
4423     }
4424   }
4425 
4426   if (shouldDisableArgRegFromCSR(CallConv) ||
4427       F.hasFnAttribute("no_caller_saved_registers")) {
4428     MachineRegisterInfo &MRI = MF.getRegInfo();
4429     for (std::pair<Register, Register> Pair : MRI.liveins())
4430       MRI.disableCalleeSavedRegister(Pair.first);
4431   }
4432 
4433   return Chain;
4434 }
4435 
4436 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
4437                                             SDValue Arg, const SDLoc &dl,
4438                                             SelectionDAG &DAG,
4439                                             const CCValAssign &VA,
4440                                             ISD::ArgFlagsTy Flags,
4441                                             bool isByVal) const {
4442   unsigned LocMemOffset = VA.getLocMemOffset();
4443   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4444   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4445                        StackPtr, PtrOff);
4446   if (isByVal)
4447     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
4448 
4449   MaybeAlign Alignment;
4450   if (Subtarget.isTargetWindowsMSVC() && !Subtarget.is64Bit() &&
4451       Arg.getSimpleValueType() != MVT::f80)
4452     Alignment = MaybeAlign(4);
4453   return DAG.getStore(
4454       Chain, dl, Arg, PtrOff,
4455       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
4456       Alignment);
4457 }
4458 
4459 /// Emit a load of return address if tail call
4460 /// optimization is performed and it is required.
4461 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
4462     SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
4463     bool Is64Bit, int FPDiff, const SDLoc &dl) const {
4464   // Adjust the Return address stack slot.
4465   EVT VT = getPointerTy(DAG.getDataLayout());
4466   OutRetAddr = getReturnAddressFrameIndex(DAG);
4467 
4468   // Load the "old" Return address.
4469   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
4470   return SDValue(OutRetAddr.getNode(), 1);
4471 }
4472 
4473 /// Emit a store of the return address if tail call
4474 /// optimization is performed and it is required (FPDiff!=0).
4475 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
4476                                         SDValue Chain, SDValue RetAddrFrIdx,
4477                                         EVT PtrVT, unsigned SlotSize,
4478                                         int FPDiff, const SDLoc &dl) {
4479   // Store the return address to the appropriate stack slot.
4480   if (!FPDiff) return Chain;
4481   // Calculate the new stack slot for the return address.
4482   int NewReturnAddrFI =
4483     MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
4484                                          false);
4485   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
4486   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
4487                        MachinePointerInfo::getFixedStack(
4488                            DAG.getMachineFunction(), NewReturnAddrFI));
4489   return Chain;
4490 }
4491 
4492 /// Returns a vector_shuffle mask for an movs{s|d}, movd
4493 /// operation of specified width.
4494 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
4495                        SDValue V2) {
4496   unsigned NumElems = VT.getVectorNumElements();
4497   SmallVector<int, 8> Mask;
4498   Mask.push_back(NumElems);
4499   for (unsigned i = 1; i != NumElems; ++i)
4500     Mask.push_back(i);
4501   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
4502 }
4503 
4504 SDValue
4505 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4506                              SmallVectorImpl<SDValue> &InVals) const {
4507   SelectionDAG &DAG                     = CLI.DAG;
4508   SDLoc &dl                             = CLI.DL;
4509   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4510   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4511   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4512   SDValue Chain                         = CLI.Chain;
4513   SDValue Callee                        = CLI.Callee;
4514   CallingConv::ID CallConv              = CLI.CallConv;
4515   bool &isTailCall                      = CLI.IsTailCall;
4516   bool isVarArg                         = CLI.IsVarArg;
4517   const auto *CB                        = CLI.CB;
4518 
4519   MachineFunction &MF = DAG.getMachineFunction();
4520   bool Is64Bit        = Subtarget.is64Bit();
4521   bool IsWin64        = Subtarget.isCallingConvWin64(CallConv);
4522   bool IsSibcall      = false;
4523   bool IsGuaranteeTCO = MF.getTarget().Options.GuaranteedTailCallOpt ||
4524       CallConv == CallingConv::Tail || CallConv == CallingConv::SwiftTail;
4525   bool IsCalleePopSRet = !IsGuaranteeTCO && hasCalleePopSRet(Outs, Subtarget);
4526   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
4527   bool HasNCSR = (CB && isa<CallInst>(CB) &&
4528                   CB->hasFnAttr("no_caller_saved_registers"));
4529   bool HasNoCfCheck = (CB && CB->doesNoCfCheck());
4530   bool IsIndirectCall = (CB && isa<CallInst>(CB) && CB->isIndirectCall());
4531   bool IsCFICall = IsIndirectCall && CLI.CFIType;
4532   const Module *M = MF.getMMI().getModule();
4533   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
4534 
4535   MachineFunction::CallSiteInfo CSInfo;
4536   if (CallConv == CallingConv::X86_INTR)
4537     report_fatal_error("X86 interrupts may not be called directly");
4538 
4539   bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
4540   if (Subtarget.isPICStyleGOT() && !IsGuaranteeTCO && !IsMustTail) {
4541     // If we are using a GOT, disable tail calls to external symbols with
4542     // default visibility. Tail calling such a symbol requires using a GOT
4543     // relocation, which forces early binding of the symbol. This breaks code
4544     // that require lazy function symbol resolution. Using musttail or
4545     // GuaranteedTailCallOpt will override this.
4546     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4547     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
4548                G->getGlobal()->hasDefaultVisibility()))
4549       isTailCall = false;
4550   }
4551 
4552   if (isTailCall && !IsMustTail) {
4553     // Check if it's really possible to do a tail call.
4554     isTailCall = IsEligibleForTailCallOptimization(
4555         Callee, CallConv, IsCalleePopSRet, isVarArg, CLI.RetTy, Outs, OutVals,
4556         Ins, DAG);
4557 
4558     // Sibcalls are automatically detected tailcalls which do not require
4559     // ABI changes.
4560     if (!IsGuaranteeTCO && isTailCall)
4561       IsSibcall = true;
4562 
4563     if (isTailCall)
4564       ++NumTailCalls;
4565   }
4566 
4567   if (IsMustTail && !isTailCall)
4568     report_fatal_error("failed to perform tail call elimination on a call "
4569                        "site marked musttail");
4570 
4571   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
4572          "Var args not supported with calling convention fastcc, ghc or hipe");
4573 
4574   // Analyze operands of the call, assigning locations to each operand.
4575   SmallVector<CCValAssign, 16> ArgLocs;
4576   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4577 
4578   // Allocate shadow area for Win64.
4579   if (IsWin64)
4580     CCInfo.AllocateStack(32, Align(8));
4581 
4582   CCInfo.AnalyzeArguments(Outs, CC_X86);
4583 
4584   // In vectorcall calling convention a second pass is required for the HVA
4585   // types.
4586   if (CallingConv::X86_VectorCall == CallConv) {
4587     CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
4588   }
4589 
4590   // Get a count of how many bytes are to be pushed on the stack.
4591   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
4592   if (IsSibcall)
4593     // This is a sibcall. The memory operands are available in caller's
4594     // own caller's stack.
4595     NumBytes = 0;
4596   else if (IsGuaranteeTCO && canGuaranteeTCO(CallConv))
4597     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
4598 
4599   int FPDiff = 0;
4600   if (isTailCall &&
4601       shouldGuaranteeTCO(CallConv,
4602                          MF.getTarget().Options.GuaranteedTailCallOpt)) {
4603     // Lower arguments at fp - stackoffset + fpdiff.
4604     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
4605 
4606     FPDiff = NumBytesCallerPushed - NumBytes;
4607 
4608     // Set the delta of movement of the returnaddr stackslot.
4609     // But only set if delta is greater than previous delta.
4610     if (FPDiff < X86Info->getTCReturnAddrDelta())
4611       X86Info->setTCReturnAddrDelta(FPDiff);
4612   }
4613 
4614   unsigned NumBytesToPush = NumBytes;
4615   unsigned NumBytesToPop = NumBytes;
4616 
4617   // If we have an inalloca argument, all stack space has already been allocated
4618   // for us and be right at the top of the stack.  We don't support multiple
4619   // arguments passed in memory when using inalloca.
4620   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
4621     NumBytesToPush = 0;
4622     if (!ArgLocs.back().isMemLoc())
4623       report_fatal_error("cannot use inalloca attribute on a register "
4624                          "parameter");
4625     if (ArgLocs.back().getLocMemOffset() != 0)
4626       report_fatal_error("any parameter with the inalloca attribute must be "
4627                          "the only memory argument");
4628   } else if (CLI.IsPreallocated) {
4629     assert(ArgLocs.back().isMemLoc() &&
4630            "cannot use preallocated attribute on a register "
4631            "parameter");
4632     SmallVector<size_t, 4> PreallocatedOffsets;
4633     for (size_t i = 0; i < CLI.OutVals.size(); ++i) {
4634       if (CLI.CB->paramHasAttr(i, Attribute::Preallocated)) {
4635         PreallocatedOffsets.push_back(ArgLocs[i].getLocMemOffset());
4636       }
4637     }
4638     auto *MFI = DAG.getMachineFunction().getInfo<X86MachineFunctionInfo>();
4639     size_t PreallocatedId = MFI->getPreallocatedIdForCallSite(CLI.CB);
4640     MFI->setPreallocatedStackSize(PreallocatedId, NumBytes);
4641     MFI->setPreallocatedArgOffsets(PreallocatedId, PreallocatedOffsets);
4642     NumBytesToPush = 0;
4643   }
4644 
4645   if (!IsSibcall && !IsMustTail)
4646     Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
4647                                  NumBytes - NumBytesToPush, dl);
4648 
4649   SDValue RetAddrFrIdx;
4650   // Load return address for tail calls.
4651   if (isTailCall && FPDiff)
4652     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
4653                                     Is64Bit, FPDiff, dl);
4654 
4655   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
4656   SmallVector<SDValue, 8> MemOpChains;
4657   SDValue StackPtr;
4658 
4659   // The next loop assumes that the locations are in the same order of the
4660   // input arguments.
4661   assert(isSortedByValueNo(ArgLocs) &&
4662          "Argument Location list must be sorted before lowering");
4663 
4664   // Walk the register/memloc assignments, inserting copies/loads.  In the case
4665   // of tail call optimization arguments are handle later.
4666   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4667   for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
4668        ++I, ++OutIndex) {
4669     assert(OutIndex < Outs.size() && "Invalid Out index");
4670     // Skip inalloca/preallocated arguments, they have already been written.
4671     ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
4672     if (Flags.isInAlloca() || Flags.isPreallocated())
4673       continue;
4674 
4675     CCValAssign &VA = ArgLocs[I];
4676     EVT RegVT = VA.getLocVT();
4677     SDValue Arg = OutVals[OutIndex];
4678     bool isByVal = Flags.isByVal();
4679 
4680     // Promote the value if needed.
4681     switch (VA.getLocInfo()) {
4682     default: llvm_unreachable("Unknown loc info!");
4683     case CCValAssign::Full: break;
4684     case CCValAssign::SExt:
4685       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
4686       break;
4687     case CCValAssign::ZExt:
4688       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
4689       break;
4690     case CCValAssign::AExt:
4691       if (Arg.getValueType().isVector() &&
4692           Arg.getValueType().getVectorElementType() == MVT::i1)
4693         Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
4694       else if (RegVT.is128BitVector()) {
4695         // Special case: passing MMX values in XMM registers.
4696         Arg = DAG.getBitcast(MVT::i64, Arg);
4697         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
4698         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
4699       } else
4700         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
4701       break;
4702     case CCValAssign::BCvt:
4703       Arg = DAG.getBitcast(RegVT, Arg);
4704       break;
4705     case CCValAssign::Indirect: {
4706       if (isByVal) {
4707         // Memcpy the argument to a temporary stack slot to prevent
4708         // the caller from seeing any modifications the callee may make
4709         // as guaranteed by the `byval` attribute.
4710         int FrameIdx = MF.getFrameInfo().CreateStackObject(
4711             Flags.getByValSize(),
4712             std::max(Align(16), Flags.getNonZeroByValAlign()), false);
4713         SDValue StackSlot =
4714             DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
4715         Chain =
4716             CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
4717         // From now on treat this as a regular pointer
4718         Arg = StackSlot;
4719         isByVal = false;
4720       } else {
4721         // Store the argument.
4722         SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
4723         int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
4724         Chain = DAG.getStore(
4725             Chain, dl, Arg, SpillSlot,
4726             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4727         Arg = SpillSlot;
4728       }
4729       break;
4730     }
4731     }
4732 
4733     if (VA.needsCustom()) {
4734       assert(VA.getValVT() == MVT::v64i1 &&
4735              "Currently the only custom case is when we split v64i1 to 2 regs");
4736       // Split v64i1 value into two registers
4737       Passv64i1ArgInRegs(dl, DAG, Arg, RegsToPass, VA, ArgLocs[++I], Subtarget);
4738     } else if (VA.isRegLoc()) {
4739       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4740       const TargetOptions &Options = DAG.getTarget().Options;
4741       if (Options.EmitCallSiteInfo)
4742         CSInfo.emplace_back(VA.getLocReg(), I);
4743       if (isVarArg && IsWin64) {
4744         // Win64 ABI requires argument XMM reg to be copied to the corresponding
4745         // shadow reg if callee is a varargs function.
4746         Register ShadowReg;
4747         switch (VA.getLocReg()) {
4748         case X86::XMM0: ShadowReg = X86::RCX; break;
4749         case X86::XMM1: ShadowReg = X86::RDX; break;
4750         case X86::XMM2: ShadowReg = X86::R8; break;
4751         case X86::XMM3: ShadowReg = X86::R9; break;
4752         }
4753         if (ShadowReg)
4754           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
4755       }
4756     } else if (!IsSibcall && (!isTailCall || isByVal)) {
4757       assert(VA.isMemLoc());
4758       if (!StackPtr.getNode())
4759         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4760                                       getPointerTy(DAG.getDataLayout()));
4761       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
4762                                              dl, DAG, VA, Flags, isByVal));
4763     }
4764   }
4765 
4766   if (!MemOpChains.empty())
4767     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4768 
4769   if (Subtarget.isPICStyleGOT()) {
4770     // ELF / PIC requires GOT in the EBX register before function calls via PLT
4771     // GOT pointer (except regcall).
4772     if (!isTailCall) {
4773       // Indirect call with RegCall calling convertion may use up all the
4774       // general registers, so it is not suitable to bind EBX reister for
4775       // GOT address, just let register allocator handle it.
4776       if (CallConv != CallingConv::X86_RegCall)
4777         RegsToPass.push_back(std::make_pair(
4778           Register(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
4779                                           getPointerTy(DAG.getDataLayout()))));
4780     } else {
4781       // If we are tail calling and generating PIC/GOT style code load the
4782       // address of the callee into ECX. The value in ecx is used as target of
4783       // the tail jump. This is done to circumvent the ebx/callee-saved problem
4784       // for tail calls on PIC/GOT architectures. Normally we would just put the
4785       // address of GOT into ebx and then call target@PLT. But for tail calls
4786       // ebx would be restored (since ebx is callee saved) before jumping to the
4787       // target@PLT.
4788 
4789       // Note: The actual moving to ECX is done further down.
4790       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4791       if (G && !G->getGlobal()->hasLocalLinkage() &&
4792           G->getGlobal()->hasDefaultVisibility())
4793         Callee = LowerGlobalAddress(Callee, DAG);
4794       else if (isa<ExternalSymbolSDNode>(Callee))
4795         Callee = LowerExternalSymbol(Callee, DAG);
4796     }
4797   }
4798 
4799   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail &&
4800       (Subtarget.hasSSE1() || !M->getModuleFlag("SkipRaxSetup"))) {
4801     // From AMD64 ABI document:
4802     // For calls that may call functions that use varargs or stdargs
4803     // (prototype-less calls or calls to functions containing ellipsis (...) in
4804     // the declaration) %al is used as hidden argument to specify the number
4805     // of SSE registers used. The contents of %al do not need to match exactly
4806     // the number of registers, but must be an ubound on the number of SSE
4807     // registers used and is in the range 0 - 8 inclusive.
4808 
4809     // Count the number of XMM registers allocated.
4810     static const MCPhysReg XMMArgRegs[] = {
4811       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4812       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
4813     };
4814     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
4815     assert((Subtarget.hasSSE1() || !NumXMMRegs)
4816            && "SSE registers cannot be used when SSE is disabled");
4817     RegsToPass.push_back(std::make_pair(Register(X86::AL),
4818                                         DAG.getConstant(NumXMMRegs, dl,
4819                                                         MVT::i8)));
4820   }
4821 
4822   if (isVarArg && IsMustTail) {
4823     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
4824     for (const auto &F : Forwards) {
4825       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
4826       RegsToPass.push_back(std::make_pair(F.PReg, Val));
4827     }
4828   }
4829 
4830   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
4831   // don't need this because the eligibility check rejects calls that require
4832   // shuffling arguments passed in memory.
4833   if (!IsSibcall && isTailCall) {
4834     // Force all the incoming stack arguments to be loaded from the stack
4835     // before any new outgoing arguments are stored to the stack, because the
4836     // outgoing stack slots may alias the incoming argument stack slots, and
4837     // the alias isn't otherwise explicit. This is slightly more conservative
4838     // than necessary, because it means that each store effectively depends
4839     // on every argument instead of just those arguments it would clobber.
4840     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
4841 
4842     SmallVector<SDValue, 8> MemOpChains2;
4843     SDValue FIN;
4844     int FI = 0;
4845     for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
4846          ++I, ++OutsIndex) {
4847       CCValAssign &VA = ArgLocs[I];
4848 
4849       if (VA.isRegLoc()) {
4850         if (VA.needsCustom()) {
4851           assert((CallConv == CallingConv::X86_RegCall) &&
4852                  "Expecting custom case only in regcall calling convention");
4853           // This means that we are in special case where one argument was
4854           // passed through two register locations - Skip the next location
4855           ++I;
4856         }
4857 
4858         continue;
4859       }
4860 
4861       assert(VA.isMemLoc());
4862       SDValue Arg = OutVals[OutsIndex];
4863       ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
4864       // Skip inalloca/preallocated arguments.  They don't require any work.
4865       if (Flags.isInAlloca() || Flags.isPreallocated())
4866         continue;
4867       // Create frame index.
4868       int32_t Offset = VA.getLocMemOffset()+FPDiff;
4869       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
4870       FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4871       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4872 
4873       if (Flags.isByVal()) {
4874         // Copy relative to framepointer.
4875         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
4876         if (!StackPtr.getNode())
4877           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4878                                         getPointerTy(DAG.getDataLayout()));
4879         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4880                              StackPtr, Source);
4881 
4882         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
4883                                                          ArgChain,
4884                                                          Flags, DAG, dl));
4885       } else {
4886         // Store relative to framepointer.
4887         MemOpChains2.push_back(DAG.getStore(
4888             ArgChain, dl, Arg, FIN,
4889             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4890       }
4891     }
4892 
4893     if (!MemOpChains2.empty())
4894       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4895 
4896     // Store the return address to the appropriate stack slot.
4897     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
4898                                      getPointerTy(DAG.getDataLayout()),
4899                                      RegInfo->getSlotSize(), FPDiff, dl);
4900   }
4901 
4902   // Build a sequence of copy-to-reg nodes chained together with token chain
4903   // and glue operands which copy the outgoing args into registers.
4904   SDValue InGlue;
4905   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4906     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4907                              RegsToPass[i].second, InGlue);
4908     InGlue = Chain.getValue(1);
4909   }
4910 
4911   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
4912     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
4913     // In the 64-bit large code model, we have to make all calls
4914     // through a register, since the call instruction's 32-bit
4915     // pc-relative offset may not be large enough to hold the whole
4916     // address.
4917   } else if (Callee->getOpcode() == ISD::GlobalAddress ||
4918              Callee->getOpcode() == ISD::ExternalSymbol) {
4919     // Lower direct calls to global addresses and external symbols. Setting
4920     // ForCall to true here has the effect of removing WrapperRIP when possible
4921     // to allow direct calls to be selected without first materializing the
4922     // address into a register.
4923     Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
4924   } else if (Subtarget.isTarget64BitILP32() &&
4925              Callee.getValueType() == MVT::i32) {
4926     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4927     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4928   }
4929 
4930   // Returns a chain & a glue for retval copy to use.
4931   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4932   SmallVector<SDValue, 8> Ops;
4933 
4934   if (!IsSibcall && isTailCall && !IsMustTail) {
4935     Chain = DAG.getCALLSEQ_END(Chain, NumBytesToPop, 0, InGlue, dl);
4936     InGlue = Chain.getValue(1);
4937   }
4938 
4939   Ops.push_back(Chain);
4940   Ops.push_back(Callee);
4941 
4942   if (isTailCall)
4943     Ops.push_back(DAG.getTargetConstant(FPDiff, dl, MVT::i32));
4944 
4945   // Add argument registers to the end of the list so that they are known live
4946   // into the call.
4947   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4948     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4949                                   RegsToPass[i].second.getValueType()));
4950 
4951   // Add a register mask operand representing the call-preserved registers.
4952   const uint32_t *Mask = [&]() {
4953     auto AdaptedCC = CallConv;
4954     // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists),
4955     // use X86_INTR calling convention because it has the same CSR mask
4956     // (same preserved registers).
4957     if (HasNCSR)
4958       AdaptedCC = (CallingConv::ID)CallingConv::X86_INTR;
4959     // If NoCalleeSavedRegisters is requested, than use GHC since it happens
4960     // to use the CSR_NoRegs_RegMask.
4961     if (CB && CB->hasFnAttr("no_callee_saved_registers"))
4962       AdaptedCC = (CallingConv::ID)CallingConv::GHC;
4963     return RegInfo->getCallPreservedMask(MF, AdaptedCC);
4964   }();
4965   assert(Mask && "Missing call preserved mask for calling convention");
4966 
4967   // If this is an invoke in a 32-bit function using a funclet-based
4968   // personality, assume the function clobbers all registers. If an exception
4969   // is thrown, the runtime will not restore CSRs.
4970   // FIXME: Model this more precisely so that we can register allocate across
4971   // the normal edge and spill and fill across the exceptional edge.
4972   if (!Is64Bit && CLI.CB && isa<InvokeInst>(CLI.CB)) {
4973     const Function &CallerFn = MF.getFunction();
4974     EHPersonality Pers =
4975         CallerFn.hasPersonalityFn()
4976             ? classifyEHPersonality(CallerFn.getPersonalityFn())
4977             : EHPersonality::Unknown;
4978     if (isFuncletEHPersonality(Pers))
4979       Mask = RegInfo->getNoPreservedMask();
4980   }
4981 
4982   // Define a new register mask from the existing mask.
4983   uint32_t *RegMask = nullptr;
4984 
4985   // In some calling conventions we need to remove the used physical registers
4986   // from the reg mask. Create a new RegMask for such calling conventions.
4987   // RegMask for calling conventions that disable only return registers (e.g.
4988   // preserve_most) will be modified later in LowerCallResult.
4989   bool ShouldDisableArgRegs = shouldDisableArgRegFromCSR(CallConv) || HasNCSR;
4990   if (ShouldDisableArgRegs || shouldDisableRetRegFromCSR(CallConv)) {
4991     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4992 
4993     // Allocate a new Reg Mask and copy Mask.
4994     RegMask = MF.allocateRegMask();
4995     unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4996     memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4997 
4998     // Make sure all sub registers of the argument registers are reset
4999     // in the RegMask.
5000     if (ShouldDisableArgRegs) {
5001       for (auto const &RegPair : RegsToPass)
5002         for (MCPhysReg SubReg : TRI->subregs_inclusive(RegPair.first))
5003           RegMask[SubReg / 32] &= ~(1u << (SubReg % 32));
5004     }
5005 
5006     // Create the RegMask Operand according to our updated mask.
5007     Ops.push_back(DAG.getRegisterMask(RegMask));
5008   } else {
5009     // Create the RegMask Operand according to the static mask.
5010     Ops.push_back(DAG.getRegisterMask(Mask));
5011   }
5012 
5013   if (InGlue.getNode())
5014     Ops.push_back(InGlue);
5015 
5016   if (isTailCall) {
5017     // We used to do:
5018     //// If this is the first return lowered for this function, add the regs
5019     //// to the liveout set for the function.
5020     // This isn't right, although it's probably harmless on x86; liveouts
5021     // should be computed from returns not tail calls.  Consider a void
5022     // function making a tail call to a function returning int.
5023     MF.getFrameInfo().setHasTailCall();
5024     SDValue Ret = DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
5025 
5026     if (IsCFICall)
5027       Ret.getNode()->setCFIType(CLI.CFIType->getZExtValue());
5028 
5029     DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
5030     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
5031     return Ret;
5032   }
5033 
5034   if (HasNoCfCheck && IsCFProtectionSupported && IsIndirectCall) {
5035     Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
5036   } else if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
5037     // Calls with a "clang.arc.attachedcall" bundle are special. They should be
5038     // expanded to the call, directly followed by a special marker sequence and
5039     // a call to a ObjC library function. Use the CALL_RVMARKER to do that.
5040     assert(!isTailCall &&
5041            "tail calls cannot be marked with clang.arc.attachedcall");
5042     assert(Is64Bit && "clang.arc.attachedcall is only supported in 64bit mode");
5043 
5044     // Add a target global address for the retainRV/claimRV runtime function
5045     // just before the call target.
5046     Function *ARCFn = *objcarc::getAttachedARCFunction(CLI.CB);
5047     auto PtrVT = getPointerTy(DAG.getDataLayout());
5048     auto GA = DAG.getTargetGlobalAddress(ARCFn, dl, PtrVT);
5049     Ops.insert(Ops.begin() + 1, GA);
5050     Chain = DAG.getNode(X86ISD::CALL_RVMARKER, dl, NodeTys, Ops);
5051   } else {
5052     Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
5053   }
5054 
5055   if (IsCFICall)
5056     Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
5057 
5058   InGlue = Chain.getValue(1);
5059   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
5060   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
5061 
5062   // Save heapallocsite metadata.
5063   if (CLI.CB)
5064     if (MDNode *HeapAlloc = CLI.CB->getMetadata("heapallocsite"))
5065       DAG.addHeapAllocSite(Chain.getNode(), HeapAlloc);
5066 
5067   // Create the CALLSEQ_END node.
5068   unsigned NumBytesForCalleeToPop = 0; // Callee pops nothing.
5069   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
5070                        DAG.getTarget().Options.GuaranteedTailCallOpt))
5071     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
5072   else if (!canGuaranteeTCO(CallConv) && IsCalleePopSRet)
5073     // If this call passes a struct-return pointer, the callee
5074     // pops that struct pointer.
5075     NumBytesForCalleeToPop = 4;
5076 
5077   // Returns a glue for retval copy to use.
5078   if (!IsSibcall) {
5079     Chain = DAG.getCALLSEQ_END(Chain, NumBytesToPop, NumBytesForCalleeToPop,
5080                                InGlue, dl);
5081     InGlue = Chain.getValue(1);
5082   }
5083 
5084   // Handle result values, copying them out of physregs into vregs that we
5085   // return.
5086   return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl, DAG,
5087                          InVals, RegMask);
5088 }
5089 
5090 //===----------------------------------------------------------------------===//
5091 //                Fast Calling Convention (tail call) implementation
5092 //===----------------------------------------------------------------------===//
5093 
5094 //  Like std call, callee cleans arguments, convention except that ECX is
5095 //  reserved for storing the tail called function address. Only 2 registers are
5096 //  free for argument passing (inreg). Tail call optimization is performed
5097 //  provided:
5098 //                * tailcallopt is enabled
5099 //                * caller/callee are fastcc
5100 //  On X86_64 architecture with GOT-style position independent code only local
5101 //  (within module) calls are supported at the moment.
5102 //  To keep the stack aligned according to platform abi the function
5103 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
5104 //  of stack alignment. (Dynamic linkers need this - Darwin's dyld for example)
5105 //  If a tail called function callee has more arguments than the caller the
5106 //  caller needs to make sure that there is room to move the RETADDR to. This is
5107 //  achieved by reserving an area the size of the argument delta right after the
5108 //  original RETADDR, but before the saved framepointer or the spilled registers
5109 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
5110 //  stack layout:
5111 //    arg1
5112 //    arg2
5113 //    RETADDR
5114 //    [ new RETADDR
5115 //      move area ]
5116 //    (possible EBP)
5117 //    ESI
5118 //    EDI
5119 //    local1 ..
5120 
5121 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
5122 /// requirement.
5123 unsigned
5124 X86TargetLowering::GetAlignedArgumentStackSize(const unsigned StackSize,
5125                                                SelectionDAG &DAG) const {
5126   const Align StackAlignment = Subtarget.getFrameLowering()->getStackAlign();
5127   const uint64_t SlotSize = Subtarget.getRegisterInfo()->getSlotSize();
5128   assert(StackSize % SlotSize == 0 &&
5129          "StackSize must be a multiple of SlotSize");
5130   return alignTo(StackSize + SlotSize, StackAlignment) - SlotSize;
5131 }
5132 
5133 /// Return true if the given stack call argument is already available in the
5134 /// same position (relatively) of the caller's incoming argument stack.
5135 static
5136 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
5137                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
5138                          const X86InstrInfo *TII, const CCValAssign &VA) {
5139   unsigned Bytes = Arg.getValueSizeInBits() / 8;
5140 
5141   for (;;) {
5142     // Look through nodes that don't alter the bits of the incoming value.
5143     unsigned Op = Arg.getOpcode();
5144     if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
5145       Arg = Arg.getOperand(0);
5146       continue;
5147     }
5148     if (Op == ISD::TRUNCATE) {
5149       const SDValue &TruncInput = Arg.getOperand(0);
5150       if (TruncInput.getOpcode() == ISD::AssertZext &&
5151           cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
5152               Arg.getValueType()) {
5153         Arg = TruncInput.getOperand(0);
5154         continue;
5155       }
5156     }
5157     break;
5158   }
5159 
5160   int FI = INT_MAX;
5161   if (Arg.getOpcode() == ISD::CopyFromReg) {
5162     Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
5163     if (!VR.isVirtual())
5164       return false;
5165     MachineInstr *Def = MRI->getVRegDef(VR);
5166     if (!Def)
5167       return false;
5168     if (!Flags.isByVal()) {
5169       if (!TII->isLoadFromStackSlot(*Def, FI))
5170         return false;
5171     } else {
5172       unsigned Opcode = Def->getOpcode();
5173       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
5174            Opcode == X86::LEA64_32r) &&
5175           Def->getOperand(1).isFI()) {
5176         FI = Def->getOperand(1).getIndex();
5177         Bytes = Flags.getByValSize();
5178       } else
5179         return false;
5180     }
5181   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
5182     if (Flags.isByVal())
5183       // ByVal argument is passed in as a pointer but it's now being
5184       // dereferenced. e.g.
5185       // define @foo(%struct.X* %A) {
5186       //   tail call @bar(%struct.X* byval %A)
5187       // }
5188       return false;
5189     SDValue Ptr = Ld->getBasePtr();
5190     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
5191     if (!FINode)
5192       return false;
5193     FI = FINode->getIndex();
5194   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
5195     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
5196     FI = FINode->getIndex();
5197     Bytes = Flags.getByValSize();
5198   } else
5199     return false;
5200 
5201   assert(FI != INT_MAX);
5202   if (!MFI.isFixedObjectIndex(FI))
5203     return false;
5204 
5205   if (Offset != MFI.getObjectOffset(FI))
5206     return false;
5207 
5208   // If this is not byval, check that the argument stack object is immutable.
5209   // inalloca and argument copy elision can create mutable argument stack
5210   // objects. Byval objects can be mutated, but a byval call intends to pass the
5211   // mutated memory.
5212   if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
5213     return false;
5214 
5215   if (VA.getLocVT().getFixedSizeInBits() >
5216       Arg.getValueSizeInBits().getFixedValue()) {
5217     // If the argument location is wider than the argument type, check that any
5218     // extension flags match.
5219     if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
5220         Flags.isSExt() != MFI.isObjectSExt(FI)) {
5221       return false;
5222     }
5223   }
5224 
5225   return Bytes == MFI.getObjectSize(FI);
5226 }
5227 
5228 /// Check whether the call is eligible for tail call optimization. Targets
5229 /// that want to do tail call optimization should implement this function.
5230 bool X86TargetLowering::IsEligibleForTailCallOptimization(
5231     SDValue Callee, CallingConv::ID CalleeCC, bool IsCalleePopSRet,
5232     bool isVarArg, Type *RetTy, const SmallVectorImpl<ISD::OutputArg> &Outs,
5233     const SmallVectorImpl<SDValue> &OutVals,
5234     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
5235   if (!mayTailCallThisCC(CalleeCC))
5236     return false;
5237 
5238   // If -tailcallopt is specified, make fastcc functions tail-callable.
5239   MachineFunction &MF = DAG.getMachineFunction();
5240   const Function &CallerF = MF.getFunction();
5241 
5242   // If the function return type is x86_fp80 and the callee return type is not,
5243   // then the FP_EXTEND of the call result is not a nop. It's not safe to
5244   // perform a tailcall optimization here.
5245   if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
5246     return false;
5247 
5248   CallingConv::ID CallerCC = CallerF.getCallingConv();
5249   bool CCMatch = CallerCC == CalleeCC;
5250   bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
5251   bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
5252   bool IsGuaranteeTCO = DAG.getTarget().Options.GuaranteedTailCallOpt ||
5253       CalleeCC == CallingConv::Tail || CalleeCC == CallingConv::SwiftTail;
5254 
5255   // Win64 functions have extra shadow space for argument homing. Don't do the
5256   // sibcall if the caller and callee have mismatched expectations for this
5257   // space.
5258   if (IsCalleeWin64 != IsCallerWin64)
5259     return false;
5260 
5261   if (IsGuaranteeTCO) {
5262     if (canGuaranteeTCO(CalleeCC) && CCMatch)
5263       return true;
5264     return false;
5265   }
5266 
5267   // Look for obvious safe cases to perform tail call optimization that do not
5268   // require ABI changes. This is what gcc calls sibcall.
5269 
5270   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
5271   // emit a special epilogue.
5272   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
5273   if (RegInfo->hasStackRealignment(MF))
5274     return false;
5275 
5276   // Also avoid sibcall optimization if we're an sret return fn and the callee
5277   // is incompatible. See comment in LowerReturn about why hasStructRetAttr is
5278   // insufficient.
5279   if (MF.getInfo<X86MachineFunctionInfo>()->getSRetReturnReg()) {
5280     // For a compatible tail call the callee must return our sret pointer. So it
5281     // needs to be (a) an sret function itself and (b) we pass our sret as its
5282     // sret. Condition #b is harder to determine.
5283     return false;
5284   } else if (IsCalleePopSRet)
5285     // The callee pops an sret, so we cannot tail-call, as our caller doesn't
5286     // expect that.
5287     return false;
5288 
5289   // Do not sibcall optimize vararg calls unless all arguments are passed via
5290   // registers.
5291   LLVMContext &C = *DAG.getContext();
5292   if (isVarArg && !Outs.empty()) {
5293     // Optimizing for varargs on Win64 is unlikely to be safe without
5294     // additional testing.
5295     if (IsCalleeWin64 || IsCallerWin64)
5296       return false;
5297 
5298     SmallVector<CCValAssign, 16> ArgLocs;
5299     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5300     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
5301     for (const auto &VA : ArgLocs)
5302       if (!VA.isRegLoc())
5303         return false;
5304   }
5305 
5306   // If the call result is in ST0 / ST1, it needs to be popped off the x87
5307   // stack.  Therefore, if it's not used by the call it is not safe to optimize
5308   // this into a sibcall.
5309   bool Unused = false;
5310   for (const auto &In : Ins) {
5311     if (!In.Used) {
5312       Unused = true;
5313       break;
5314     }
5315   }
5316   if (Unused) {
5317     SmallVector<CCValAssign, 16> RVLocs;
5318     CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
5319     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
5320     for (const auto &VA : RVLocs) {
5321       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
5322         return false;
5323     }
5324   }
5325 
5326   // Check that the call results are passed in the same way.
5327   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
5328                                   RetCC_X86, RetCC_X86))
5329     return false;
5330   // The callee has to preserve all registers the caller needs to preserve.
5331   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
5332   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
5333   if (!CCMatch) {
5334     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
5335     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
5336       return false;
5337   }
5338 
5339   unsigned StackArgsSize = 0;
5340 
5341   // If the callee takes no arguments then go on to check the results of the
5342   // call.
5343   if (!Outs.empty()) {
5344     // Check if stack adjustment is needed. For now, do not do this if any
5345     // argument is passed on the stack.
5346     SmallVector<CCValAssign, 16> ArgLocs;
5347     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5348 
5349     // Allocate shadow area for Win64
5350     if (IsCalleeWin64)
5351       CCInfo.AllocateStack(32, Align(8));
5352 
5353     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
5354     StackArgsSize = CCInfo.getStackSize();
5355 
5356     if (CCInfo.getStackSize()) {
5357       // Check if the arguments are already laid out in the right way as
5358       // the caller's fixed stack objects.
5359       MachineFrameInfo &MFI = MF.getFrameInfo();
5360       const MachineRegisterInfo *MRI = &MF.getRegInfo();
5361       const X86InstrInfo *TII = Subtarget.getInstrInfo();
5362       for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
5363         const CCValAssign &VA = ArgLocs[I];
5364         SDValue Arg = OutVals[I];
5365         ISD::ArgFlagsTy Flags = Outs[I].Flags;
5366         if (VA.getLocInfo() == CCValAssign::Indirect)
5367           return false;
5368         if (!VA.isRegLoc()) {
5369           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, MFI, MRI,
5370                                    TII, VA))
5371             return false;
5372         }
5373       }
5374     }
5375 
5376     bool PositionIndependent = isPositionIndependent();
5377     // If the tailcall address may be in a register, then make sure it's
5378     // possible to register allocate for it. In 32-bit, the call address can
5379     // only target EAX, EDX, or ECX since the tail call must be scheduled after
5380     // callee-saved registers are restored. These happen to be the same
5381     // registers used to pass 'inreg' arguments so watch out for those.
5382     if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
5383                                   !isa<ExternalSymbolSDNode>(Callee)) ||
5384                                  PositionIndependent)) {
5385       unsigned NumInRegs = 0;
5386       // In PIC we need an extra register to formulate the address computation
5387       // for the callee.
5388       unsigned MaxInRegs = PositionIndependent ? 2 : 3;
5389 
5390       for (const auto &VA : ArgLocs) {
5391         if (!VA.isRegLoc())
5392           continue;
5393         Register Reg = VA.getLocReg();
5394         switch (Reg) {
5395         default: break;
5396         case X86::EAX: case X86::EDX: case X86::ECX:
5397           if (++NumInRegs == MaxInRegs)
5398             return false;
5399           break;
5400         }
5401       }
5402     }
5403 
5404     const MachineRegisterInfo &MRI = MF.getRegInfo();
5405     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
5406       return false;
5407   }
5408 
5409   bool CalleeWillPop =
5410       X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
5411                        MF.getTarget().Options.GuaranteedTailCallOpt);
5412 
5413   if (unsigned BytesToPop =
5414           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
5415     // If we have bytes to pop, the callee must pop them.
5416     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
5417     if (!CalleePopMatches)
5418       return false;
5419   } else if (CalleeWillPop && StackArgsSize > 0) {
5420     // If we don't have bytes to pop, make sure the callee doesn't pop any.
5421     return false;
5422   }
5423 
5424   return true;
5425 }
5426 
5427 FastISel *
5428 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
5429                                   const TargetLibraryInfo *libInfo) const {
5430   return X86::createFastISel(funcInfo, libInfo);
5431 }
5432 
5433 //===----------------------------------------------------------------------===//
5434 //                           Other Lowering Hooks
5435 //===----------------------------------------------------------------------===//
5436 
5437 bool X86::mayFoldLoad(SDValue Op, const X86Subtarget &Subtarget,
5438                       bool AssumeSingleUse) {
5439   if (!AssumeSingleUse && !Op.hasOneUse())
5440     return false;
5441   if (!ISD::isNormalLoad(Op.getNode()))
5442     return false;
5443 
5444   // If this is an unaligned vector, make sure the target supports folding it.
5445   auto *Ld = cast<LoadSDNode>(Op.getNode());
5446   if (!Subtarget.hasAVX() && !Subtarget.hasSSEUnalignedMem() &&
5447       Ld->getValueSizeInBits(0) == 128 && Ld->getAlign() < Align(16))
5448     return false;
5449 
5450   // TODO: If this is a non-temporal load and the target has an instruction
5451   //       for it, it should not be folded. See "useNonTemporalLoad()".
5452 
5453   return true;
5454 }
5455 
5456 bool X86::mayFoldLoadIntoBroadcastFromMem(SDValue Op, MVT EltVT,
5457                                           const X86Subtarget &Subtarget,
5458                                           bool AssumeSingleUse) {
5459   assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
5460   if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
5461     return false;
5462 
5463   // We can not replace a wide volatile load with a broadcast-from-memory,
5464   // because that would narrow the load, which isn't legal for volatiles.
5465   auto *Ld = cast<LoadSDNode>(Op.getNode());
5466   return !Ld->isVolatile() ||
5467          Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
5468 }
5469 
5470 bool X86::mayFoldIntoStore(SDValue Op) {
5471   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
5472 }
5473 
5474 bool X86::mayFoldIntoZeroExtend(SDValue Op) {
5475   if (Op.hasOneUse()) {
5476     unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
5477     return (ISD::ZERO_EXTEND == Opcode);
5478   }
5479   return false;
5480 }
5481 
5482 static bool isTargetShuffle(unsigned Opcode) {
5483   switch(Opcode) {
5484   default: return false;
5485   case X86ISD::BLENDI:
5486   case X86ISD::PSHUFB:
5487   case X86ISD::PSHUFD:
5488   case X86ISD::PSHUFHW:
5489   case X86ISD::PSHUFLW:
5490   case X86ISD::SHUFP:
5491   case X86ISD::INSERTPS:
5492   case X86ISD::EXTRQI:
5493   case X86ISD::INSERTQI:
5494   case X86ISD::VALIGN:
5495   case X86ISD::PALIGNR:
5496   case X86ISD::VSHLDQ:
5497   case X86ISD::VSRLDQ:
5498   case X86ISD::MOVLHPS:
5499   case X86ISD::MOVHLPS:
5500   case X86ISD::MOVSHDUP:
5501   case X86ISD::MOVSLDUP:
5502   case X86ISD::MOVDDUP:
5503   case X86ISD::MOVSS:
5504   case X86ISD::MOVSD:
5505   case X86ISD::MOVSH:
5506   case X86ISD::UNPCKL:
5507   case X86ISD::UNPCKH:
5508   case X86ISD::VBROADCAST:
5509   case X86ISD::VPERMILPI:
5510   case X86ISD::VPERMILPV:
5511   case X86ISD::VPERM2X128:
5512   case X86ISD::SHUF128:
5513   case X86ISD::VPERMIL2:
5514   case X86ISD::VPERMI:
5515   case X86ISD::VPPERM:
5516   case X86ISD::VPERMV:
5517   case X86ISD::VPERMV3:
5518   case X86ISD::VZEXT_MOVL:
5519     return true;
5520   }
5521 }
5522 
5523 static bool isTargetShuffleVariableMask(unsigned Opcode) {
5524   switch (Opcode) {
5525   default: return false;
5526   // Target Shuffles.
5527   case X86ISD::PSHUFB:
5528   case X86ISD::VPERMILPV:
5529   case X86ISD::VPERMIL2:
5530   case X86ISD::VPPERM:
5531   case X86ISD::VPERMV:
5532   case X86ISD::VPERMV3:
5533     return true;
5534   // 'Faux' Target Shuffles.
5535   case ISD::OR:
5536   case ISD::AND:
5537   case X86ISD::ANDNP:
5538     return true;
5539   }
5540 }
5541 
5542 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
5543   MachineFunction &MF = DAG.getMachineFunction();
5544   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
5545   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
5546   int ReturnAddrIndex = FuncInfo->getRAIndex();
5547 
5548   if (ReturnAddrIndex == 0) {
5549     // Set up a frame object for the return address.
5550     unsigned SlotSize = RegInfo->getSlotSize();
5551     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
5552                                                           -(int64_t)SlotSize,
5553                                                           false);
5554     FuncInfo->setRAIndex(ReturnAddrIndex);
5555   }
5556 
5557   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
5558 }
5559 
5560 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
5561                                        bool hasSymbolicDisplacement) {
5562   // Offset should fit into 32 bit immediate field.
5563   if (!isInt<32>(Offset))
5564     return false;
5565 
5566   // If we don't have a symbolic displacement - we don't have any extra
5567   // restrictions.
5568   if (!hasSymbolicDisplacement)
5569     return true;
5570 
5571   // FIXME: Some tweaks might be needed for medium code model.
5572   if (M != CodeModel::Small && M != CodeModel::Kernel)
5573     return false;
5574 
5575   // For small code model we assume that latest object is 16MB before end of 31
5576   // bits boundary. We may also accept pretty large negative constants knowing
5577   // that all objects are in the positive half of address space.
5578   if (M == CodeModel::Small && Offset < 16*1024*1024)
5579     return true;
5580 
5581   // For kernel code model we know that all object resist in the negative half
5582   // of 32bits address space. We may not accept negative offsets, since they may
5583   // be just off and we may accept pretty large positive ones.
5584   if (M == CodeModel::Kernel && Offset >= 0)
5585     return true;
5586 
5587   return false;
5588 }
5589 
5590 /// Determines whether the callee is required to pop its own arguments.
5591 /// Callee pop is necessary to support tail calls.
5592 bool X86::isCalleePop(CallingConv::ID CallingConv,
5593                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
5594   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
5595   // can guarantee TCO.
5596   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
5597     return true;
5598 
5599   switch (CallingConv) {
5600   default:
5601     return false;
5602   case CallingConv::X86_StdCall:
5603   case CallingConv::X86_FastCall:
5604   case CallingConv::X86_ThisCall:
5605   case CallingConv::X86_VectorCall:
5606     return !is64Bit;
5607   }
5608 }
5609 
5610 /// Return true if the condition is an signed comparison operation.
5611 static bool isX86CCSigned(unsigned X86CC) {
5612   switch (X86CC) {
5613   default:
5614     llvm_unreachable("Invalid integer condition!");
5615   case X86::COND_E:
5616   case X86::COND_NE:
5617   case X86::COND_B:
5618   case X86::COND_A:
5619   case X86::COND_BE:
5620   case X86::COND_AE:
5621     return false;
5622   case X86::COND_G:
5623   case X86::COND_GE:
5624   case X86::COND_L:
5625   case X86::COND_LE:
5626     return true;
5627   }
5628 }
5629 
5630 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
5631   switch (SetCCOpcode) {
5632   default: llvm_unreachable("Invalid integer condition!");
5633   case ISD::SETEQ:  return X86::COND_E;
5634   case ISD::SETGT:  return X86::COND_G;
5635   case ISD::SETGE:  return X86::COND_GE;
5636   case ISD::SETLT:  return X86::COND_L;
5637   case ISD::SETLE:  return X86::COND_LE;
5638   case ISD::SETNE:  return X86::COND_NE;
5639   case ISD::SETULT: return X86::COND_B;
5640   case ISD::SETUGT: return X86::COND_A;
5641   case ISD::SETULE: return X86::COND_BE;
5642   case ISD::SETUGE: return X86::COND_AE;
5643   }
5644 }
5645 
5646 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
5647 /// condition code, returning the condition code and the LHS/RHS of the
5648 /// comparison to make.
5649 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
5650                                     bool isFP, SDValue &LHS, SDValue &RHS,
5651                                     SelectionDAG &DAG) {
5652   if (!isFP) {
5653     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5654       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
5655         // X > -1   -> X == 0, jump !sign.
5656         RHS = DAG.getConstant(0, DL, RHS.getValueType());
5657         return X86::COND_NS;
5658       }
5659       if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
5660         // X < 0   -> X == 0, jump on sign.
5661         return X86::COND_S;
5662       }
5663       if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
5664         // X >= 0   -> X == 0, jump on !sign.
5665         return X86::COND_NS;
5666       }
5667       if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
5668         // X < 1   -> X <= 0
5669         RHS = DAG.getConstant(0, DL, RHS.getValueType());
5670         return X86::COND_LE;
5671       }
5672     }
5673 
5674     return TranslateIntegerX86CC(SetCCOpcode);
5675   }
5676 
5677   // First determine if it is required or is profitable to flip the operands.
5678 
5679   // If LHS is a foldable load, but RHS is not, flip the condition.
5680   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
5681       !ISD::isNON_EXTLoad(RHS.getNode())) {
5682     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
5683     std::swap(LHS, RHS);
5684   }
5685 
5686   switch (SetCCOpcode) {
5687   default: break;
5688   case ISD::SETOLT:
5689   case ISD::SETOLE:
5690   case ISD::SETUGT:
5691   case ISD::SETUGE:
5692     std::swap(LHS, RHS);
5693     break;
5694   }
5695 
5696   // On a floating point condition, the flags are set as follows:
5697   // ZF  PF  CF   op
5698   //  0 | 0 | 0 | X > Y
5699   //  0 | 0 | 1 | X < Y
5700   //  1 | 0 | 0 | X == Y
5701   //  1 | 1 | 1 | unordered
5702   switch (SetCCOpcode) {
5703   default: llvm_unreachable("Condcode should be pre-legalized away");
5704   case ISD::SETUEQ:
5705   case ISD::SETEQ:   return X86::COND_E;
5706   case ISD::SETOLT:              // flipped
5707   case ISD::SETOGT:
5708   case ISD::SETGT:   return X86::COND_A;
5709   case ISD::SETOLE:              // flipped
5710   case ISD::SETOGE:
5711   case ISD::SETGE:   return X86::COND_AE;
5712   case ISD::SETUGT:              // flipped
5713   case ISD::SETULT:
5714   case ISD::SETLT:   return X86::COND_B;
5715   case ISD::SETUGE:              // flipped
5716   case ISD::SETULE:
5717   case ISD::SETLE:   return X86::COND_BE;
5718   case ISD::SETONE:
5719   case ISD::SETNE:   return X86::COND_NE;
5720   case ISD::SETUO:   return X86::COND_P;
5721   case ISD::SETO:    return X86::COND_NP;
5722   case ISD::SETOEQ:
5723   case ISD::SETUNE:  return X86::COND_INVALID;
5724   }
5725 }
5726 
5727 /// Is there a floating point cmov for the specific X86 condition code?
5728 /// Current x86 isa includes the following FP cmov instructions:
5729 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
5730 static bool hasFPCMov(unsigned X86CC) {
5731   switch (X86CC) {
5732   default:
5733     return false;
5734   case X86::COND_B:
5735   case X86::COND_BE:
5736   case X86::COND_E:
5737   case X86::COND_P:
5738   case X86::COND_A:
5739   case X86::COND_AE:
5740   case X86::COND_NE:
5741   case X86::COND_NP:
5742     return true;
5743   }
5744 }
5745 
5746 static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
5747   return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
5748          VT.is512BitVector();
5749 }
5750 
5751 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5752                                            const CallInst &I,
5753                                            MachineFunction &MF,
5754                                            unsigned Intrinsic) const {
5755   Info.flags = MachineMemOperand::MONone;
5756   Info.offset = 0;
5757 
5758   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
5759   if (!IntrData) {
5760     switch (Intrinsic) {
5761     case Intrinsic::x86_aesenc128kl:
5762     case Intrinsic::x86_aesdec128kl:
5763       Info.opc = ISD::INTRINSIC_W_CHAIN;
5764       Info.ptrVal = I.getArgOperand(1);
5765       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5766       Info.align = Align(1);
5767       Info.flags |= MachineMemOperand::MOLoad;
5768       return true;
5769     case Intrinsic::x86_aesenc256kl:
5770     case Intrinsic::x86_aesdec256kl:
5771       Info.opc = ISD::INTRINSIC_W_CHAIN;
5772       Info.ptrVal = I.getArgOperand(1);
5773       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5774       Info.align = Align(1);
5775       Info.flags |= MachineMemOperand::MOLoad;
5776       return true;
5777     case Intrinsic::x86_aesencwide128kl:
5778     case Intrinsic::x86_aesdecwide128kl:
5779       Info.opc = ISD::INTRINSIC_W_CHAIN;
5780       Info.ptrVal = I.getArgOperand(0);
5781       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5782       Info.align = Align(1);
5783       Info.flags |= MachineMemOperand::MOLoad;
5784       return true;
5785     case Intrinsic::x86_aesencwide256kl:
5786     case Intrinsic::x86_aesdecwide256kl:
5787       Info.opc = ISD::INTRINSIC_W_CHAIN;
5788       Info.ptrVal = I.getArgOperand(0);
5789       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5790       Info.align = Align(1);
5791       Info.flags |= MachineMemOperand::MOLoad;
5792       return true;
5793     case Intrinsic::x86_cmpccxadd32:
5794     case Intrinsic::x86_cmpccxadd64:
5795     case Intrinsic::x86_atomic_bts:
5796     case Intrinsic::x86_atomic_btc:
5797     case Intrinsic::x86_atomic_btr: {
5798       Info.opc = ISD::INTRINSIC_W_CHAIN;
5799       Info.ptrVal = I.getArgOperand(0);
5800       unsigned Size = I.getType()->getScalarSizeInBits();
5801       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
5802       Info.align = Align(Size);
5803       Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
5804                     MachineMemOperand::MOVolatile;
5805       return true;
5806     }
5807     case Intrinsic::x86_atomic_bts_rm:
5808     case Intrinsic::x86_atomic_btc_rm:
5809     case Intrinsic::x86_atomic_btr_rm: {
5810       Info.opc = ISD::INTRINSIC_W_CHAIN;
5811       Info.ptrVal = I.getArgOperand(0);
5812       unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
5813       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
5814       Info.align = Align(Size);
5815       Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
5816                     MachineMemOperand::MOVolatile;
5817       return true;
5818     }
5819     case Intrinsic::x86_aadd32:
5820     case Intrinsic::x86_aadd64:
5821     case Intrinsic::x86_aand32:
5822     case Intrinsic::x86_aand64:
5823     case Intrinsic::x86_aor32:
5824     case Intrinsic::x86_aor64:
5825     case Intrinsic::x86_axor32:
5826     case Intrinsic::x86_axor64:
5827     case Intrinsic::x86_atomic_add_cc:
5828     case Intrinsic::x86_atomic_sub_cc:
5829     case Intrinsic::x86_atomic_or_cc:
5830     case Intrinsic::x86_atomic_and_cc:
5831     case Intrinsic::x86_atomic_xor_cc: {
5832       Info.opc = ISD::INTRINSIC_W_CHAIN;
5833       Info.ptrVal = I.getArgOperand(0);
5834       unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
5835       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
5836       Info.align = Align(Size);
5837       Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
5838                     MachineMemOperand::MOVolatile;
5839       return true;
5840     }
5841     }
5842     return false;
5843   }
5844 
5845   switch (IntrData->Type) {
5846   case TRUNCATE_TO_MEM_VI8:
5847   case TRUNCATE_TO_MEM_VI16:
5848   case TRUNCATE_TO_MEM_VI32: {
5849     Info.opc = ISD::INTRINSIC_VOID;
5850     Info.ptrVal = I.getArgOperand(0);
5851     MVT VT  = MVT::getVT(I.getArgOperand(1)->getType());
5852     MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
5853     if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
5854       ScalarVT = MVT::i8;
5855     else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
5856       ScalarVT = MVT::i16;
5857     else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
5858       ScalarVT = MVT::i32;
5859 
5860     Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
5861     Info.align = Align(1);
5862     Info.flags |= MachineMemOperand::MOStore;
5863     break;
5864   }
5865   case GATHER:
5866   case GATHER_AVX2: {
5867     Info.opc = ISD::INTRINSIC_W_CHAIN;
5868     Info.ptrVal = nullptr;
5869     MVT DataVT = MVT::getVT(I.getType());
5870     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5871     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5872                                 IndexVT.getVectorNumElements());
5873     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5874     Info.align = Align(1);
5875     Info.flags |= MachineMemOperand::MOLoad;
5876     break;
5877   }
5878   case SCATTER: {
5879     Info.opc = ISD::INTRINSIC_VOID;
5880     Info.ptrVal = nullptr;
5881     MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
5882     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5883     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5884                                 IndexVT.getVectorNumElements());
5885     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5886     Info.align = Align(1);
5887     Info.flags |= MachineMemOperand::MOStore;
5888     break;
5889   }
5890   default:
5891     return false;
5892   }
5893 
5894   return true;
5895 }
5896 
5897 /// Returns true if the target can instruction select the
5898 /// specified FP immediate natively. If false, the legalizer will
5899 /// materialize the FP immediate as a load from a constant pool.
5900 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5901                                      bool ForCodeSize) const {
5902   for (const APFloat &FPImm : LegalFPImmediates)
5903     if (Imm.bitwiseIsEqual(FPImm))
5904       return true;
5905   return false;
5906 }
5907 
5908 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
5909                                               ISD::LoadExtType ExtTy,
5910                                               EVT NewVT) const {
5911   assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
5912 
5913   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
5914   // relocation target a movq or addq instruction: don't let the load shrink.
5915   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
5916   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
5917     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
5918       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
5919 
5920   // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
5921   // those uses are extracted directly into a store, then the extract + store
5922   // can be store-folded. Therefore, it's probably not worth splitting the load.
5923   EVT VT = Load->getValueType(0);
5924   if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
5925     for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
5926       // Skip uses of the chain value. Result 0 of the node is the load value.
5927       if (UI.getUse().getResNo() != 0)
5928         continue;
5929 
5930       // If this use is not an extract + store, it's probably worth splitting.
5931       if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
5932           UI->use_begin()->getOpcode() != ISD::STORE)
5933         return true;
5934     }
5935     // All non-chain uses are extract + store.
5936     return false;
5937   }
5938 
5939   return true;
5940 }
5941 
5942 /// Returns true if it is beneficial to convert a load of a constant
5943 /// to just the constant itself.
5944 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5945                                                           Type *Ty) const {
5946   assert(Ty->isIntegerTy());
5947 
5948   unsigned BitSize = Ty->getPrimitiveSizeInBits();
5949   if (BitSize == 0 || BitSize > 64)
5950     return false;
5951   return true;
5952 }
5953 
5954 bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
5955   // If we are using XMM registers in the ABI and the condition of the select is
5956   // a floating-point compare and we have blendv or conditional move, then it is
5957   // cheaper to select instead of doing a cross-register move and creating a
5958   // load that depends on the compare result.
5959   bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
5960   return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
5961 }
5962 
5963 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
5964   // TODO: It might be a win to ease or lift this restriction, but the generic
5965   // folds in DAGCombiner conflict with vector folds for an AVX512 target.
5966   if (VT.isVector() && Subtarget.hasAVX512())
5967     return false;
5968 
5969   return true;
5970 }
5971 
5972 bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
5973                                                SDValue C) const {
5974   // TODO: We handle scalars using custom code, but generic combining could make
5975   // that unnecessary.
5976   APInt MulC;
5977   if (!ISD::isConstantSplatVector(C.getNode(), MulC))
5978     return false;
5979 
5980   // Find the type this will be legalized too. Otherwise we might prematurely
5981   // convert this to shl+add/sub and then still have to type legalize those ops.
5982   // Another choice would be to defer the decision for illegal types until
5983   // after type legalization. But constant splat vectors of i64 can't make it
5984   // through type legalization on 32-bit targets so we would need to special
5985   // case vXi64.
5986   while (getTypeAction(Context, VT) != TypeLegal)
5987     VT = getTypeToTransformTo(Context, VT);
5988 
5989   // If vector multiply is legal, assume that's faster than shl + add/sub.
5990   // Multiply is a complex op with higher latency and lower throughput in
5991   // most implementations, sub-vXi32 vector multiplies are always fast,
5992   // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
5993   // is always going to be slow.
5994   unsigned EltSizeInBits = VT.getScalarSizeInBits();
5995   if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
5996       (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
5997     return false;
5998 
5999   // shl+add, shl+sub, shl+add+neg
6000   return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
6001          (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
6002 }
6003 
6004 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
6005                                                 unsigned Index) const {
6006   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
6007     return false;
6008 
6009   // Mask vectors support all subregister combinations and operations that
6010   // extract half of vector.
6011   if (ResVT.getVectorElementType() == MVT::i1)
6012     return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
6013                           (Index == ResVT.getVectorNumElements()));
6014 
6015   return (Index % ResVT.getVectorNumElements()) == 0;
6016 }
6017 
6018 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
6019   unsigned Opc = VecOp.getOpcode();
6020 
6021   // Assume target opcodes can't be scalarized.
6022   // TODO - do we have any exceptions?
6023   if (Opc >= ISD::BUILTIN_OP_END)
6024     return false;
6025 
6026   // If the vector op is not supported, try to convert to scalar.
6027   EVT VecVT = VecOp.getValueType();
6028   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
6029     return true;
6030 
6031   // If the vector op is supported, but the scalar op is not, the transform may
6032   // not be worthwhile.
6033   EVT ScalarVT = VecVT.getScalarType();
6034   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
6035 }
6036 
6037 bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT,
6038                                              bool) const {
6039   // TODO: Allow vectors?
6040   if (VT.isVector())
6041     return false;
6042   return VT.isSimple() || !isOperationExpand(Opcode, VT);
6043 }
6044 
6045 bool X86TargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
6046   // Speculate cttz only if we can directly use TZCNT or can promote to i32.
6047   return Subtarget.hasBMI() ||
6048          (!Ty->isVectorTy() && Ty->getScalarSizeInBits() < 32);
6049 }
6050 
6051 bool X86TargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
6052   // Speculate ctlz only if we can directly use LZCNT.
6053   return Subtarget.hasLZCNT();
6054 }
6055 
6056 bool X86TargetLowering::ShouldShrinkFPConstant(EVT VT) const {
6057   // Don't shrink FP constpool if SSE2 is available since cvtss2sd is more
6058   // expensive than a straight movsd. On the other hand, it's important to
6059   // shrink long double fp constant since fldt is very slow.
6060   return !Subtarget.hasSSE2() || VT == MVT::f80;
6061 }
6062 
6063 bool X86TargetLowering::isScalarFPTypeInSSEReg(EVT VT) const {
6064   return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
6065          (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
6066 }
6067 
6068 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
6069                                                 const SelectionDAG &DAG,
6070                                                 const MachineMemOperand &MMO) const {
6071   if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
6072       BitcastVT.getVectorElementType() == MVT::i1)
6073     return false;
6074 
6075   if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
6076     return false;
6077 
6078   // If both types are legal vectors, it's always ok to convert them.
6079   if (LoadVT.isVector() && BitcastVT.isVector() &&
6080       isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
6081     return true;
6082 
6083   return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
6084 }
6085 
6086 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
6087                                          const MachineFunction &MF) const {
6088   // Do not merge to float value size (128 bytes) if no implicit
6089   // float attribute is set.
6090   bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
6091 
6092   if (NoFloat) {
6093     unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
6094     return (MemVT.getSizeInBits() <= MaxIntSize);
6095   }
6096   // Make sure we don't merge greater than our preferred vector
6097   // width.
6098   if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
6099     return false;
6100 
6101   return true;
6102 }
6103 
6104 bool X86TargetLowering::isCtlzFast() const {
6105   return Subtarget.hasFastLZCNT();
6106 }
6107 
6108 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
6109     const Instruction &AndI) const {
6110   return true;
6111 }
6112 
6113 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
6114   EVT VT = Y.getValueType();
6115 
6116   if (VT.isVector())
6117     return false;
6118 
6119   if (!Subtarget.hasBMI())
6120     return false;
6121 
6122   // There are only 32-bit and 64-bit forms for 'andn'.
6123   if (VT != MVT::i32 && VT != MVT::i64)
6124     return false;
6125 
6126   return !isa<ConstantSDNode>(Y);
6127 }
6128 
6129 bool X86TargetLowering::hasAndNot(SDValue Y) const {
6130   EVT VT = Y.getValueType();
6131 
6132   if (!VT.isVector())
6133     return hasAndNotCompare(Y);
6134 
6135   // Vector.
6136 
6137   if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
6138     return false;
6139 
6140   if (VT == MVT::v4i32)
6141     return true;
6142 
6143   return Subtarget.hasSSE2();
6144 }
6145 
6146 bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
6147   return X.getValueType().isScalarInteger(); // 'bt'
6148 }
6149 
6150 bool X86TargetLowering::
6151     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
6152         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
6153         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
6154         SelectionDAG &DAG) const {
6155   // Does baseline recommend not to perform the fold by default?
6156   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
6157           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
6158     return false;
6159   // For scalars this transform is always beneficial.
6160   if (X.getValueType().isScalarInteger())
6161     return true;
6162   // If all the shift amounts are identical, then transform is beneficial even
6163   // with rudimentary SSE2 shifts.
6164   if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
6165     return true;
6166   // If we have AVX2 with it's powerful shift operations, then it's also good.
6167   if (Subtarget.hasAVX2())
6168     return true;
6169   // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
6170   return NewShiftOpcode == ISD::SHL;
6171 }
6172 
6173 bool X86TargetLowering::preferScalarizeSplat(SDNode *N) const {
6174   return N->getOpcode() != ISD::FP_EXTEND;
6175 }
6176 
6177 bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
6178     const SDNode *N, CombineLevel Level) const {
6179   assert(((N->getOpcode() == ISD::SHL &&
6180            N->getOperand(0).getOpcode() == ISD::SRL) ||
6181           (N->getOpcode() == ISD::SRL &&
6182            N->getOperand(0).getOpcode() == ISD::SHL)) &&
6183          "Expected shift-shift mask");
6184   // TODO: Should we always create i64 masks? Or only folded immediates?
6185   EVT VT = N->getValueType(0);
6186   if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
6187       (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
6188     // Only fold if the shift values are equal - so it folds to AND.
6189     // TODO - we should fold if either is a non-uniform vector but we don't do
6190     // the fold for non-splats yet.
6191     return N->getOperand(1) == N->getOperand(0).getOperand(1);
6192   }
6193   return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
6194 }
6195 
6196 bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
6197   EVT VT = Y.getValueType();
6198 
6199   // For vectors, we don't have a preference, but we probably want a mask.
6200   if (VT.isVector())
6201     return false;
6202 
6203   // 64-bit shifts on 32-bit targets produce really bad bloated code.
6204   if (VT == MVT::i64 && !Subtarget.is64Bit())
6205     return false;
6206 
6207   return true;
6208 }
6209 
6210 TargetLowering::ShiftLegalizationStrategy
6211 X86TargetLowering::preferredShiftLegalizationStrategy(
6212     SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
6213   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
6214       !Subtarget.isOSWindows())
6215     return ShiftLegalizationStrategy::LowerToLibcall;
6216   return TargetLowering::preferredShiftLegalizationStrategy(DAG, N,
6217                                                             ExpansionFactor);
6218 }
6219 
6220 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
6221   // Any legal vector type can be splatted more efficiently than
6222   // loading/spilling from memory.
6223   return isTypeLegal(VT);
6224 }
6225 
6226 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
6227   MVT VT = MVT::getIntegerVT(NumBits);
6228   if (isTypeLegal(VT))
6229     return VT;
6230 
6231   // PMOVMSKB can handle this.
6232   if (NumBits == 128 && isTypeLegal(MVT::v16i8))
6233     return MVT::v16i8;
6234 
6235   // VPMOVMSKB can handle this.
6236   if (NumBits == 256 && isTypeLegal(MVT::v32i8))
6237     return MVT::v32i8;
6238 
6239   // TODO: Allow 64-bit type for 32-bit target.
6240   // TODO: 512-bit types should be allowed, but make sure that those
6241   // cases are handled in combineVectorSizedSetCCEquality().
6242 
6243   return MVT::INVALID_SIMPLE_VALUE_TYPE;
6244 }
6245 
6246 /// Val is the undef sentinel value or equal to the specified value.
6247 static bool isUndefOrEqual(int Val, int CmpVal) {
6248   return ((Val == SM_SentinelUndef) || (Val == CmpVal));
6249 }
6250 
6251 /// Return true if every element in Mask is the undef sentinel value or equal to
6252 /// the specified value.
6253 static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
6254   return llvm::all_of(Mask, [CmpVal](int M) {
6255     return (M == SM_SentinelUndef) || (M == CmpVal);
6256   });
6257 }
6258 
6259 /// Return true if every element in Mask, beginning from position Pos and ending
6260 /// in Pos+Size is the undef sentinel value or equal to the specified value.
6261 static bool isUndefOrEqualInRange(ArrayRef<int> Mask, int CmpVal, unsigned Pos,
6262                                   unsigned Size) {
6263   return llvm::all_of(Mask.slice(Pos, Size),
6264                       [CmpVal](int M) { return isUndefOrEqual(M, CmpVal); });
6265 }
6266 
6267 /// Val is either the undef or zero sentinel value.
6268 static bool isUndefOrZero(int Val) {
6269   return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
6270 }
6271 
6272 /// Return true if every element in Mask, beginning from position Pos and ending
6273 /// in Pos+Size is the undef sentinel value.
6274 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
6275   return llvm::all_of(Mask.slice(Pos, Size),
6276                       [](int M) { return M == SM_SentinelUndef; });
6277 }
6278 
6279 /// Return true if the mask creates a vector whose lower half is undefined.
6280 static bool isUndefLowerHalf(ArrayRef<int> Mask) {
6281   unsigned NumElts = Mask.size();
6282   return isUndefInRange(Mask, 0, NumElts / 2);
6283 }
6284 
6285 /// Return true if the mask creates a vector whose upper half is undefined.
6286 static bool isUndefUpperHalf(ArrayRef<int> Mask) {
6287   unsigned NumElts = Mask.size();
6288   return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
6289 }
6290 
6291 /// Return true if Val falls within the specified range (L, H].
6292 static bool isInRange(int Val, int Low, int Hi) {
6293   return (Val >= Low && Val < Hi);
6294 }
6295 
6296 /// Return true if the value of any element in Mask falls within the specified
6297 /// range (L, H].
6298 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
6299   return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
6300 }
6301 
6302 /// Return true if the value of any element in Mask is the zero sentinel value.
6303 static bool isAnyZero(ArrayRef<int> Mask) {
6304   return llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
6305 }
6306 
6307 /// Return true if the value of any element in Mask is the zero or undef
6308 /// sentinel values.
6309 static bool isAnyZeroOrUndef(ArrayRef<int> Mask) {
6310   return llvm::any_of(Mask, [](int M) {
6311     return M == SM_SentinelZero || M == SM_SentinelUndef;
6312   });
6313 }
6314 
6315 /// Return true if Val is undef or if its value falls within the
6316 /// specified range (L, H].
6317 static bool isUndefOrInRange(int Val, int Low, int Hi) {
6318   return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
6319 }
6320 
6321 /// Return true if every element in Mask is undef or if its value
6322 /// falls within the specified range (L, H].
6323 static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
6324   return llvm::all_of(
6325       Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
6326 }
6327 
6328 /// Return true if Val is undef, zero or if its value falls within the
6329 /// specified range (L, H].
6330 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
6331   return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
6332 }
6333 
6334 /// Return true if every element in Mask is undef, zero or if its value
6335 /// falls within the specified range (L, H].
6336 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
6337   return llvm::all_of(
6338       Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
6339 }
6340 
6341 /// Return true if every element in Mask, beginning
6342 /// from position Pos and ending in Pos + Size, falls within the specified
6343 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
6344 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
6345                                        unsigned Size, int Low, int Step = 1) {
6346   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
6347     if (!isUndefOrEqual(Mask[i], Low))
6348       return false;
6349   return true;
6350 }
6351 
6352 /// Return true if every element in Mask, beginning
6353 /// from position Pos and ending in Pos+Size, falls within the specified
6354 /// sequential range (Low, Low+Size], or is undef or is zero.
6355 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
6356                                              unsigned Size, int Low,
6357                                              int Step = 1) {
6358   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
6359     if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
6360       return false;
6361   return true;
6362 }
6363 
6364 /// Return true if every element in Mask, beginning
6365 /// from position Pos and ending in Pos+Size is undef or is zero.
6366 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
6367                                  unsigned Size) {
6368   return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
6369 }
6370 
6371 /// Helper function to test whether a shuffle mask could be
6372 /// simplified by widening the elements being shuffled.
6373 ///
6374 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
6375 /// leaves it in an unspecified state.
6376 ///
6377 /// NOTE: This must handle normal vector shuffle masks and *target* vector
6378 /// shuffle masks. The latter have the special property of a '-2' representing
6379 /// a zero-ed lane of a vector.
6380 static bool canWidenShuffleElements(ArrayRef<int> Mask,
6381                                     SmallVectorImpl<int> &WidenedMask) {
6382   WidenedMask.assign(Mask.size() / 2, 0);
6383   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
6384     int M0 = Mask[i];
6385     int M1 = Mask[i + 1];
6386 
6387     // If both elements are undef, its trivial.
6388     if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
6389       WidenedMask[i / 2] = SM_SentinelUndef;
6390       continue;
6391     }
6392 
6393     // Check for an undef mask and a mask value properly aligned to fit with
6394     // a pair of values. If we find such a case, use the non-undef mask's value.
6395     if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
6396       WidenedMask[i / 2] = M1 / 2;
6397       continue;
6398     }
6399     if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
6400       WidenedMask[i / 2] = M0 / 2;
6401       continue;
6402     }
6403 
6404     // When zeroing, we need to spread the zeroing across both lanes to widen.
6405     if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
6406       if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
6407           (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
6408         WidenedMask[i / 2] = SM_SentinelZero;
6409         continue;
6410       }
6411       return false;
6412     }
6413 
6414     // Finally check if the two mask values are adjacent and aligned with
6415     // a pair.
6416     if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
6417       WidenedMask[i / 2] = M0 / 2;
6418       continue;
6419     }
6420 
6421     // Otherwise we can't safely widen the elements used in this shuffle.
6422     return false;
6423   }
6424   assert(WidenedMask.size() == Mask.size() / 2 &&
6425          "Incorrect size of mask after widening the elements!");
6426 
6427   return true;
6428 }
6429 
6430 static bool canWidenShuffleElements(ArrayRef<int> Mask,
6431                                     const APInt &Zeroable,
6432                                     bool V2IsZero,
6433                                     SmallVectorImpl<int> &WidenedMask) {
6434   // Create an alternative mask with info about zeroable elements.
6435   // Here we do not set undef elements as zeroable.
6436   SmallVector<int, 64> ZeroableMask(Mask);
6437   if (V2IsZero) {
6438     assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
6439     for (int i = 0, Size = Mask.size(); i != Size; ++i)
6440       if (Mask[i] != SM_SentinelUndef && Zeroable[i])
6441         ZeroableMask[i] = SM_SentinelZero;
6442   }
6443   return canWidenShuffleElements(ZeroableMask, WidenedMask);
6444 }
6445 
6446 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
6447   SmallVector<int, 32> WidenedMask;
6448   return canWidenShuffleElements(Mask, WidenedMask);
6449 }
6450 
6451 // Attempt to narrow/widen shuffle mask until it matches the target number of
6452 // elements.
6453 static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
6454                                  SmallVectorImpl<int> &ScaledMask) {
6455   unsigned NumSrcElts = Mask.size();
6456   assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
6457          "Illegal shuffle scale factor");
6458 
6459   // Narrowing is guaranteed to work.
6460   if (NumDstElts >= NumSrcElts) {
6461     int Scale = NumDstElts / NumSrcElts;
6462     llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
6463     return true;
6464   }
6465 
6466   // We have to repeat the widening until we reach the target size, but we can
6467   // split out the first widening as it sets up ScaledMask for us.
6468   if (canWidenShuffleElements(Mask, ScaledMask)) {
6469     while (ScaledMask.size() > NumDstElts) {
6470       SmallVector<int, 16> WidenedMask;
6471       if (!canWidenShuffleElements(ScaledMask, WidenedMask))
6472         return false;
6473       ScaledMask = std::move(WidenedMask);
6474     }
6475     return true;
6476   }
6477 
6478   return false;
6479 }
6480 
6481 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
6482 bool X86::isZeroNode(SDValue Elt) {
6483   return isNullConstant(Elt) || isNullFPConstant(Elt);
6484 }
6485 
6486 // Build a vector of constants.
6487 // Use an UNDEF node if MaskElt == -1.
6488 // Split 64-bit constants in the 32-bit mode.
6489 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
6490                               const SDLoc &dl, bool IsMask = false) {
6491 
6492   SmallVector<SDValue, 32>  Ops;
6493   bool Split = false;
6494 
6495   MVT ConstVecVT = VT;
6496   unsigned NumElts = VT.getVectorNumElements();
6497   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
6498   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
6499     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
6500     Split = true;
6501   }
6502 
6503   MVT EltVT = ConstVecVT.getVectorElementType();
6504   for (unsigned i = 0; i < NumElts; ++i) {
6505     bool IsUndef = Values[i] < 0 && IsMask;
6506     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
6507       DAG.getConstant(Values[i], dl, EltVT);
6508     Ops.push_back(OpNode);
6509     if (Split)
6510       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
6511                     DAG.getConstant(0, dl, EltVT));
6512   }
6513   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
6514   if (Split)
6515     ConstsNode = DAG.getBitcast(VT, ConstsNode);
6516   return ConstsNode;
6517 }
6518 
6519 static SDValue getConstVector(ArrayRef<APInt> Bits, const APInt &Undefs,
6520                               MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6521   assert(Bits.size() == Undefs.getBitWidth() &&
6522          "Unequal constant and undef arrays");
6523   SmallVector<SDValue, 32> Ops;
6524   bool Split = false;
6525 
6526   MVT ConstVecVT = VT;
6527   unsigned NumElts = VT.getVectorNumElements();
6528   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
6529   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
6530     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
6531     Split = true;
6532   }
6533 
6534   MVT EltVT = ConstVecVT.getVectorElementType();
6535   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
6536     if (Undefs[i]) {
6537       Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
6538       continue;
6539     }
6540     const APInt &V = Bits[i];
6541     assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
6542     if (Split) {
6543       Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
6544       Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
6545     } else if (EltVT == MVT::f32) {
6546       APFloat FV(APFloat::IEEEsingle(), V);
6547       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
6548     } else if (EltVT == MVT::f64) {
6549       APFloat FV(APFloat::IEEEdouble(), V);
6550       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
6551     } else {
6552       Ops.push_back(DAG.getConstant(V, dl, EltVT));
6553     }
6554   }
6555 
6556   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
6557   return DAG.getBitcast(VT, ConstsNode);
6558 }
6559 
6560 static SDValue getConstVector(ArrayRef<APInt> Bits, MVT VT,
6561                               SelectionDAG &DAG, const SDLoc &dl) {
6562   APInt Undefs = APInt::getZero(Bits.size());
6563   return getConstVector(Bits, Undefs, VT, DAG, dl);
6564 }
6565 
6566 /// Returns a vector of specified type with all zero elements.
6567 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
6568                              SelectionDAG &DAG, const SDLoc &dl) {
6569   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
6570           VT.getVectorElementType() == MVT::i1) &&
6571          "Unexpected vector type");
6572 
6573   // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
6574   // type. This ensures they get CSE'd. But if the integer type is not
6575   // available, use a floating-point +0.0 instead.
6576   SDValue Vec;
6577   if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
6578     Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
6579   } else if (VT.isFloatingPoint()) {
6580     Vec = DAG.getConstantFP(+0.0, dl, VT);
6581   } else if (VT.getVectorElementType() == MVT::i1) {
6582     assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
6583            "Unexpected vector type");
6584     Vec = DAG.getConstant(0, dl, VT);
6585   } else {
6586     unsigned Num32BitElts = VT.getSizeInBits() / 32;
6587     Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
6588   }
6589   return DAG.getBitcast(VT, Vec);
6590 }
6591 
6592 // Helper to determine if the ops are all the extracted subvectors come from a
6593 // single source. If we allow commute they don't have to be in order (Lo/Hi).
6594 static SDValue getSplitVectorSrc(SDValue LHS, SDValue RHS, bool AllowCommute) {
6595   if (LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6596       RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6597       LHS.getValueType() != RHS.getValueType() ||
6598       LHS.getOperand(0) != RHS.getOperand(0))
6599     return SDValue();
6600 
6601   SDValue Src = LHS.getOperand(0);
6602   if (Src.getValueSizeInBits() != (LHS.getValueSizeInBits() * 2))
6603     return SDValue();
6604 
6605   unsigned NumElts = LHS.getValueType().getVectorNumElements();
6606   if ((LHS.getConstantOperandAPInt(1) == 0 &&
6607        RHS.getConstantOperandAPInt(1) == NumElts) ||
6608       (AllowCommute && RHS.getConstantOperandAPInt(1) == 0 &&
6609        LHS.getConstantOperandAPInt(1) == NumElts))
6610     return Src;
6611 
6612   return SDValue();
6613 }
6614 
6615 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
6616                                 const SDLoc &dl, unsigned vectorWidth) {
6617   EVT VT = Vec.getValueType();
6618   EVT ElVT = VT.getVectorElementType();
6619   unsigned Factor = VT.getSizeInBits() / vectorWidth;
6620   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
6621                                   VT.getVectorNumElements() / Factor);
6622 
6623   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
6624   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
6625   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
6626 
6627   // This is the index of the first element of the vectorWidth-bit chunk
6628   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
6629   IdxVal &= ~(ElemsPerChunk - 1);
6630 
6631   // If the input is a buildvector just emit a smaller one.
6632   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
6633     return DAG.getBuildVector(ResultVT, dl,
6634                               Vec->ops().slice(IdxVal, ElemsPerChunk));
6635 
6636   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
6637   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
6638 }
6639 
6640 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
6641 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
6642 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
6643 /// instructions or a simple subregister reference. Idx is an index in the
6644 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
6645 /// lowering EXTRACT_VECTOR_ELT operations easier.
6646 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
6647                                    SelectionDAG &DAG, const SDLoc &dl) {
6648   assert((Vec.getValueType().is256BitVector() ||
6649           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
6650   return extractSubVector(Vec, IdxVal, DAG, dl, 128);
6651 }
6652 
6653 /// Generate a DAG to grab 256-bits from a 512-bit vector.
6654 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
6655                                    SelectionDAG &DAG, const SDLoc &dl) {
6656   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
6657   return extractSubVector(Vec, IdxVal, DAG, dl, 256);
6658 }
6659 
6660 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
6661                                SelectionDAG &DAG, const SDLoc &dl,
6662                                unsigned vectorWidth) {
6663   assert((vectorWidth == 128 || vectorWidth == 256) &&
6664          "Unsupported vector width");
6665   // Inserting UNDEF is Result
6666   if (Vec.isUndef())
6667     return Result;
6668   EVT VT = Vec.getValueType();
6669   EVT ElVT = VT.getVectorElementType();
6670   EVT ResultVT = Result.getValueType();
6671 
6672   // Insert the relevant vectorWidth bits.
6673   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
6674   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
6675 
6676   // This is the index of the first element of the vectorWidth-bit chunk
6677   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
6678   IdxVal &= ~(ElemsPerChunk - 1);
6679 
6680   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
6681   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
6682 }
6683 
6684 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
6685 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
6686 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
6687 /// simple superregister reference.  Idx is an index in the 128 bits
6688 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
6689 /// lowering INSERT_VECTOR_ELT operations easier.
6690 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
6691                                   SelectionDAG &DAG, const SDLoc &dl) {
6692   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
6693   return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
6694 }
6695 
6696 /// Widen a vector to a larger size with the same scalar type, with the new
6697 /// elements either zero or undef.
6698 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
6699                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
6700                               const SDLoc &dl) {
6701   assert(Vec.getValueSizeInBits().getFixedValue() < VT.getFixedSizeInBits() &&
6702          Vec.getValueType().getScalarType() == VT.getScalarType() &&
6703          "Unsupported vector widening type");
6704   SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
6705                                 : DAG.getUNDEF(VT);
6706   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
6707                      DAG.getIntPtrConstant(0, dl));
6708 }
6709 
6710 /// Widen a vector to a larger size with the same scalar type, with the new
6711 /// elements either zero or undef.
6712 static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
6713                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
6714                               const SDLoc &dl, unsigned WideSizeInBits) {
6715   assert(Vec.getValueSizeInBits() < WideSizeInBits &&
6716          (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
6717          "Unsupported vector widening type");
6718   unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
6719   MVT SVT = Vec.getSimpleValueType().getScalarType();
6720   MVT VT = MVT::getVectorVT(SVT, WideNumElts);
6721   return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
6722 }
6723 
6724 // Helper function to collect subvector ops that are concatenated together,
6725 // either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
6726 // The subvectors in Ops are guaranteed to be the same type.
6727 static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops,
6728                              SelectionDAG &DAG) {
6729   assert(Ops.empty() && "Expected an empty ops vector");
6730 
6731   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
6732     Ops.append(N->op_begin(), N->op_end());
6733     return true;
6734   }
6735 
6736   if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
6737     SDValue Src = N->getOperand(0);
6738     SDValue Sub = N->getOperand(1);
6739     const APInt &Idx = N->getConstantOperandAPInt(2);
6740     EVT VT = Src.getValueType();
6741     EVT SubVT = Sub.getValueType();
6742 
6743     // TODO - Handle more general insert_subvector chains.
6744     if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2)) {
6745       // insert_subvector(undef, x, lo)
6746       if (Idx == 0 && Src.isUndef()) {
6747         Ops.push_back(Sub);
6748         Ops.push_back(DAG.getUNDEF(SubVT));
6749         return true;
6750       }
6751       if (Idx == (VT.getVectorNumElements() / 2)) {
6752         // insert_subvector(insert_subvector(undef, x, lo), y, hi)
6753         if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6754             Src.getOperand(1).getValueType() == SubVT &&
6755             isNullConstant(Src.getOperand(2))) {
6756           Ops.push_back(Src.getOperand(1));
6757           Ops.push_back(Sub);
6758           return true;
6759         }
6760         // insert_subvector(x, extract_subvector(x, lo), hi)
6761         if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6762             Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
6763           Ops.append(2, Sub);
6764           return true;
6765         }
6766         // insert_subvector(undef, x, hi)
6767         if (Src.isUndef()) {
6768           Ops.push_back(DAG.getUNDEF(SubVT));
6769           Ops.push_back(Sub);
6770           return true;
6771         }
6772       }
6773     }
6774   }
6775 
6776   return false;
6777 }
6778 
6779 // Helper to check if \p V can be split into subvectors and the upper subvectors
6780 // are all undef. In which case return the lower subvectors.
6781 static bool isUpperSubvectorUndef(SDValue V, SmallVectorImpl<SDValue> &LowerOps,
6782                                   SelectionDAG &DAG) {
6783   SmallVector<SDValue> SubOps;
6784   if (!collectConcatOps(V.getNode(), SubOps, DAG))
6785     return false;
6786 
6787   unsigned NumSubOps = SubOps.size();
6788   assert((NumSubOps % 2) == 0 && "Unexpected number of subvectors");
6789 
6790   ArrayRef<SDValue> UpperOps(SubOps.begin() + (NumSubOps / 2), SubOps.end());
6791   if (any_of(UpperOps, [](SDValue Op) { return !Op.isUndef(); }))
6792     return false;
6793 
6794   LowerOps.assign(SubOps.begin(), SubOps.begin() + (NumSubOps / 2));
6795   return true;
6796 }
6797 
6798 // Helper to check if we can access all the constituent subvectors without any
6799 // extract ops.
6800 static bool isFreeToSplitVector(SDNode *N, SelectionDAG &DAG) {
6801   SmallVector<SDValue> Ops;
6802   return collectConcatOps(N, Ops, DAG);
6803 }
6804 
6805 static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
6806                                                const SDLoc &dl) {
6807   EVT VT = Op.getValueType();
6808   unsigned NumElems = VT.getVectorNumElements();
6809   unsigned SizeInBits = VT.getSizeInBits();
6810   assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
6811          "Can't split odd sized vector");
6812 
6813   // If this is a splat value (with no-undefs) then use the lower subvector,
6814   // which should be a free extraction.
6815   SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
6816   if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
6817     return std::make_pair(Lo, Lo);
6818 
6819   SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
6820   return std::make_pair(Lo, Hi);
6821 }
6822 
6823 /// Break an operation into 2 half sized ops and then concatenate the results.
6824 static SDValue splitVectorOp(SDValue Op, SelectionDAG &DAG) {
6825   unsigned NumOps = Op.getNumOperands();
6826   EVT VT = Op.getValueType();
6827   SDLoc dl(Op);
6828 
6829   // Extract the LHS Lo/Hi vectors
6830   SmallVector<SDValue> LoOps(NumOps, SDValue());
6831   SmallVector<SDValue> HiOps(NumOps, SDValue());
6832   for (unsigned I = 0; I != NumOps; ++I) {
6833     SDValue SrcOp = Op.getOperand(I);
6834     if (!SrcOp.getValueType().isVector()) {
6835       LoOps[I] = HiOps[I] = SrcOp;
6836       continue;
6837     }
6838     std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
6839   }
6840 
6841   EVT LoVT, HiVT;
6842   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6843   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
6844                      DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
6845                      DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
6846 }
6847 
6848 /// Break an unary integer operation into 2 half sized ops and then
6849 /// concatenate the result back.
6850 static SDValue splitVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
6851   // Make sure we only try to split 256/512-bit types to avoid creating
6852   // narrow vectors.
6853   EVT VT = Op.getValueType();
6854   (void)VT;
6855   assert((Op.getOperand(0).getValueType().is256BitVector() ||
6856           Op.getOperand(0).getValueType().is512BitVector()) &&
6857          (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
6858   assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
6859              VT.getVectorNumElements() &&
6860          "Unexpected VTs!");
6861   return splitVectorOp(Op, DAG);
6862 }
6863 
6864 /// Break a binary integer operation into 2 half sized ops and then
6865 /// concatenate the result back.
6866 static SDValue splitVectorIntBinary(SDValue Op, SelectionDAG &DAG) {
6867   // Assert that all the types match.
6868   EVT VT = Op.getValueType();
6869   (void)VT;
6870   assert(Op.getOperand(0).getValueType() == VT &&
6871          Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
6872   assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
6873   return splitVectorOp(Op, DAG);
6874 }
6875 
6876 // Helper for splitting operands of an operation to legal target size and
6877 // apply a function on each part.
6878 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
6879 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
6880 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
6881 // The argument Builder is a function that will be applied on each split part:
6882 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
6883 template <typename F>
6884 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
6885                          const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
6886                          F Builder, bool CheckBWI = true) {
6887   assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
6888   unsigned NumSubs = 1;
6889   if ((CheckBWI && Subtarget.useBWIRegs()) ||
6890       (!CheckBWI && Subtarget.useAVX512Regs())) {
6891     if (VT.getSizeInBits() > 512) {
6892       NumSubs = VT.getSizeInBits() / 512;
6893       assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
6894     }
6895   } else if (Subtarget.hasAVX2()) {
6896     if (VT.getSizeInBits() > 256) {
6897       NumSubs = VT.getSizeInBits() / 256;
6898       assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
6899     }
6900   } else {
6901     if (VT.getSizeInBits() > 128) {
6902       NumSubs = VT.getSizeInBits() / 128;
6903       assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
6904     }
6905   }
6906 
6907   if (NumSubs == 1)
6908     return Builder(DAG, DL, Ops);
6909 
6910   SmallVector<SDValue, 4> Subs;
6911   for (unsigned i = 0; i != NumSubs; ++i) {
6912     SmallVector<SDValue, 2> SubOps;
6913     for (SDValue Op : Ops) {
6914       EVT OpVT = Op.getValueType();
6915       unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
6916       unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
6917       SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
6918     }
6919     Subs.push_back(Builder(DAG, DL, SubOps));
6920   }
6921   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
6922 }
6923 
6924 // Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
6925 // targets.
6926 static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
6927                              ArrayRef<SDValue> Ops, SelectionDAG &DAG,
6928                              const X86Subtarget &Subtarget) {
6929   assert(Subtarget.hasAVX512() && "AVX512 target expected");
6930   MVT SVT = VT.getScalarType();
6931 
6932   // If we have a 32/64 splatted constant, splat it to DstTy to
6933   // encourage a foldable broadcast'd operand.
6934   auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
6935     unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
6936     // AVX512 broadcasts 32/64-bit operands.
6937     // TODO: Support float once getAVX512Node is used by fp-ops.
6938     if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
6939         !DAG.getTargetLoweringInfo().isTypeLegal(SVT))
6940       return SDValue();
6941     // If we're not widening, don't bother if we're not bitcasting.
6942     if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
6943       return SDValue();
6944     if (auto *BV = dyn_cast<BuildVectorSDNode>(peekThroughBitcasts(Op))) {
6945       APInt SplatValue, SplatUndef;
6946       unsigned SplatBitSize;
6947       bool HasAnyUndefs;
6948       if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6949                               HasAnyUndefs, OpEltSizeInBits) &&
6950           !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
6951         return DAG.getConstant(SplatValue, DL, DstVT);
6952     }
6953     return SDValue();
6954   };
6955 
6956   bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
6957 
6958   MVT DstVT = VT;
6959   if (Widen)
6960     DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
6961 
6962   // Canonicalize src operands.
6963   SmallVector<SDValue> SrcOps(Ops.begin(), Ops.end());
6964   for (SDValue &Op : SrcOps) {
6965     MVT OpVT = Op.getSimpleValueType();
6966     // Just pass through scalar operands.
6967     if (!OpVT.isVector())
6968       continue;
6969     assert(OpVT == VT && "Vector type mismatch");
6970 
6971     if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
6972       Op = BroadcastOp;
6973       continue;
6974     }
6975 
6976     // Just widen the subvector by inserting into an undef wide vector.
6977     if (Widen)
6978       Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
6979   }
6980 
6981   SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
6982 
6983   // Perform the 512-bit op then extract the bottom subvector.
6984   if (Widen)
6985     Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
6986   return Res;
6987 }
6988 
6989 /// Insert i1-subvector to i1-vector.
6990 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
6991                                 const X86Subtarget &Subtarget) {
6992 
6993   SDLoc dl(Op);
6994   SDValue Vec = Op.getOperand(0);
6995   SDValue SubVec = Op.getOperand(1);
6996   SDValue Idx = Op.getOperand(2);
6997   unsigned IdxVal = Op.getConstantOperandVal(2);
6998 
6999   // Inserting undef is a nop. We can just return the original vector.
7000   if (SubVec.isUndef())
7001     return Vec;
7002 
7003   if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
7004     return Op;
7005 
7006   MVT OpVT = Op.getSimpleValueType();
7007   unsigned NumElems = OpVT.getVectorNumElements();
7008   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
7009 
7010   // Extend to natively supported kshift.
7011   MVT WideOpVT = OpVT;
7012   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
7013     WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
7014 
7015   // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
7016   // if necessary.
7017   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
7018     // May need to promote to a legal type.
7019     Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
7020                      DAG.getConstant(0, dl, WideOpVT),
7021                      SubVec, Idx);
7022     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
7023   }
7024 
7025   MVT SubVecVT = SubVec.getSimpleValueType();
7026   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
7027   assert(IdxVal + SubVecNumElems <= NumElems &&
7028          IdxVal % SubVecVT.getSizeInBits() == 0 &&
7029          "Unexpected index value in INSERT_SUBVECTOR");
7030 
7031   SDValue Undef = DAG.getUNDEF(WideOpVT);
7032 
7033   if (IdxVal == 0) {
7034     // Zero lower bits of the Vec
7035     SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
7036     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
7037                       ZeroIdx);
7038     Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
7039     Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
7040     // Merge them together, SubVec should be zero extended.
7041     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
7042                          DAG.getConstant(0, dl, WideOpVT),
7043                          SubVec, ZeroIdx);
7044     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
7045     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
7046   }
7047 
7048   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
7049                        Undef, SubVec, ZeroIdx);
7050 
7051   if (Vec.isUndef()) {
7052     assert(IdxVal != 0 && "Unexpected index");
7053     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
7054                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
7055     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
7056   }
7057 
7058   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
7059     assert(IdxVal != 0 && "Unexpected index");
7060     // If upper elements of Vec are known undef, then just shift into place.
7061     if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
7062                      [](SDValue V) { return V.isUndef(); })) {
7063       SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
7064                            DAG.getTargetConstant(IdxVal, dl, MVT::i8));
7065     } else {
7066       NumElems = WideOpVT.getVectorNumElements();
7067       unsigned ShiftLeft = NumElems - SubVecNumElems;
7068       unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
7069       SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
7070                            DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
7071       if (ShiftRight != 0)
7072         SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
7073                              DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
7074     }
7075     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
7076   }
7077 
7078   // Simple case when we put subvector in the upper part
7079   if (IdxVal + SubVecNumElems == NumElems) {
7080     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
7081                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
7082     if (SubVecNumElems * 2 == NumElems) {
7083       // Special case, use legal zero extending insert_subvector. This allows
7084       // isel to optimize when bits are known zero.
7085       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
7086       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
7087                         DAG.getConstant(0, dl, WideOpVT),
7088                         Vec, ZeroIdx);
7089     } else {
7090       // Otherwise use explicit shifts to zero the bits.
7091       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
7092                         Undef, Vec, ZeroIdx);
7093       NumElems = WideOpVT.getVectorNumElements();
7094       SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
7095       Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
7096       Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
7097     }
7098     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
7099     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
7100   }
7101 
7102   // Inserting into the middle is more complicated.
7103 
7104   NumElems = WideOpVT.getVectorNumElements();
7105 
7106   // Widen the vector if needed.
7107   Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
7108 
7109   unsigned ShiftLeft = NumElems - SubVecNumElems;
7110   unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
7111 
7112   // Do an optimization for the the most frequently used types.
7113   if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
7114     APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
7115     Mask0.flipAllBits();
7116     SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
7117     SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
7118     Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
7119     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
7120                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
7121     SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
7122                          DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
7123     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
7124 
7125     // Reduce to original width if needed.
7126     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
7127   }
7128 
7129   // Clear the upper bits of the subvector and move it to its insert position.
7130   SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
7131                        DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
7132   SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
7133                        DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
7134 
7135   // Isolate the bits below the insertion point.
7136   unsigned LowShift = NumElems - IdxVal;
7137   SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
7138                             DAG.getTargetConstant(LowShift, dl, MVT::i8));
7139   Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
7140                     DAG.getTargetConstant(LowShift, dl, MVT::i8));
7141 
7142   // Isolate the bits after the last inserted bit.
7143   unsigned HighShift = IdxVal + SubVecNumElems;
7144   SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
7145                             DAG.getTargetConstant(HighShift, dl, MVT::i8));
7146   High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
7147                     DAG.getTargetConstant(HighShift, dl, MVT::i8));
7148 
7149   // Now OR all 3 pieces together.
7150   Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
7151   SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
7152 
7153   // Reduce to original width if needed.
7154   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
7155 }
7156 
7157 static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
7158                                 const SDLoc &dl) {
7159   assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
7160   EVT SubVT = V1.getValueType();
7161   EVT SubSVT = SubVT.getScalarType();
7162   unsigned SubNumElts = SubVT.getVectorNumElements();
7163   unsigned SubVectorWidth = SubVT.getSizeInBits();
7164   EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
7165   SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
7166   return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
7167 }
7168 
7169 /// Returns a vector of specified type with all bits set.
7170 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
7171 /// Then bitcast to their original type, ensuring they get CSE'd.
7172 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
7173   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
7174          "Expected a 128/256/512-bit vector type");
7175 
7176   APInt Ones = APInt::getAllOnes(32);
7177   unsigned NumElts = VT.getSizeInBits() / 32;
7178   SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
7179   return DAG.getBitcast(VT, Vec);
7180 }
7181 
7182 static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
7183                                       SDValue In, SelectionDAG &DAG) {
7184   EVT InVT = In.getValueType();
7185   assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
7186   assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
7187           ISD::ZERO_EXTEND == Opcode) &&
7188          "Unknown extension opcode");
7189 
7190   // For 256-bit vectors, we only need the lower (128-bit) input half.
7191   // For 512-bit vectors, we only need the lower input half or quarter.
7192   if (InVT.getSizeInBits() > 128) {
7193     assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
7194            "Expected VTs to be the same size!");
7195     unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
7196     In = extractSubVector(In, 0, DAG, DL,
7197                           std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
7198     InVT = In.getValueType();
7199   }
7200 
7201   if (VT.getVectorNumElements() != InVT.getVectorNumElements())
7202     Opcode = DAG.getOpcode_EXTEND_VECTOR_INREG(Opcode);
7203 
7204   return DAG.getNode(Opcode, DL, VT, In);
7205 }
7206 
7207 // Create OR(AND(LHS,MASK),AND(RHS,~MASK)) bit select pattern
7208 static SDValue getBitSelect(const SDLoc &DL, MVT VT, SDValue LHS, SDValue RHS,
7209                             SDValue Mask, SelectionDAG &DAG) {
7210   LHS = DAG.getNode(ISD::AND, DL, VT, LHS, Mask);
7211   RHS = DAG.getNode(X86ISD::ANDNP, DL, VT, Mask, RHS);
7212   return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
7213 }
7214 
7215 // Match (xor X, -1) -> X.
7216 // Match extract_subvector(xor X, -1) -> extract_subvector(X).
7217 // Match concat_vectors(xor X, -1, xor Y, -1) -> concat_vectors(X, Y).
7218 static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
7219   V = peekThroughBitcasts(V);
7220   if (V.getOpcode() == ISD::XOR &&
7221       (ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()) ||
7222        isAllOnesConstant(V.getOperand(1))))
7223     return V.getOperand(0);
7224   if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
7225       (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
7226     if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
7227       Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
7228       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
7229                          Not, V.getOperand(1));
7230     }
7231   }
7232   SmallVector<SDValue, 2> CatOps;
7233   if (collectConcatOps(V.getNode(), CatOps, DAG)) {
7234     for (SDValue &CatOp : CatOps) {
7235       SDValue NotCat = IsNOT(CatOp, DAG);
7236       if (!NotCat) return SDValue();
7237       CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
7238     }
7239     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), V.getValueType(), CatOps);
7240   }
7241   return SDValue();
7242 }
7243 
7244 void llvm::createUnpackShuffleMask(EVT VT, SmallVectorImpl<int> &Mask,
7245                                    bool Lo, bool Unary) {
7246   assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
7247          "Illegal vector type to unpack");
7248   assert(Mask.empty() && "Expected an empty shuffle mask vector");
7249   int NumElts = VT.getVectorNumElements();
7250   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
7251   for (int i = 0; i < NumElts; ++i) {
7252     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
7253     int Pos = (i % NumEltsInLane) / 2 + LaneStart;
7254     Pos += (Unary ? 0 : NumElts * (i % 2));
7255     Pos += (Lo ? 0 : NumEltsInLane / 2);
7256     Mask.push_back(Pos);
7257   }
7258 }
7259 
7260 /// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
7261 /// imposed by AVX and specific to the unary pattern. Example:
7262 /// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
7263 /// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
7264 void llvm::createSplat2ShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
7265                                    bool Lo) {
7266   assert(Mask.empty() && "Expected an empty shuffle mask vector");
7267   int NumElts = VT.getVectorNumElements();
7268   for (int i = 0; i < NumElts; ++i) {
7269     int Pos = i / 2;
7270     Pos += (Lo ? 0 : NumElts / 2);
7271     Mask.push_back(Pos);
7272   }
7273 }
7274 
7275 // Attempt to constant fold, else just create a VECTOR_SHUFFLE.
7276 static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
7277                                 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
7278   if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
7279       (ISD::isBuildVectorOfConstantSDNodes(V2.getNode()) || V2.isUndef())) {
7280     SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
7281     for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
7282       int M = Mask[I];
7283       if (M < 0)
7284         continue;
7285       SDValue V = (M < NumElts) ? V1 : V2;
7286       if (V.isUndef())
7287         continue;
7288       Ops[I] = V.getOperand(M % NumElts);
7289     }
7290     return DAG.getBuildVector(VT, dl, Ops);
7291   }
7292 
7293   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
7294 }
7295 
7296 /// Returns a vector_shuffle node for an unpackl operation.
7297 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
7298                           SDValue V1, SDValue V2) {
7299   SmallVector<int, 8> Mask;
7300   createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
7301   return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
7302 }
7303 
7304 /// Returns a vector_shuffle node for an unpackh operation.
7305 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
7306                           SDValue V1, SDValue V2) {
7307   SmallVector<int, 8> Mask;
7308   createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
7309   return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
7310 }
7311 
7312 /// Returns a node that packs the LHS + RHS nodes together at half width.
7313 /// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
7314 /// TODO: Add subvector splitting if/when we have a need for it.
7315 static SDValue getPack(SelectionDAG &DAG, const X86Subtarget &Subtarget,
7316                        const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
7317                        bool PackHiHalf = false) {
7318   MVT OpVT = LHS.getSimpleValueType();
7319   unsigned EltSizeInBits = VT.getScalarSizeInBits();
7320   bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
7321   assert(OpVT == RHS.getSimpleValueType() &&
7322          VT.getSizeInBits() == OpVT.getSizeInBits() &&
7323          (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
7324          "Unexpected PACK operand types");
7325   assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
7326          "Unexpected PACK result type");
7327 
7328   // Rely on vector shuffles for vXi64 -> vXi32 packing.
7329   if (EltSizeInBits == 32) {
7330     SmallVector<int> PackMask;
7331     int Offset = PackHiHalf ? 1 : 0;
7332     int NumElts = VT.getVectorNumElements();
7333     for (int I = 0; I != NumElts; I += 4) {
7334       PackMask.push_back(I + Offset);
7335       PackMask.push_back(I + Offset + 2);
7336       PackMask.push_back(I + Offset + NumElts);
7337       PackMask.push_back(I + Offset + NumElts + 2);
7338     }
7339     return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
7340                                 DAG.getBitcast(VT, RHS), PackMask);
7341   }
7342 
7343   // See if we already have sufficient leading bits for PACKSS/PACKUS.
7344   if (!PackHiHalf) {
7345     if (UsePackUS &&
7346         DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
7347         DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
7348       return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
7349 
7350     if (DAG.ComputeMaxSignificantBits(LHS) <= EltSizeInBits &&
7351         DAG.ComputeMaxSignificantBits(RHS) <= EltSizeInBits)
7352       return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
7353   }
7354 
7355   // Fallback to sign/zero extending the requested half and pack.
7356   SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
7357   if (UsePackUS) {
7358     if (PackHiHalf) {
7359       LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
7360       RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
7361     } else {
7362       SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
7363       LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
7364       RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
7365     };
7366     return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
7367   };
7368 
7369   if (!PackHiHalf) {
7370     LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
7371     RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
7372   }
7373   LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
7374   RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
7375   return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
7376 }
7377 
7378 /// Return a vector_shuffle of the specified vector of zero or undef vector.
7379 /// This produces a shuffle where the low element of V2 is swizzled into the
7380 /// zero/undef vector, landing at element Idx.
7381 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
7382 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
7383                                            bool IsZero,
7384                                            const X86Subtarget &Subtarget,
7385                                            SelectionDAG &DAG) {
7386   MVT VT = V2.getSimpleValueType();
7387   SDValue V1 = IsZero
7388     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
7389   int NumElems = VT.getVectorNumElements();
7390   SmallVector<int, 16> MaskVec(NumElems);
7391   for (int i = 0; i != NumElems; ++i)
7392     // If this is the insertion idx, put the low elt of V2 here.
7393     MaskVec[i] = (i == Idx) ? NumElems : i;
7394   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
7395 }
7396 
7397 static const Constant *getTargetConstantFromBasePtr(SDValue Ptr) {
7398   if (Ptr.getOpcode() == X86ISD::Wrapper ||
7399       Ptr.getOpcode() == X86ISD::WrapperRIP)
7400     Ptr = Ptr.getOperand(0);
7401 
7402   auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
7403   if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
7404     return nullptr;
7405 
7406   return CNode->getConstVal();
7407 }
7408 
7409 static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
7410   if (!Load || !ISD::isNormalLoad(Load))
7411     return nullptr;
7412   return getTargetConstantFromBasePtr(Load->getBasePtr());
7413 }
7414 
7415 static const Constant *getTargetConstantFromNode(SDValue Op) {
7416   Op = peekThroughBitcasts(Op);
7417   return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
7418 }
7419 
7420 const Constant *
7421 X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
7422   assert(LD && "Unexpected null LoadSDNode");
7423   return getTargetConstantFromNode(LD);
7424 }
7425 
7426 // Extract raw constant bits from constant pools.
7427 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
7428                                           APInt &UndefElts,
7429                                           SmallVectorImpl<APInt> &EltBits,
7430                                           bool AllowWholeUndefs = true,
7431                                           bool AllowPartialUndefs = true) {
7432   assert(EltBits.empty() && "Expected an empty EltBits vector");
7433 
7434   Op = peekThroughBitcasts(Op);
7435 
7436   EVT VT = Op.getValueType();
7437   unsigned SizeInBits = VT.getSizeInBits();
7438   assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
7439   unsigned NumElts = SizeInBits / EltSizeInBits;
7440 
7441   // Bitcast a source array of element bits to the target size.
7442   auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
7443     unsigned NumSrcElts = UndefSrcElts.getBitWidth();
7444     unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
7445     assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
7446            "Constant bit sizes don't match");
7447 
7448     // Don't split if we don't allow undef bits.
7449     bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
7450     if (UndefSrcElts.getBoolValue() && !AllowUndefs)
7451       return false;
7452 
7453     // If we're already the right size, don't bother bitcasting.
7454     if (NumSrcElts == NumElts) {
7455       UndefElts = UndefSrcElts;
7456       EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
7457       return true;
7458     }
7459 
7460     // Extract all the undef/constant element data and pack into single bitsets.
7461     APInt UndefBits(SizeInBits, 0);
7462     APInt MaskBits(SizeInBits, 0);
7463 
7464     for (unsigned i = 0; i != NumSrcElts; ++i) {
7465       unsigned BitOffset = i * SrcEltSizeInBits;
7466       if (UndefSrcElts[i])
7467         UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
7468       MaskBits.insertBits(SrcEltBits[i], BitOffset);
7469     }
7470 
7471     // Split the undef/constant single bitset data into the target elements.
7472     UndefElts = APInt(NumElts, 0);
7473     EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
7474 
7475     for (unsigned i = 0; i != NumElts; ++i) {
7476       unsigned BitOffset = i * EltSizeInBits;
7477       APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
7478 
7479       // Only treat an element as UNDEF if all bits are UNDEF.
7480       if (UndefEltBits.isAllOnes()) {
7481         if (!AllowWholeUndefs)
7482           return false;
7483         UndefElts.setBit(i);
7484         continue;
7485       }
7486 
7487       // If only some bits are UNDEF then treat them as zero (or bail if not
7488       // supported).
7489       if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
7490         return false;
7491 
7492       EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
7493     }
7494     return true;
7495   };
7496 
7497   // Collect constant bits and insert into mask/undef bit masks.
7498   auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
7499                                 unsigned UndefBitIndex) {
7500     if (!Cst)
7501       return false;
7502     if (isa<UndefValue>(Cst)) {
7503       Undefs.setBit(UndefBitIndex);
7504       return true;
7505     }
7506     if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
7507       Mask = CInt->getValue();
7508       return true;
7509     }
7510     if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
7511       Mask = CFP->getValueAPF().bitcastToAPInt();
7512       return true;
7513     }
7514     if (auto *CDS = dyn_cast<ConstantDataSequential>(Cst)) {
7515       Type *Ty = CDS->getType();
7516       Mask = APInt::getZero(Ty->getPrimitiveSizeInBits());
7517       Type *EltTy = CDS->getElementType();
7518       bool IsInteger = EltTy->isIntegerTy();
7519       bool IsFP =
7520           EltTy->isHalfTy() || EltTy->isFloatTy() || EltTy->isDoubleTy();
7521       if (!IsInteger && !IsFP)
7522         return false;
7523       unsigned EltBits = EltTy->getPrimitiveSizeInBits();
7524       for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
7525         if (IsInteger)
7526           Mask.insertBits(CDS->getElementAsAPInt(I), I * EltBits);
7527         else
7528           Mask.insertBits(CDS->getElementAsAPFloat(I).bitcastToAPInt(),
7529                           I * EltBits);
7530       return true;
7531     }
7532     return false;
7533   };
7534 
7535   // Handle UNDEFs.
7536   if (Op.isUndef()) {
7537     APInt UndefSrcElts = APInt::getAllOnes(NumElts);
7538     SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
7539     return CastBitData(UndefSrcElts, SrcEltBits);
7540   }
7541 
7542   // Extract scalar constant bits.
7543   if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
7544     APInt UndefSrcElts = APInt::getZero(1);
7545     SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
7546     return CastBitData(UndefSrcElts, SrcEltBits);
7547   }
7548   if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7549     APInt UndefSrcElts = APInt::getZero(1);
7550     APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
7551     SmallVector<APInt, 64> SrcEltBits(1, RawBits);
7552     return CastBitData(UndefSrcElts, SrcEltBits);
7553   }
7554 
7555   // Extract constant bits from build vector.
7556   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
7557     BitVector Undefs;
7558     SmallVector<APInt> SrcEltBits;
7559     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7560     if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
7561       APInt UndefSrcElts = APInt::getZero(SrcEltBits.size());
7562       for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
7563         if (Undefs[I])
7564           UndefSrcElts.setBit(I);
7565       return CastBitData(UndefSrcElts, SrcEltBits);
7566     }
7567   }
7568 
7569   // Extract constant bits from constant pool vector.
7570   if (auto *Cst = getTargetConstantFromNode(Op)) {
7571     Type *CstTy = Cst->getType();
7572     unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
7573     if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
7574       return false;
7575 
7576     unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
7577     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7578 
7579     APInt UndefSrcElts(NumSrcElts, 0);
7580     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
7581     for (unsigned i = 0; i != NumSrcElts; ++i)
7582       if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
7583                                UndefSrcElts, i))
7584         return false;
7585 
7586     return CastBitData(UndefSrcElts, SrcEltBits);
7587   }
7588 
7589   // Extract constant bits from a broadcasted constant pool scalar.
7590   if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
7591       EltSizeInBits <= VT.getScalarSizeInBits()) {
7592     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
7593     if (MemIntr->getMemoryVT().getStoreSizeInBits() != VT.getScalarSizeInBits())
7594       return false;
7595 
7596     SDValue Ptr = MemIntr->getBasePtr();
7597     if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
7598       unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7599       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7600 
7601       APInt UndefSrcElts(NumSrcElts, 0);
7602       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
7603       if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
7604         if (UndefSrcElts[0])
7605           UndefSrcElts.setBits(0, NumSrcElts);
7606         if (SrcEltBits[0].getBitWidth() != SrcEltSizeInBits)
7607           SrcEltBits[0] = SrcEltBits[0].trunc(SrcEltSizeInBits);
7608         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
7609         return CastBitData(UndefSrcElts, SrcEltBits);
7610       }
7611     }
7612   }
7613 
7614   // Extract constant bits from a subvector broadcast.
7615   if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
7616     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
7617     SDValue Ptr = MemIntr->getBasePtr();
7618     // The source constant may be larger than the subvector broadcast,
7619     // ensure we extract the correct subvector constants.
7620     if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
7621       Type *CstTy = Cst->getType();
7622       unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
7623       unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
7624       if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
7625           (SizeInBits % SubVecSizeInBits) != 0)
7626         return false;
7627       unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
7628       unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
7629       unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
7630       APInt UndefSubElts(NumSubElts, 0);
7631       SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
7632                                         APInt(CstEltSizeInBits, 0));
7633       for (unsigned i = 0; i != NumSubElts; ++i) {
7634         if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
7635                                  UndefSubElts, i))
7636           return false;
7637         for (unsigned j = 1; j != NumSubVecs; ++j)
7638           SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
7639       }
7640       UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
7641                                      UndefSubElts);
7642       return CastBitData(UndefSubElts, SubEltBits);
7643     }
7644   }
7645 
7646   // Extract a rematerialized scalar constant insertion.
7647   if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
7648       Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7649       isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
7650     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7651     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7652 
7653     APInt UndefSrcElts(NumSrcElts, 0);
7654     SmallVector<APInt, 64> SrcEltBits;
7655     auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
7656     SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
7657     SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
7658     return CastBitData(UndefSrcElts, SrcEltBits);
7659   }
7660 
7661   // Insert constant bits from a base and sub vector sources.
7662   if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
7663     // If bitcasts to larger elements we might lose track of undefs - don't
7664     // allow any to be safe.
7665     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7666     bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
7667 
7668     APInt UndefSrcElts, UndefSubElts;
7669     SmallVector<APInt, 32> EltSrcBits, EltSubBits;
7670     if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
7671                                       UndefSubElts, EltSubBits,
7672                                       AllowWholeUndefs && AllowUndefs,
7673                                       AllowPartialUndefs && AllowUndefs) &&
7674         getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
7675                                       UndefSrcElts, EltSrcBits,
7676                                       AllowWholeUndefs && AllowUndefs,
7677                                       AllowPartialUndefs && AllowUndefs)) {
7678       unsigned BaseIdx = Op.getConstantOperandVal(2);
7679       UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
7680       for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
7681         EltSrcBits[BaseIdx + i] = EltSubBits[i];
7682       return CastBitData(UndefSrcElts, EltSrcBits);
7683     }
7684   }
7685 
7686   // Extract constant bits from a subvector's source.
7687   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7688     // TODO - support extract_subvector through bitcasts.
7689     if (EltSizeInBits != VT.getScalarSizeInBits())
7690       return false;
7691 
7692     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
7693                                       UndefElts, EltBits, AllowWholeUndefs,
7694                                       AllowPartialUndefs)) {
7695       EVT SrcVT = Op.getOperand(0).getValueType();
7696       unsigned NumSrcElts = SrcVT.getVectorNumElements();
7697       unsigned NumSubElts = VT.getVectorNumElements();
7698       unsigned BaseIdx = Op.getConstantOperandVal(1);
7699       UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
7700       if ((BaseIdx + NumSubElts) != NumSrcElts)
7701         EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
7702       if (BaseIdx != 0)
7703         EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
7704       return true;
7705     }
7706   }
7707 
7708   // Extract constant bits from shuffle node sources.
7709   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
7710     // TODO - support shuffle through bitcasts.
7711     if (EltSizeInBits != VT.getScalarSizeInBits())
7712       return false;
7713 
7714     ArrayRef<int> Mask = SVN->getMask();
7715     if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
7716         llvm::any_of(Mask, [](int M) { return M < 0; }))
7717       return false;
7718 
7719     APInt UndefElts0, UndefElts1;
7720     SmallVector<APInt, 32> EltBits0, EltBits1;
7721     if (isAnyInRange(Mask, 0, NumElts) &&
7722         !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
7723                                        UndefElts0, EltBits0, AllowWholeUndefs,
7724                                        AllowPartialUndefs))
7725       return false;
7726     if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
7727         !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
7728                                        UndefElts1, EltBits1, AllowWholeUndefs,
7729                                        AllowPartialUndefs))
7730       return false;
7731 
7732     UndefElts = APInt::getZero(NumElts);
7733     for (int i = 0; i != (int)NumElts; ++i) {
7734       int M = Mask[i];
7735       if (M < 0) {
7736         UndefElts.setBit(i);
7737         EltBits.push_back(APInt::getZero(EltSizeInBits));
7738       } else if (M < (int)NumElts) {
7739         if (UndefElts0[M])
7740           UndefElts.setBit(i);
7741         EltBits.push_back(EltBits0[M]);
7742       } else {
7743         if (UndefElts1[M - NumElts])
7744           UndefElts.setBit(i);
7745         EltBits.push_back(EltBits1[M - NumElts]);
7746       }
7747     }
7748     return true;
7749   }
7750 
7751   return false;
7752 }
7753 
7754 namespace llvm {
7755 namespace X86 {
7756 bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
7757   APInt UndefElts;
7758   SmallVector<APInt, 16> EltBits;
7759   if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
7760                                     UndefElts, EltBits, true,
7761                                     AllowPartialUndefs)) {
7762     int SplatIndex = -1;
7763     for (int i = 0, e = EltBits.size(); i != e; ++i) {
7764       if (UndefElts[i])
7765         continue;
7766       if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
7767         SplatIndex = -1;
7768         break;
7769       }
7770       SplatIndex = i;
7771     }
7772     if (0 <= SplatIndex) {
7773       SplatVal = EltBits[SplatIndex];
7774       return true;
7775     }
7776   }
7777 
7778   return false;
7779 }
7780 } // namespace X86
7781 } // namespace llvm
7782 
7783 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
7784                                         unsigned MaskEltSizeInBits,
7785                                         SmallVectorImpl<uint64_t> &RawMask,
7786                                         APInt &UndefElts) {
7787   // Extract the raw target constant bits.
7788   SmallVector<APInt, 64> EltBits;
7789   if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
7790                                      EltBits, /* AllowWholeUndefs */ true,
7791                                      /* AllowPartialUndefs */ false))
7792     return false;
7793 
7794   // Insert the extracted elements into the mask.
7795   for (const APInt &Elt : EltBits)
7796     RawMask.push_back(Elt.getZExtValue());
7797 
7798   return true;
7799 }
7800 
7801 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
7802 /// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
7803 /// Note: This ignores saturation, so inputs must be checked first.
7804 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
7805                                   bool Unary, unsigned NumStages = 1) {
7806   assert(Mask.empty() && "Expected an empty shuffle mask vector");
7807   unsigned NumElts = VT.getVectorNumElements();
7808   unsigned NumLanes = VT.getSizeInBits() / 128;
7809   unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
7810   unsigned Offset = Unary ? 0 : NumElts;
7811   unsigned Repetitions = 1u << (NumStages - 1);
7812   unsigned Increment = 1u << NumStages;
7813   assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
7814 
7815   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
7816     for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
7817       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
7818         Mask.push_back(Elt + (Lane * NumEltsPerLane));
7819       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
7820         Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
7821     }
7822   }
7823 }
7824 
7825 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
7826 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
7827                                 APInt &DemandedLHS, APInt &DemandedRHS) {
7828   int NumLanes = VT.getSizeInBits() / 128;
7829   int NumElts = DemandedElts.getBitWidth();
7830   int NumInnerElts = NumElts / 2;
7831   int NumEltsPerLane = NumElts / NumLanes;
7832   int NumInnerEltsPerLane = NumInnerElts / NumLanes;
7833 
7834   DemandedLHS = APInt::getZero(NumInnerElts);
7835   DemandedRHS = APInt::getZero(NumInnerElts);
7836 
7837   // Map DemandedElts to the packed operands.
7838   for (int Lane = 0; Lane != NumLanes; ++Lane) {
7839     for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
7840       int OuterIdx = (Lane * NumEltsPerLane) + Elt;
7841       int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
7842       if (DemandedElts[OuterIdx])
7843         DemandedLHS.setBit(InnerIdx);
7844       if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
7845         DemandedRHS.setBit(InnerIdx);
7846     }
7847   }
7848 }
7849 
7850 // Split the demanded elts of a HADD/HSUB node between its operands.
7851 static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
7852                                  APInt &DemandedLHS, APInt &DemandedRHS) {
7853   int NumLanes = VT.getSizeInBits() / 128;
7854   int NumElts = DemandedElts.getBitWidth();
7855   int NumEltsPerLane = NumElts / NumLanes;
7856   int HalfEltsPerLane = NumEltsPerLane / 2;
7857 
7858   DemandedLHS = APInt::getZero(NumElts);
7859   DemandedRHS = APInt::getZero(NumElts);
7860 
7861   // Map DemandedElts to the horizontal operands.
7862   for (int Idx = 0; Idx != NumElts; ++Idx) {
7863     if (!DemandedElts[Idx])
7864       continue;
7865     int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
7866     int LocalIdx = Idx % NumEltsPerLane;
7867     if (LocalIdx < HalfEltsPerLane) {
7868       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
7869       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
7870     } else {
7871       LocalIdx -= HalfEltsPerLane;
7872       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
7873       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
7874     }
7875   }
7876 }
7877 
7878 /// Calculates the shuffle mask corresponding to the target-specific opcode.
7879 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
7880 /// operands in \p Ops, and returns true.
7881 /// Sets \p IsUnary to true if only one source is used. Note that this will set
7882 /// IsUnary for shuffles which use a single input multiple times, and in those
7883 /// cases it will adjust the mask to only have indices within that single input.
7884 /// It is an error to call this with non-empty Mask/Ops vectors.
7885 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
7886                                  SmallVectorImpl<SDValue> &Ops,
7887                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
7888   unsigned NumElems = VT.getVectorNumElements();
7889   unsigned MaskEltSize = VT.getScalarSizeInBits();
7890   SmallVector<uint64_t, 32> RawMask;
7891   APInt RawUndefs;
7892   uint64_t ImmN;
7893 
7894   assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
7895   assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
7896 
7897   IsUnary = false;
7898   bool IsFakeUnary = false;
7899   switch (N->getOpcode()) {
7900   case X86ISD::BLENDI:
7901     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7902     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7903     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7904     DecodeBLENDMask(NumElems, ImmN, Mask);
7905     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7906     break;
7907   case X86ISD::SHUFP:
7908     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7909     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7910     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7911     DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
7912     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7913     break;
7914   case X86ISD::INSERTPS:
7915     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7916     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7917     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7918     DecodeINSERTPSMask(ImmN, Mask);
7919     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7920     break;
7921   case X86ISD::EXTRQI:
7922     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7923     if (isa<ConstantSDNode>(N->getOperand(1)) &&
7924         isa<ConstantSDNode>(N->getOperand(2))) {
7925       int BitLen = N->getConstantOperandVal(1);
7926       int BitIdx = N->getConstantOperandVal(2);
7927       DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
7928       IsUnary = true;
7929     }
7930     break;
7931   case X86ISD::INSERTQI:
7932     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7933     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7934     if (isa<ConstantSDNode>(N->getOperand(2)) &&
7935         isa<ConstantSDNode>(N->getOperand(3))) {
7936       int BitLen = N->getConstantOperandVal(2);
7937       int BitIdx = N->getConstantOperandVal(3);
7938       DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
7939       IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7940     }
7941     break;
7942   case X86ISD::UNPCKH:
7943     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7944     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7945     DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
7946     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7947     break;
7948   case X86ISD::UNPCKL:
7949     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7950     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7951     DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
7952     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7953     break;
7954   case X86ISD::MOVHLPS:
7955     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7956     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7957     DecodeMOVHLPSMask(NumElems, Mask);
7958     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7959     break;
7960   case X86ISD::MOVLHPS:
7961     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7962     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7963     DecodeMOVLHPSMask(NumElems, Mask);
7964     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7965     break;
7966   case X86ISD::VALIGN:
7967     assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
7968            "Only 32-bit and 64-bit elements are supported!");
7969     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7970     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7971     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7972     DecodeVALIGNMask(NumElems, ImmN, Mask);
7973     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7974     Ops.push_back(N->getOperand(1));
7975     Ops.push_back(N->getOperand(0));
7976     break;
7977   case X86ISD::PALIGNR:
7978     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7979     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7980     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7981     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7982     DecodePALIGNRMask(NumElems, ImmN, Mask);
7983     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7984     Ops.push_back(N->getOperand(1));
7985     Ops.push_back(N->getOperand(0));
7986     break;
7987   case X86ISD::VSHLDQ:
7988     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7989     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7990     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7991     DecodePSLLDQMask(NumElems, ImmN, Mask);
7992     IsUnary = true;
7993     break;
7994   case X86ISD::VSRLDQ:
7995     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7996     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7997     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7998     DecodePSRLDQMask(NumElems, ImmN, Mask);
7999     IsUnary = true;
8000     break;
8001   case X86ISD::PSHUFD:
8002   case X86ISD::VPERMILPI:
8003     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8004     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
8005     DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
8006     IsUnary = true;
8007     break;
8008   case X86ISD::PSHUFHW:
8009     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8010     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
8011     DecodePSHUFHWMask(NumElems, ImmN, Mask);
8012     IsUnary = true;
8013     break;
8014   case X86ISD::PSHUFLW:
8015     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8016     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
8017     DecodePSHUFLWMask(NumElems, ImmN, Mask);
8018     IsUnary = true;
8019     break;
8020   case X86ISD::VZEXT_MOVL:
8021     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8022     DecodeZeroMoveLowMask(NumElems, Mask);
8023     IsUnary = true;
8024     break;
8025   case X86ISD::VBROADCAST:
8026     // We only decode broadcasts of same-sized vectors, peeking through to
8027     // extracted subvectors is likely to cause hasOneUse issues with
8028     // SimplifyDemandedBits etc.
8029     if (N->getOperand(0).getValueType() == VT) {
8030       DecodeVectorBroadcast(NumElems, Mask);
8031       IsUnary = true;
8032       break;
8033     }
8034     return false;
8035   case X86ISD::VPERMILPV: {
8036     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8037     IsUnary = true;
8038     SDValue MaskNode = N->getOperand(1);
8039     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
8040                                     RawUndefs)) {
8041       DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
8042       break;
8043     }
8044     return false;
8045   }
8046   case X86ISD::PSHUFB: {
8047     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
8048     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8049     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
8050     IsUnary = true;
8051     SDValue MaskNode = N->getOperand(1);
8052     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
8053       DecodePSHUFBMask(RawMask, RawUndefs, Mask);
8054       break;
8055     }
8056     return false;
8057   }
8058   case X86ISD::VPERMI:
8059     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8060     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
8061     DecodeVPERMMask(NumElems, ImmN, Mask);
8062     IsUnary = true;
8063     break;
8064   case X86ISD::MOVSS:
8065   case X86ISD::MOVSD:
8066   case X86ISD::MOVSH:
8067     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8068     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
8069     DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
8070     break;
8071   case X86ISD::VPERM2X128:
8072     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8073     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
8074     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
8075     DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
8076     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
8077     break;
8078   case X86ISD::SHUF128:
8079     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8080     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
8081     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
8082     decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
8083     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
8084     break;
8085   case X86ISD::MOVSLDUP:
8086     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8087     DecodeMOVSLDUPMask(NumElems, Mask);
8088     IsUnary = true;
8089     break;
8090   case X86ISD::MOVSHDUP:
8091     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8092     DecodeMOVSHDUPMask(NumElems, Mask);
8093     IsUnary = true;
8094     break;
8095   case X86ISD::MOVDDUP:
8096     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8097     DecodeMOVDDUPMask(NumElems, Mask);
8098     IsUnary = true;
8099     break;
8100   case X86ISD::VPERMIL2: {
8101     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8102     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
8103     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
8104     SDValue MaskNode = N->getOperand(2);
8105     SDValue CtrlNode = N->getOperand(3);
8106     if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
8107       unsigned CtrlImm = CtrlOp->getZExtValue();
8108       if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
8109                                       RawUndefs)) {
8110         DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
8111                             Mask);
8112         break;
8113       }
8114     }
8115     return false;
8116   }
8117   case X86ISD::VPPERM: {
8118     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8119     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
8120     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
8121     SDValue MaskNode = N->getOperand(2);
8122     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
8123       DecodeVPPERMMask(RawMask, RawUndefs, Mask);
8124       break;
8125     }
8126     return false;
8127   }
8128   case X86ISD::VPERMV: {
8129     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
8130     IsUnary = true;
8131     // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
8132     Ops.push_back(N->getOperand(1));
8133     SDValue MaskNode = N->getOperand(0);
8134     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
8135                                     RawUndefs)) {
8136       DecodeVPERMVMask(RawMask, RawUndefs, Mask);
8137       break;
8138     }
8139     return false;
8140   }
8141   case X86ISD::VPERMV3: {
8142     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
8143     assert(N->getOperand(2).getValueType() == VT && "Unexpected value type");
8144     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
8145     // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
8146     Ops.push_back(N->getOperand(0));
8147     Ops.push_back(N->getOperand(2));
8148     SDValue MaskNode = N->getOperand(1);
8149     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
8150                                     RawUndefs)) {
8151       DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
8152       break;
8153     }
8154     return false;
8155   }
8156   default: llvm_unreachable("unknown target shuffle node");
8157   }
8158 
8159   // Empty mask indicates the decode failed.
8160   if (Mask.empty())
8161     return false;
8162 
8163   // Check if we're getting a shuffle mask with zero'd elements.
8164   if (!AllowSentinelZero && isAnyZero(Mask))
8165     return false;
8166 
8167   // If we have a fake unary shuffle, the shuffle mask is spread across two
8168   // inputs that are actually the same node. Re-map the mask to always point
8169   // into the first input.
8170   if (IsFakeUnary)
8171     for (int &M : Mask)
8172       if (M >= (int)Mask.size())
8173         M -= Mask.size();
8174 
8175   // If we didn't already add operands in the opcode-specific code, default to
8176   // adding 1 or 2 operands starting at 0.
8177   if (Ops.empty()) {
8178     Ops.push_back(N->getOperand(0));
8179     if (!IsUnary || IsFakeUnary)
8180       Ops.push_back(N->getOperand(1));
8181   }
8182 
8183   return true;
8184 }
8185 
8186 // Wrapper for getTargetShuffleMask with InUnary;
8187 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
8188                                  SmallVectorImpl<SDValue> &Ops,
8189                                  SmallVectorImpl<int> &Mask) {
8190   bool IsUnary;
8191   return getTargetShuffleMask(N, VT, AllowSentinelZero, Ops, Mask, IsUnary);
8192 }
8193 
8194 /// Compute whether each element of a shuffle is zeroable.
8195 ///
8196 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
8197 /// Either it is an undef element in the shuffle mask, the element of the input
8198 /// referenced is undef, or the element of the input referenced is known to be
8199 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
8200 /// as many lanes with this technique as possible to simplify the remaining
8201 /// shuffle.
8202 static void computeZeroableShuffleElements(ArrayRef<int> Mask,
8203                                            SDValue V1, SDValue V2,
8204                                            APInt &KnownUndef, APInt &KnownZero) {
8205   int Size = Mask.size();
8206   KnownUndef = KnownZero = APInt::getZero(Size);
8207 
8208   V1 = peekThroughBitcasts(V1);
8209   V2 = peekThroughBitcasts(V2);
8210 
8211   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
8212   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
8213 
8214   int VectorSizeInBits = V1.getValueSizeInBits();
8215   int ScalarSizeInBits = VectorSizeInBits / Size;
8216   assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
8217 
8218   for (int i = 0; i < Size; ++i) {
8219     int M = Mask[i];
8220     // Handle the easy cases.
8221     if (M < 0) {
8222       KnownUndef.setBit(i);
8223       continue;
8224     }
8225     if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
8226       KnownZero.setBit(i);
8227       continue;
8228     }
8229 
8230     // Determine shuffle input and normalize the mask.
8231     SDValue V = M < Size ? V1 : V2;
8232     M %= Size;
8233 
8234     // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
8235     if (V.getOpcode() != ISD::BUILD_VECTOR)
8236       continue;
8237 
8238     // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
8239     // the (larger) source element must be UNDEF/ZERO.
8240     if ((Size % V.getNumOperands()) == 0) {
8241       int Scale = Size / V->getNumOperands();
8242       SDValue Op = V.getOperand(M / Scale);
8243       if (Op.isUndef())
8244         KnownUndef.setBit(i);
8245       if (X86::isZeroNode(Op))
8246         KnownZero.setBit(i);
8247       else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
8248         APInt Val = Cst->getAPIntValue();
8249         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
8250         if (Val == 0)
8251           KnownZero.setBit(i);
8252       } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
8253         APInt Val = Cst->getValueAPF().bitcastToAPInt();
8254         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
8255         if (Val == 0)
8256           KnownZero.setBit(i);
8257       }
8258       continue;
8259     }
8260 
8261     // If the BUILD_VECTOR has more elements then all the (smaller) source
8262     // elements must be UNDEF or ZERO.
8263     if ((V.getNumOperands() % Size) == 0) {
8264       int Scale = V->getNumOperands() / Size;
8265       bool AllUndef = true;
8266       bool AllZero = true;
8267       for (int j = 0; j < Scale; ++j) {
8268         SDValue Op = V.getOperand((M * Scale) + j);
8269         AllUndef &= Op.isUndef();
8270         AllZero &= X86::isZeroNode(Op);
8271       }
8272       if (AllUndef)
8273         KnownUndef.setBit(i);
8274       if (AllZero)
8275         KnownZero.setBit(i);
8276       continue;
8277     }
8278   }
8279 }
8280 
8281 /// Decode a target shuffle mask and inputs and see if any values are
8282 /// known to be undef or zero from their inputs.
8283 /// Returns true if the target shuffle mask was decoded.
8284 /// FIXME: Merge this with computeZeroableShuffleElements?
8285 static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
8286                                          SmallVectorImpl<SDValue> &Ops,
8287                                          APInt &KnownUndef, APInt &KnownZero) {
8288   bool IsUnary;
8289   if (!isTargetShuffle(N.getOpcode()))
8290     return false;
8291 
8292   MVT VT = N.getSimpleValueType();
8293   if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
8294     return false;
8295 
8296   int Size = Mask.size();
8297   SDValue V1 = Ops[0];
8298   SDValue V2 = IsUnary ? V1 : Ops[1];
8299   KnownUndef = KnownZero = APInt::getZero(Size);
8300 
8301   V1 = peekThroughBitcasts(V1);
8302   V2 = peekThroughBitcasts(V2);
8303 
8304   assert((VT.getSizeInBits() % Size) == 0 &&
8305          "Illegal split of shuffle value type");
8306   unsigned EltSizeInBits = VT.getSizeInBits() / Size;
8307 
8308   // Extract known constant input data.
8309   APInt UndefSrcElts[2];
8310   SmallVector<APInt, 32> SrcEltBits[2];
8311   bool IsSrcConstant[2] = {
8312       getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
8313                                     SrcEltBits[0], true, false),
8314       getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
8315                                     SrcEltBits[1], true, false)};
8316 
8317   for (int i = 0; i < Size; ++i) {
8318     int M = Mask[i];
8319 
8320     // Already decoded as SM_SentinelZero / SM_SentinelUndef.
8321     if (M < 0) {
8322       assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
8323       if (SM_SentinelUndef == M)
8324         KnownUndef.setBit(i);
8325       if (SM_SentinelZero == M)
8326         KnownZero.setBit(i);
8327       continue;
8328     }
8329 
8330     // Determine shuffle input and normalize the mask.
8331     unsigned SrcIdx = M / Size;
8332     SDValue V = M < Size ? V1 : V2;
8333     M %= Size;
8334 
8335     // We are referencing an UNDEF input.
8336     if (V.isUndef()) {
8337       KnownUndef.setBit(i);
8338       continue;
8339     }
8340 
8341     // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
8342     // TODO: We currently only set UNDEF for integer types - floats use the same
8343     // registers as vectors and many of the scalar folded loads rely on the
8344     // SCALAR_TO_VECTOR pattern.
8345     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8346         (Size % V.getValueType().getVectorNumElements()) == 0) {
8347       int Scale = Size / V.getValueType().getVectorNumElements();
8348       int Idx = M / Scale;
8349       if (Idx != 0 && !VT.isFloatingPoint())
8350         KnownUndef.setBit(i);
8351       else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
8352         KnownZero.setBit(i);
8353       continue;
8354     }
8355 
8356     // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
8357     // base vectors.
8358     if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
8359       SDValue Vec = V.getOperand(0);
8360       int NumVecElts = Vec.getValueType().getVectorNumElements();
8361       if (Vec.isUndef() && Size == NumVecElts) {
8362         int Idx = V.getConstantOperandVal(2);
8363         int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
8364         if (M < Idx || (Idx + NumSubElts) <= M)
8365           KnownUndef.setBit(i);
8366       }
8367       continue;
8368     }
8369 
8370     // Attempt to extract from the source's constant bits.
8371     if (IsSrcConstant[SrcIdx]) {
8372       if (UndefSrcElts[SrcIdx][M])
8373         KnownUndef.setBit(i);
8374       else if (SrcEltBits[SrcIdx][M] == 0)
8375         KnownZero.setBit(i);
8376     }
8377   }
8378 
8379   assert(VT.getVectorNumElements() == (unsigned)Size &&
8380          "Different mask size from vector size!");
8381   return true;
8382 }
8383 
8384 // Replace target shuffle mask elements with known undef/zero sentinels.
8385 static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
8386                                               const APInt &KnownUndef,
8387                                               const APInt &KnownZero,
8388                                               bool ResolveKnownZeros= true) {
8389   unsigned NumElts = Mask.size();
8390   assert(KnownUndef.getBitWidth() == NumElts &&
8391          KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
8392 
8393   for (unsigned i = 0; i != NumElts; ++i) {
8394     if (KnownUndef[i])
8395       Mask[i] = SM_SentinelUndef;
8396     else if (ResolveKnownZeros && KnownZero[i])
8397       Mask[i] = SM_SentinelZero;
8398   }
8399 }
8400 
8401 // Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
8402 static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
8403                                               APInt &KnownUndef,
8404                                               APInt &KnownZero) {
8405   unsigned NumElts = Mask.size();
8406   KnownUndef = KnownZero = APInt::getZero(NumElts);
8407 
8408   for (unsigned i = 0; i != NumElts; ++i) {
8409     int M = Mask[i];
8410     if (SM_SentinelUndef == M)
8411       KnownUndef.setBit(i);
8412     if (SM_SentinelZero == M)
8413       KnownZero.setBit(i);
8414   }
8415 }
8416 
8417 // Attempt to create a shuffle mask from a VSELECT/BLENDV condition mask.
8418 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
8419                                          SDValue Cond, bool IsBLENDV = false) {
8420   EVT CondVT = Cond.getValueType();
8421   unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
8422   unsigned NumElts = CondVT.getVectorNumElements();
8423 
8424   APInt UndefElts;
8425   SmallVector<APInt, 32> EltBits;
8426   if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
8427                                      true, false))
8428     return false;
8429 
8430   Mask.resize(NumElts, SM_SentinelUndef);
8431 
8432   for (int i = 0; i != (int)NumElts; ++i) {
8433     Mask[i] = i;
8434     // Arbitrarily choose from the 2nd operand if the select condition element
8435     // is undef.
8436     // TODO: Can we do better by matching patterns such as even/odd?
8437     if (UndefElts[i] || (!IsBLENDV && EltBits[i].isZero()) ||
8438         (IsBLENDV && EltBits[i].isNonNegative()))
8439       Mask[i] += NumElts;
8440   }
8441 
8442   return true;
8443 }
8444 
8445 // Forward declaration (for getFauxShuffleMask recursive check).
8446 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
8447                                    SmallVectorImpl<SDValue> &Inputs,
8448                                    SmallVectorImpl<int> &Mask,
8449                                    const SelectionDAG &DAG, unsigned Depth,
8450                                    bool ResolveKnownElts);
8451 
8452 // Attempt to decode ops that could be represented as a shuffle mask.
8453 // The decoded shuffle mask may contain a different number of elements to the
8454 // destination value type.
8455 // TODO: Merge into getTargetShuffleInputs()
8456 static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
8457                                SmallVectorImpl<int> &Mask,
8458                                SmallVectorImpl<SDValue> &Ops,
8459                                const SelectionDAG &DAG, unsigned Depth,
8460                                bool ResolveKnownElts) {
8461   Mask.clear();
8462   Ops.clear();
8463 
8464   MVT VT = N.getSimpleValueType();
8465   unsigned NumElts = VT.getVectorNumElements();
8466   unsigned NumSizeInBits = VT.getSizeInBits();
8467   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
8468   if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
8469     return false;
8470   assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
8471   unsigned NumSizeInBytes = NumSizeInBits / 8;
8472   unsigned NumBytesPerElt = NumBitsPerElt / 8;
8473 
8474   unsigned Opcode = N.getOpcode();
8475   switch (Opcode) {
8476   case ISD::VECTOR_SHUFFLE: {
8477     // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
8478     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
8479     if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
8480       Mask.append(ShuffleMask.begin(), ShuffleMask.end());
8481       Ops.push_back(N.getOperand(0));
8482       Ops.push_back(N.getOperand(1));
8483       return true;
8484     }
8485     return false;
8486   }
8487   case ISD::AND:
8488   case X86ISD::ANDNP: {
8489     // Attempt to decode as a per-byte mask.
8490     APInt UndefElts;
8491     SmallVector<APInt, 32> EltBits;
8492     SDValue N0 = N.getOperand(0);
8493     SDValue N1 = N.getOperand(1);
8494     bool IsAndN = (X86ISD::ANDNP == Opcode);
8495     uint64_t ZeroMask = IsAndN ? 255 : 0;
8496     if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
8497       return false;
8498     // We can't assume an undef src element gives an undef dst - the other src
8499     // might be zero.
8500     if (!UndefElts.isZero())
8501       return false;
8502     for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
8503       const APInt &ByteBits = EltBits[i];
8504       if (ByteBits != 0 && ByteBits != 255)
8505         return false;
8506       Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
8507     }
8508     Ops.push_back(IsAndN ? N1 : N0);
8509     return true;
8510   }
8511   case ISD::OR: {
8512     // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
8513     // is a valid shuffle index.
8514     SDValue N0 = peekThroughBitcasts(N.getOperand(0));
8515     SDValue N1 = peekThroughBitcasts(N.getOperand(1));
8516     if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
8517       return false;
8518 
8519     SmallVector<int, 64> SrcMask0, SrcMask1;
8520     SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
8521     APInt Demand0 = APInt::getAllOnes(N0.getValueType().getVectorNumElements());
8522     APInt Demand1 = APInt::getAllOnes(N1.getValueType().getVectorNumElements());
8523     if (!getTargetShuffleInputs(N0, Demand0, SrcInputs0, SrcMask0, DAG,
8524                                 Depth + 1, true) ||
8525         !getTargetShuffleInputs(N1, Demand1, SrcInputs1, SrcMask1, DAG,
8526                                 Depth + 1, true))
8527       return false;
8528 
8529     size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
8530     SmallVector<int, 64> Mask0, Mask1;
8531     narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
8532     narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
8533     for (int i = 0; i != (int)MaskSize; ++i) {
8534       // NOTE: Don't handle SM_SentinelUndef, as we can end up in infinite
8535       // loops converting between OR and BLEND shuffles due to
8536       // canWidenShuffleElements merging away undef elements, meaning we
8537       // fail to recognise the OR as the undef element isn't known zero.
8538       if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
8539         Mask.push_back(SM_SentinelZero);
8540       else if (Mask1[i] == SM_SentinelZero)
8541         Mask.push_back(i);
8542       else if (Mask0[i] == SM_SentinelZero)
8543         Mask.push_back(i + MaskSize);
8544       else
8545         return false;
8546     }
8547     Ops.push_back(N0);
8548     Ops.push_back(N1);
8549     return true;
8550   }
8551   case ISD::INSERT_SUBVECTOR: {
8552     SDValue Src = N.getOperand(0);
8553     SDValue Sub = N.getOperand(1);
8554     EVT SubVT = Sub.getValueType();
8555     unsigned NumSubElts = SubVT.getVectorNumElements();
8556     if (!N->isOnlyUserOf(Sub.getNode()))
8557       return false;
8558     uint64_t InsertIdx = N.getConstantOperandVal(2);
8559     // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
8560     if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8561         Sub.getOperand(0).getValueType() == VT) {
8562       uint64_t ExtractIdx = Sub.getConstantOperandVal(1);
8563       for (int i = 0; i != (int)NumElts; ++i)
8564         Mask.push_back(i);
8565       for (int i = 0; i != (int)NumSubElts; ++i)
8566         Mask[InsertIdx + i] = NumElts + ExtractIdx + i;
8567       Ops.push_back(Src);
8568       Ops.push_back(Sub.getOperand(0));
8569       return true;
8570     }
8571     // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
8572     SmallVector<int, 64> SubMask;
8573     SmallVector<SDValue, 2> SubInputs;
8574     SDValue SubSrc = peekThroughOneUseBitcasts(Sub);
8575     EVT SubSrcVT = SubSrc.getValueType();
8576     if (!SubSrcVT.isVector())
8577       return false;
8578 
8579     APInt SubDemand = APInt::getAllOnes(SubSrcVT.getVectorNumElements());
8580     if (!getTargetShuffleInputs(SubSrc, SubDemand, SubInputs, SubMask, DAG,
8581                                 Depth + 1, ResolveKnownElts))
8582       return false;
8583 
8584     // Subvector shuffle inputs must not be larger than the subvector.
8585     if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
8586           return SubVT.getFixedSizeInBits() <
8587                  SubInput.getValueSizeInBits().getFixedValue();
8588         }))
8589       return false;
8590 
8591     if (SubMask.size() != NumSubElts) {
8592       assert(((SubMask.size() % NumSubElts) == 0 ||
8593               (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale");
8594       if ((NumSubElts % SubMask.size()) == 0) {
8595         int Scale = NumSubElts / SubMask.size();
8596         SmallVector<int,64> ScaledSubMask;
8597         narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
8598         SubMask = ScaledSubMask;
8599       } else {
8600         int Scale = SubMask.size() / NumSubElts;
8601         NumSubElts = SubMask.size();
8602         NumElts *= Scale;
8603         InsertIdx *= Scale;
8604       }
8605     }
8606     Ops.push_back(Src);
8607     Ops.append(SubInputs.begin(), SubInputs.end());
8608     if (ISD::isBuildVectorAllZeros(Src.getNode()))
8609       Mask.append(NumElts, SM_SentinelZero);
8610     else
8611       for (int i = 0; i != (int)NumElts; ++i)
8612         Mask.push_back(i);
8613     for (int i = 0; i != (int)NumSubElts; ++i) {
8614       int M = SubMask[i];
8615       if (0 <= M) {
8616         int InputIdx = M / NumSubElts;
8617         M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
8618       }
8619       Mask[i + InsertIdx] = M;
8620     }
8621     return true;
8622   }
8623   case X86ISD::PINSRB:
8624   case X86ISD::PINSRW:
8625   case ISD::SCALAR_TO_VECTOR:
8626   case ISD::INSERT_VECTOR_ELT: {
8627     // Match against a insert_vector_elt/scalar_to_vector of an extract from a
8628     // vector, for matching src/dst vector types.
8629     SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
8630 
8631     unsigned DstIdx = 0;
8632     if (Opcode != ISD::SCALAR_TO_VECTOR) {
8633       // Check we have an in-range constant insertion index.
8634       if (!isa<ConstantSDNode>(N.getOperand(2)) ||
8635           N.getConstantOperandAPInt(2).uge(NumElts))
8636         return false;
8637       DstIdx = N.getConstantOperandVal(2);
8638 
8639       // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
8640       if (X86::isZeroNode(Scl)) {
8641         Ops.push_back(N.getOperand(0));
8642         for (unsigned i = 0; i != NumElts; ++i)
8643           Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
8644         return true;
8645       }
8646     }
8647 
8648     // Peek through trunc/aext/zext.
8649     // TODO: aext shouldn't require SM_SentinelZero padding.
8650     // TODO: handle shift of scalars.
8651     unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
8652     while (Scl.getOpcode() == ISD::TRUNCATE ||
8653            Scl.getOpcode() == ISD::ANY_EXTEND ||
8654            Scl.getOpcode() == ISD::ZERO_EXTEND) {
8655       Scl = Scl.getOperand(0);
8656       MinBitsPerElt =
8657           std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
8658     }
8659     if ((MinBitsPerElt % 8) != 0)
8660       return false;
8661 
8662     // Attempt to find the source vector the scalar was extracted from.
8663     SDValue SrcExtract;
8664     if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
8665          Scl.getOpcode() == X86ISD::PEXTRW ||
8666          Scl.getOpcode() == X86ISD::PEXTRB) &&
8667         Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
8668       SrcExtract = Scl;
8669     }
8670     if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
8671       return false;
8672 
8673     SDValue SrcVec = SrcExtract.getOperand(0);
8674     EVT SrcVT = SrcVec.getValueType();
8675     if (!SrcVT.getScalarType().isByteSized())
8676       return false;
8677     unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
8678     unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
8679     unsigned DstByte = DstIdx * NumBytesPerElt;
8680     MinBitsPerElt =
8681         std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
8682 
8683     // Create 'identity' byte level shuffle mask and then add inserted bytes.
8684     if (Opcode == ISD::SCALAR_TO_VECTOR) {
8685       Ops.push_back(SrcVec);
8686       Mask.append(NumSizeInBytes, SM_SentinelUndef);
8687     } else {
8688       Ops.push_back(SrcVec);
8689       Ops.push_back(N.getOperand(0));
8690       for (int i = 0; i != (int)NumSizeInBytes; ++i)
8691         Mask.push_back(NumSizeInBytes + i);
8692     }
8693 
8694     unsigned MinBytesPerElts = MinBitsPerElt / 8;
8695     MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
8696     for (unsigned i = 0; i != MinBytesPerElts; ++i)
8697       Mask[DstByte + i] = SrcByte + i;
8698     for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
8699       Mask[DstByte + i] = SM_SentinelZero;
8700     return true;
8701   }
8702   case X86ISD::PACKSS:
8703   case X86ISD::PACKUS: {
8704     SDValue N0 = N.getOperand(0);
8705     SDValue N1 = N.getOperand(1);
8706     assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
8707            N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
8708            "Unexpected input value type");
8709 
8710     APInt EltsLHS, EltsRHS;
8711     getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
8712 
8713     // If we know input saturation won't happen (or we don't care for particular
8714     // lanes), we can treat this as a truncation shuffle.
8715     bool Offset0 = false, Offset1 = false;
8716     if (Opcode == X86ISD::PACKSS) {
8717       if ((!(N0.isUndef() || EltsLHS.isZero()) &&
8718            DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
8719           (!(N1.isUndef() || EltsRHS.isZero()) &&
8720            DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
8721         return false;
8722       // We can't easily fold ASHR into a shuffle, but if it was feeding a
8723       // PACKSS then it was likely being used for sign-extension for a
8724       // truncation, so just peek through and adjust the mask accordingly.
8725       if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
8726           N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
8727         Offset0 = true;
8728         N0 = N0.getOperand(0);
8729       }
8730       if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
8731           N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
8732         Offset1 = true;
8733         N1 = N1.getOperand(0);
8734       }
8735     } else {
8736       APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
8737       if ((!(N0.isUndef() || EltsLHS.isZero()) &&
8738            !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
8739           (!(N1.isUndef() || EltsRHS.isZero()) &&
8740            !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
8741         return false;
8742     }
8743 
8744     bool IsUnary = (N0 == N1);
8745 
8746     Ops.push_back(N0);
8747     if (!IsUnary)
8748       Ops.push_back(N1);
8749 
8750     createPackShuffleMask(VT, Mask, IsUnary);
8751 
8752     if (Offset0 || Offset1) {
8753       for (int &M : Mask)
8754         if ((Offset0 && isInRange(M, 0, NumElts)) ||
8755             (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
8756           ++M;
8757     }
8758     return true;
8759   }
8760   case ISD::VSELECT:
8761   case X86ISD::BLENDV: {
8762     SDValue Cond = N.getOperand(0);
8763     if (createShuffleMaskFromVSELECT(Mask, Cond, Opcode == X86ISD::BLENDV)) {
8764       Ops.push_back(N.getOperand(1));
8765       Ops.push_back(N.getOperand(2));
8766       return true;
8767     }
8768     return false;
8769   }
8770   case X86ISD::VTRUNC: {
8771     SDValue Src = N.getOperand(0);
8772     EVT SrcVT = Src.getValueType();
8773     // Truncated source must be a simple vector.
8774     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
8775         (SrcVT.getScalarSizeInBits() % 8) != 0)
8776       return false;
8777     unsigned NumSrcElts = SrcVT.getVectorNumElements();
8778     unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
8779     unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
8780     assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
8781     for (unsigned i = 0; i != NumSrcElts; ++i)
8782       Mask.push_back(i * Scale);
8783     Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
8784     Ops.push_back(Src);
8785     return true;
8786   }
8787   case X86ISD::VSHLI:
8788   case X86ISD::VSRLI: {
8789     uint64_t ShiftVal = N.getConstantOperandVal(1);
8790     // Out of range bit shifts are guaranteed to be zero.
8791     if (NumBitsPerElt <= ShiftVal) {
8792       Mask.append(NumElts, SM_SentinelZero);
8793       return true;
8794     }
8795 
8796     // We can only decode 'whole byte' bit shifts as shuffles.
8797     if ((ShiftVal % 8) != 0)
8798       break;
8799 
8800     uint64_t ByteShift = ShiftVal / 8;
8801     Ops.push_back(N.getOperand(0));
8802 
8803     // Clear mask to all zeros and insert the shifted byte indices.
8804     Mask.append(NumSizeInBytes, SM_SentinelZero);
8805 
8806     if (X86ISD::VSHLI == Opcode) {
8807       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
8808         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
8809           Mask[i + j] = i + j - ByteShift;
8810     } else {
8811       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
8812         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
8813           Mask[i + j - ByteShift] = i + j;
8814     }
8815     return true;
8816   }
8817   case X86ISD::VROTLI:
8818   case X86ISD::VROTRI: {
8819     // We can only decode 'whole byte' bit rotates as shuffles.
8820     uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
8821     if ((RotateVal % 8) != 0)
8822       return false;
8823     Ops.push_back(N.getOperand(0));
8824     int Offset = RotateVal / 8;
8825     Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
8826     for (int i = 0; i != (int)NumElts; ++i) {
8827       int BaseIdx = i * NumBytesPerElt;
8828       for (int j = 0; j != (int)NumBytesPerElt; ++j) {
8829         Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
8830       }
8831     }
8832     return true;
8833   }
8834   case X86ISD::VBROADCAST: {
8835     SDValue Src = N.getOperand(0);
8836     if (!Src.getSimpleValueType().isVector()) {
8837       if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8838           !isNullConstant(Src.getOperand(1)) ||
8839           Src.getOperand(0).getValueType().getScalarType() !=
8840               VT.getScalarType())
8841         return false;
8842       Src = Src.getOperand(0);
8843     }
8844     Ops.push_back(Src);
8845     Mask.append(NumElts, 0);
8846     return true;
8847   }
8848   case ISD::SIGN_EXTEND_VECTOR_INREG: {
8849     SDValue Src = N.getOperand(0);
8850     EVT SrcVT = Src.getValueType();
8851     unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
8852 
8853     // Extended source must be a simple vector.
8854     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
8855         (NumBitsPerSrcElt % 8) != 0)
8856       return false;
8857 
8858     // We can only handle all-signbits extensions.
8859     APInt DemandedSrcElts =
8860         DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
8861     if (DAG.ComputeNumSignBits(Src, DemandedSrcElts) != NumBitsPerSrcElt)
8862       return false;
8863 
8864     assert((NumBitsPerElt % NumBitsPerSrcElt) == 0 && "Unexpected extension");
8865     unsigned Scale = NumBitsPerElt / NumBitsPerSrcElt;
8866     for (unsigned I = 0; I != NumElts; ++I)
8867       Mask.append(Scale, I);
8868     Ops.push_back(Src);
8869     return true;
8870   }
8871   case ISD::ZERO_EXTEND:
8872   case ISD::ANY_EXTEND:
8873   case ISD::ZERO_EXTEND_VECTOR_INREG:
8874   case ISD::ANY_EXTEND_VECTOR_INREG: {
8875     SDValue Src = N.getOperand(0);
8876     EVT SrcVT = Src.getValueType();
8877 
8878     // Extended source must be a simple vector.
8879     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
8880         (SrcVT.getScalarSizeInBits() % 8) != 0)
8881       return false;
8882 
8883     bool IsAnyExtend =
8884         (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
8885     DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
8886                          IsAnyExtend, Mask);
8887     Ops.push_back(Src);
8888     return true;
8889   }
8890   }
8891 
8892   return false;
8893 }
8894 
8895 /// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
8896 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
8897                                               SmallVectorImpl<int> &Mask) {
8898   int MaskWidth = Mask.size();
8899   SmallVector<SDValue, 16> UsedInputs;
8900   for (int i = 0, e = Inputs.size(); i < e; ++i) {
8901     int lo = UsedInputs.size() * MaskWidth;
8902     int hi = lo + MaskWidth;
8903 
8904     // Strip UNDEF input usage.
8905     if (Inputs[i].isUndef())
8906       for (int &M : Mask)
8907         if ((lo <= M) && (M < hi))
8908           M = SM_SentinelUndef;
8909 
8910     // Check for unused inputs.
8911     if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
8912       for (int &M : Mask)
8913         if (lo <= M)
8914           M -= MaskWidth;
8915       continue;
8916     }
8917 
8918     // Check for repeated inputs.
8919     bool IsRepeat = false;
8920     for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
8921       if (UsedInputs[j] != Inputs[i])
8922         continue;
8923       for (int &M : Mask)
8924         if (lo <= M)
8925           M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
8926       IsRepeat = true;
8927       break;
8928     }
8929     if (IsRepeat)
8930       continue;
8931 
8932     UsedInputs.push_back(Inputs[i]);
8933   }
8934   Inputs = UsedInputs;
8935 }
8936 
8937 /// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
8938 /// and then sets the SM_SentinelUndef and SM_SentinelZero values.
8939 /// Returns true if the target shuffle mask was decoded.
8940 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
8941                                    SmallVectorImpl<SDValue> &Inputs,
8942                                    SmallVectorImpl<int> &Mask,
8943                                    APInt &KnownUndef, APInt &KnownZero,
8944                                    const SelectionDAG &DAG, unsigned Depth,
8945                                    bool ResolveKnownElts) {
8946   if (Depth >= SelectionDAG::MaxRecursionDepth)
8947     return false; // Limit search depth.
8948 
8949   EVT VT = Op.getValueType();
8950   if (!VT.isSimple() || !VT.isVector())
8951     return false;
8952 
8953   if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
8954     if (ResolveKnownElts)
8955       resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
8956     return true;
8957   }
8958   if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
8959                          ResolveKnownElts)) {
8960     resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
8961     return true;
8962   }
8963   return false;
8964 }
8965 
8966 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
8967                                    SmallVectorImpl<SDValue> &Inputs,
8968                                    SmallVectorImpl<int> &Mask,
8969                                    const SelectionDAG &DAG, unsigned Depth,
8970                                    bool ResolveKnownElts) {
8971   APInt KnownUndef, KnownZero;
8972   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
8973                                 KnownZero, DAG, Depth, ResolveKnownElts);
8974 }
8975 
8976 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
8977                                    SmallVectorImpl<int> &Mask,
8978                                    const SelectionDAG &DAG, unsigned Depth = 0,
8979                                    bool ResolveKnownElts = true) {
8980   EVT VT = Op.getValueType();
8981   if (!VT.isSimple() || !VT.isVector())
8982     return false;
8983 
8984   unsigned NumElts = Op.getValueType().getVectorNumElements();
8985   APInt DemandedElts = APInt::getAllOnes(NumElts);
8986   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, DAG, Depth,
8987                                 ResolveKnownElts);
8988 }
8989 
8990 // Attempt to create a scalar/subvector broadcast from the base MemSDNode.
8991 static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
8992                                  EVT MemVT, MemSDNode *Mem, unsigned Offset,
8993                                  SelectionDAG &DAG) {
8994   assert((Opcode == X86ISD::VBROADCAST_LOAD ||
8995           Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
8996          "Unknown broadcast load type");
8997 
8998   // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
8999   if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
9000     return SDValue();
9001 
9002   SDValue Ptr =
9003       DAG.getMemBasePlusOffset(Mem->getBasePtr(), TypeSize::Fixed(Offset), DL);
9004   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9005   SDValue Ops[] = {Mem->getChain(), Ptr};
9006   SDValue BcstLd = DAG.getMemIntrinsicNode(
9007       Opcode, DL, Tys, Ops, MemVT,
9008       DAG.getMachineFunction().getMachineMemOperand(
9009           Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
9010   DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
9011   return BcstLd;
9012 }
9013 
9014 /// Returns the scalar element that will make up the i'th
9015 /// element of the result of the vector shuffle.
9016 static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
9017                                    SelectionDAG &DAG, unsigned Depth) {
9018   if (Depth >= SelectionDAG::MaxRecursionDepth)
9019     return SDValue(); // Limit search depth.
9020 
9021   EVT VT = Op.getValueType();
9022   unsigned Opcode = Op.getOpcode();
9023   unsigned NumElems = VT.getVectorNumElements();
9024 
9025   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
9026   if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
9027     int Elt = SV->getMaskElt(Index);
9028 
9029     if (Elt < 0)
9030       return DAG.getUNDEF(VT.getVectorElementType());
9031 
9032     SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
9033     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
9034   }
9035 
9036   // Recurse into target specific vector shuffles to find scalars.
9037   if (isTargetShuffle(Opcode)) {
9038     MVT ShufVT = VT.getSimpleVT();
9039     MVT ShufSVT = ShufVT.getVectorElementType();
9040     int NumElems = (int)ShufVT.getVectorNumElements();
9041     SmallVector<int, 16> ShuffleMask;
9042     SmallVector<SDValue, 16> ShuffleOps;
9043     if (!getTargetShuffleMask(Op.getNode(), ShufVT, true, ShuffleOps,
9044                               ShuffleMask))
9045       return SDValue();
9046 
9047     int Elt = ShuffleMask[Index];
9048     if (Elt == SM_SentinelZero)
9049       return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
9050                                  : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
9051     if (Elt == SM_SentinelUndef)
9052       return DAG.getUNDEF(ShufSVT);
9053 
9054     assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
9055     SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
9056     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
9057   }
9058 
9059   // Recurse into insert_subvector base/sub vector to find scalars.
9060   if (Opcode == ISD::INSERT_SUBVECTOR) {
9061     SDValue Vec = Op.getOperand(0);
9062     SDValue Sub = Op.getOperand(1);
9063     uint64_t SubIdx = Op.getConstantOperandVal(2);
9064     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
9065 
9066     if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
9067       return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
9068     return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
9069   }
9070 
9071   // Recurse into concat_vectors sub vector to find scalars.
9072   if (Opcode == ISD::CONCAT_VECTORS) {
9073     EVT SubVT = Op.getOperand(0).getValueType();
9074     unsigned NumSubElts = SubVT.getVectorNumElements();
9075     uint64_t SubIdx = Index / NumSubElts;
9076     uint64_t SubElt = Index % NumSubElts;
9077     return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
9078   }
9079 
9080   // Recurse into extract_subvector src vector to find scalars.
9081   if (Opcode == ISD::EXTRACT_SUBVECTOR) {
9082     SDValue Src = Op.getOperand(0);
9083     uint64_t SrcIdx = Op.getConstantOperandVal(1);
9084     return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
9085   }
9086 
9087   // We only peek through bitcasts of the same vector width.
9088   if (Opcode == ISD::BITCAST) {
9089     SDValue Src = Op.getOperand(0);
9090     EVT SrcVT = Src.getValueType();
9091     if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
9092       return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
9093     return SDValue();
9094   }
9095 
9096   // Actual nodes that may contain scalar elements
9097 
9098   // For insert_vector_elt - either return the index matching scalar or recurse
9099   // into the base vector.
9100   if (Opcode == ISD::INSERT_VECTOR_ELT &&
9101       isa<ConstantSDNode>(Op.getOperand(2))) {
9102     if (Op.getConstantOperandAPInt(2) == Index)
9103       return Op.getOperand(1);
9104     return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
9105   }
9106 
9107   if (Opcode == ISD::SCALAR_TO_VECTOR)
9108     return (Index == 0) ? Op.getOperand(0)
9109                         : DAG.getUNDEF(VT.getVectorElementType());
9110 
9111   if (Opcode == ISD::BUILD_VECTOR)
9112     return Op.getOperand(Index);
9113 
9114   return SDValue();
9115 }
9116 
9117 // Use PINSRB/PINSRW/PINSRD to create a build vector.
9118 static SDValue LowerBuildVectorAsInsert(SDValue Op, const APInt &NonZeroMask,
9119                                         unsigned NumNonZero, unsigned NumZero,
9120                                         SelectionDAG &DAG,
9121                                         const X86Subtarget &Subtarget) {
9122   MVT VT = Op.getSimpleValueType();
9123   unsigned NumElts = VT.getVectorNumElements();
9124   assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
9125           ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
9126          "Illegal vector insertion");
9127 
9128   SDLoc dl(Op);
9129   SDValue V;
9130   bool First = true;
9131 
9132   for (unsigned i = 0; i < NumElts; ++i) {
9133     bool IsNonZero = NonZeroMask[i];
9134     if (!IsNonZero)
9135       continue;
9136 
9137     // If the build vector contains zeros or our first insertion is not the
9138     // first index then insert into zero vector to break any register
9139     // dependency else use SCALAR_TO_VECTOR.
9140     if (First) {
9141       First = false;
9142       if (NumZero || 0 != i)
9143         V = getZeroVector(VT, Subtarget, DAG, dl);
9144       else {
9145         assert(0 == i && "Expected insertion into zero-index");
9146         V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
9147         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
9148         V = DAG.getBitcast(VT, V);
9149         continue;
9150       }
9151     }
9152     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
9153                     DAG.getIntPtrConstant(i, dl));
9154   }
9155 
9156   return V;
9157 }
9158 
9159 /// Custom lower build_vector of v16i8.
9160 static SDValue LowerBuildVectorv16i8(SDValue Op, const APInt &NonZeroMask,
9161                                      unsigned NumNonZero, unsigned NumZero,
9162                                      SelectionDAG &DAG,
9163                                      const X86Subtarget &Subtarget) {
9164   if (NumNonZero > 8 && !Subtarget.hasSSE41())
9165     return SDValue();
9166 
9167   // SSE4.1 - use PINSRB to insert each byte directly.
9168   if (Subtarget.hasSSE41())
9169     return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
9170                                     Subtarget);
9171 
9172   SDLoc dl(Op);
9173   SDValue V;
9174 
9175   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
9176   for (unsigned i = 0; i < 16; i += 2) {
9177     bool ThisIsNonZero = NonZeroMask[i];
9178     bool NextIsNonZero = NonZeroMask[i + 1];
9179     if (!ThisIsNonZero && !NextIsNonZero)
9180       continue;
9181 
9182     // FIXME: Investigate combining the first 4 bytes as a i32 instead.
9183     SDValue Elt;
9184     if (ThisIsNonZero) {
9185       if (NumZero || NextIsNonZero)
9186         Elt = DAG.getZExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
9187       else
9188         Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
9189     }
9190 
9191     if (NextIsNonZero) {
9192       SDValue NextElt = Op.getOperand(i + 1);
9193       if (i == 0 && NumZero)
9194         NextElt = DAG.getZExtOrTrunc(NextElt, dl, MVT::i32);
9195       else
9196         NextElt = DAG.getAnyExtOrTrunc(NextElt, dl, MVT::i32);
9197       NextElt = DAG.getNode(ISD::SHL, dl, MVT::i32, NextElt,
9198                             DAG.getConstant(8, dl, MVT::i8));
9199       if (ThisIsNonZero)
9200         Elt = DAG.getNode(ISD::OR, dl, MVT::i32, NextElt, Elt);
9201       else
9202         Elt = NextElt;
9203     }
9204 
9205     // If our first insertion is not the first index or zeros are needed, then
9206     // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
9207     // elements undefined).
9208     if (!V) {
9209       if (i != 0 || NumZero)
9210         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
9211       else {
9212         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Elt);
9213         V = DAG.getBitcast(MVT::v8i16, V);
9214         continue;
9215       }
9216     }
9217     Elt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Elt);
9218     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, Elt,
9219                     DAG.getIntPtrConstant(i / 2, dl));
9220   }
9221 
9222   return DAG.getBitcast(MVT::v16i8, V);
9223 }
9224 
9225 /// Custom lower build_vector of v8i16.
9226 static SDValue LowerBuildVectorv8i16(SDValue Op, const APInt &NonZeroMask,
9227                                      unsigned NumNonZero, unsigned NumZero,
9228                                      SelectionDAG &DAG,
9229                                      const X86Subtarget &Subtarget) {
9230   if (NumNonZero > 4 && !Subtarget.hasSSE41())
9231     return SDValue();
9232 
9233   // Use PINSRW to insert each byte directly.
9234   return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
9235                                   Subtarget);
9236 }
9237 
9238 /// Custom lower build_vector of v4i32 or v4f32.
9239 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
9240                                      const X86Subtarget &Subtarget) {
9241   // If this is a splat of a pair of elements, use MOVDDUP (unless the target
9242   // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
9243   // Because we're creating a less complicated build vector here, we may enable
9244   // further folding of the MOVDDUP via shuffle transforms.
9245   if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
9246       Op.getOperand(0) == Op.getOperand(2) &&
9247       Op.getOperand(1) == Op.getOperand(3) &&
9248       Op.getOperand(0) != Op.getOperand(1)) {
9249     SDLoc DL(Op);
9250     MVT VT = Op.getSimpleValueType();
9251     MVT EltVT = VT.getVectorElementType();
9252     // Create a new build vector with the first 2 elements followed by undef
9253     // padding, bitcast to v2f64, duplicate, and bitcast back.
9254     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
9255                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
9256     SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
9257     SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
9258     return DAG.getBitcast(VT, Dup);
9259   }
9260 
9261   // Find all zeroable elements.
9262   std::bitset<4> Zeroable, Undefs;
9263   for (int i = 0; i < 4; ++i) {
9264     SDValue Elt = Op.getOperand(i);
9265     Undefs[i] = Elt.isUndef();
9266     Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
9267   }
9268   assert(Zeroable.size() - Zeroable.count() > 1 &&
9269          "We expect at least two non-zero elements!");
9270 
9271   // We only know how to deal with build_vector nodes where elements are either
9272   // zeroable or extract_vector_elt with constant index.
9273   SDValue FirstNonZero;
9274   unsigned FirstNonZeroIdx;
9275   for (unsigned i = 0; i < 4; ++i) {
9276     if (Zeroable[i])
9277       continue;
9278     SDValue Elt = Op.getOperand(i);
9279     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9280         !isa<ConstantSDNode>(Elt.getOperand(1)))
9281       return SDValue();
9282     // Make sure that this node is extracting from a 128-bit vector.
9283     MVT VT = Elt.getOperand(0).getSimpleValueType();
9284     if (!VT.is128BitVector())
9285       return SDValue();
9286     if (!FirstNonZero.getNode()) {
9287       FirstNonZero = Elt;
9288       FirstNonZeroIdx = i;
9289     }
9290   }
9291 
9292   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
9293   SDValue V1 = FirstNonZero.getOperand(0);
9294   MVT VT = V1.getSimpleValueType();
9295 
9296   // See if this build_vector can be lowered as a blend with zero.
9297   SDValue Elt;
9298   unsigned EltMaskIdx, EltIdx;
9299   int Mask[4];
9300   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
9301     if (Zeroable[EltIdx]) {
9302       // The zero vector will be on the right hand side.
9303       Mask[EltIdx] = EltIdx+4;
9304       continue;
9305     }
9306 
9307     Elt = Op->getOperand(EltIdx);
9308     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
9309     EltMaskIdx = Elt.getConstantOperandVal(1);
9310     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
9311       break;
9312     Mask[EltIdx] = EltIdx;
9313   }
9314 
9315   if (EltIdx == 4) {
9316     // Let the shuffle legalizer deal with blend operations.
9317     SDValue VZeroOrUndef = (Zeroable == Undefs)
9318                                ? DAG.getUNDEF(VT)
9319                                : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
9320     if (V1.getSimpleValueType() != VT)
9321       V1 = DAG.getBitcast(VT, V1);
9322     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
9323   }
9324 
9325   // See if we can lower this build_vector to a INSERTPS.
9326   if (!Subtarget.hasSSE41())
9327     return SDValue();
9328 
9329   SDValue V2 = Elt.getOperand(0);
9330   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
9331     V1 = SDValue();
9332 
9333   bool CanFold = true;
9334   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
9335     if (Zeroable[i])
9336       continue;
9337 
9338     SDValue Current = Op->getOperand(i);
9339     SDValue SrcVector = Current->getOperand(0);
9340     if (!V1.getNode())
9341       V1 = SrcVector;
9342     CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
9343   }
9344 
9345   if (!CanFold)
9346     return SDValue();
9347 
9348   assert(V1.getNode() && "Expected at least two non-zero elements!");
9349   if (V1.getSimpleValueType() != MVT::v4f32)
9350     V1 = DAG.getBitcast(MVT::v4f32, V1);
9351   if (V2.getSimpleValueType() != MVT::v4f32)
9352     V2 = DAG.getBitcast(MVT::v4f32, V2);
9353 
9354   // Ok, we can emit an INSERTPS instruction.
9355   unsigned ZMask = Zeroable.to_ulong();
9356 
9357   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
9358   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
9359   SDLoc DL(Op);
9360   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
9361                                DAG.getIntPtrConstant(InsertPSMask, DL, true));
9362   return DAG.getBitcast(VT, Result);
9363 }
9364 
9365 /// Return a vector logical shift node.
9366 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
9367                          SelectionDAG &DAG, const TargetLowering &TLI,
9368                          const SDLoc &dl) {
9369   assert(VT.is128BitVector() && "Unknown type for VShift");
9370   MVT ShVT = MVT::v16i8;
9371   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
9372   SrcOp = DAG.getBitcast(ShVT, SrcOp);
9373   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
9374   SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
9375   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
9376 }
9377 
9378 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
9379                                       SelectionDAG &DAG) {
9380 
9381   // Check if the scalar load can be widened into a vector load. And if
9382   // the address is "base + cst" see if the cst can be "absorbed" into
9383   // the shuffle mask.
9384   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
9385     SDValue Ptr = LD->getBasePtr();
9386     if (!ISD::isNormalLoad(LD) || !LD->isSimple())
9387       return SDValue();
9388     EVT PVT = LD->getValueType(0);
9389     if (PVT != MVT::i32 && PVT != MVT::f32)
9390       return SDValue();
9391 
9392     int FI = -1;
9393     int64_t Offset = 0;
9394     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
9395       FI = FINode->getIndex();
9396       Offset = 0;
9397     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
9398                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9399       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9400       Offset = Ptr.getConstantOperandVal(1);
9401       Ptr = Ptr.getOperand(0);
9402     } else {
9403       return SDValue();
9404     }
9405 
9406     // FIXME: 256-bit vector instructions don't require a strict alignment,
9407     // improve this code to support it better.
9408     Align RequiredAlign(VT.getSizeInBits() / 8);
9409     SDValue Chain = LD->getChain();
9410     // Make sure the stack object alignment is at least 16 or 32.
9411     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9412     MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
9413     if (!InferredAlign || *InferredAlign < RequiredAlign) {
9414       if (MFI.isFixedObjectIndex(FI)) {
9415         // Can't change the alignment. FIXME: It's possible to compute
9416         // the exact stack offset and reference FI + adjust offset instead.
9417         // If someone *really* cares about this. That's the way to implement it.
9418         return SDValue();
9419       } else {
9420         MFI.setObjectAlignment(FI, RequiredAlign);
9421       }
9422     }
9423 
9424     // (Offset % 16 or 32) must be multiple of 4. Then address is then
9425     // Ptr + (Offset & ~15).
9426     if (Offset < 0)
9427       return SDValue();
9428     if ((Offset % RequiredAlign.value()) & 3)
9429       return SDValue();
9430     int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
9431     if (StartOffset) {
9432       SDLoc DL(Ptr);
9433       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
9434                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
9435     }
9436 
9437     int EltNo = (Offset - StartOffset) >> 2;
9438     unsigned NumElems = VT.getVectorNumElements();
9439 
9440     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
9441     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
9442                              LD->getPointerInfo().getWithOffset(StartOffset));
9443 
9444     SmallVector<int, 8> Mask(NumElems, EltNo);
9445 
9446     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
9447   }
9448 
9449   return SDValue();
9450 }
9451 
9452 // Recurse to find a LoadSDNode source and the accumulated ByteOffest.
9453 static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
9454   if (ISD::isNON_EXTLoad(Elt.getNode())) {
9455     auto *BaseLd = cast<LoadSDNode>(Elt);
9456     if (!BaseLd->isSimple())
9457       return false;
9458     Ld = BaseLd;
9459     ByteOffset = 0;
9460     return true;
9461   }
9462 
9463   switch (Elt.getOpcode()) {
9464   case ISD::BITCAST:
9465   case ISD::TRUNCATE:
9466   case ISD::SCALAR_TO_VECTOR:
9467     return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
9468   case ISD::SRL:
9469     if (auto *AmtC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
9470       uint64_t Amt = AmtC->getZExtValue();
9471       if ((Amt % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
9472         ByteOffset += Amt / 8;
9473         return true;
9474       }
9475     }
9476     break;
9477   case ISD::EXTRACT_VECTOR_ELT:
9478     if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
9479       SDValue Src = Elt.getOperand(0);
9480       unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
9481       unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
9482       if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
9483           findEltLoadSrc(Src, Ld, ByteOffset)) {
9484         uint64_t Idx = IdxC->getZExtValue();
9485         ByteOffset += Idx * (SrcSizeInBits / 8);
9486         return true;
9487       }
9488     }
9489     break;
9490   }
9491 
9492   return false;
9493 }
9494 
9495 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
9496 /// elements can be replaced by a single large load which has the same value as
9497 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
9498 ///
9499 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
9500 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
9501                                         const SDLoc &DL, SelectionDAG &DAG,
9502                                         const X86Subtarget &Subtarget,
9503                                         bool IsAfterLegalize) {
9504   if ((VT.getScalarSizeInBits() % 8) != 0)
9505     return SDValue();
9506 
9507   unsigned NumElems = Elts.size();
9508 
9509   int LastLoadedElt = -1;
9510   APInt LoadMask = APInt::getZero(NumElems);
9511   APInt ZeroMask = APInt::getZero(NumElems);
9512   APInt UndefMask = APInt::getZero(NumElems);
9513 
9514   SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
9515   SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
9516 
9517   // For each element in the initializer, see if we've found a load, zero or an
9518   // undef.
9519   for (unsigned i = 0; i < NumElems; ++i) {
9520     SDValue Elt = peekThroughBitcasts(Elts[i]);
9521     if (!Elt.getNode())
9522       return SDValue();
9523     if (Elt.isUndef()) {
9524       UndefMask.setBit(i);
9525       continue;
9526     }
9527     if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
9528       ZeroMask.setBit(i);
9529       continue;
9530     }
9531 
9532     // Each loaded element must be the correct fractional portion of the
9533     // requested vector load.
9534     unsigned EltSizeInBits = Elt.getValueSizeInBits();
9535     if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
9536       return SDValue();
9537 
9538     if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
9539       return SDValue();
9540     unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
9541     if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
9542       return SDValue();
9543 
9544     LoadMask.setBit(i);
9545     LastLoadedElt = i;
9546   }
9547   assert((ZeroMask.popcount() + UndefMask.popcount() + LoadMask.popcount()) ==
9548              NumElems &&
9549          "Incomplete element masks");
9550 
9551   // Handle Special Cases - all undef or undef/zero.
9552   if (UndefMask.popcount() == NumElems)
9553     return DAG.getUNDEF(VT);
9554   if ((ZeroMask.popcount() + UndefMask.popcount()) == NumElems)
9555     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
9556                           : DAG.getConstantFP(0.0, DL, VT);
9557 
9558   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9559   int FirstLoadedElt = LoadMask.countr_zero();
9560   SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
9561   EVT EltBaseVT = EltBase.getValueType();
9562   assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
9563          "Register/Memory size mismatch");
9564   LoadSDNode *LDBase = Loads[FirstLoadedElt];
9565   assert(LDBase && "Did not find base load for merging consecutive loads");
9566   unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
9567   unsigned BaseSizeInBytes = BaseSizeInBits / 8;
9568   int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
9569   int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
9570   assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
9571 
9572   // TODO: Support offsetting the base load.
9573   if (ByteOffsets[FirstLoadedElt] != 0)
9574     return SDValue();
9575 
9576   // Check to see if the element's load is consecutive to the base load
9577   // or offset from a previous (already checked) load.
9578   auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
9579     LoadSDNode *Ld = Loads[EltIdx];
9580     int64_t ByteOffset = ByteOffsets[EltIdx];
9581     if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
9582       int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
9583       return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
9584               Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
9585     }
9586     return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
9587                                               EltIdx - FirstLoadedElt);
9588   };
9589 
9590   // Consecutive loads can contain UNDEFS but not ZERO elements.
9591   // Consecutive loads with UNDEFs and ZEROs elements require a
9592   // an additional shuffle stage to clear the ZERO elements.
9593   bool IsConsecutiveLoad = true;
9594   bool IsConsecutiveLoadWithZeros = true;
9595   for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
9596     if (LoadMask[i]) {
9597       if (!CheckConsecutiveLoad(LDBase, i)) {
9598         IsConsecutiveLoad = false;
9599         IsConsecutiveLoadWithZeros = false;
9600         break;
9601       }
9602     } else if (ZeroMask[i]) {
9603       IsConsecutiveLoad = false;
9604     }
9605   }
9606 
9607   auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
9608     auto MMOFlags = LDBase->getMemOperand()->getFlags();
9609     assert(LDBase->isSimple() &&
9610            "Cannot merge volatile or atomic loads.");
9611     SDValue NewLd =
9612         DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
9613                     LDBase->getPointerInfo(), LDBase->getOriginalAlign(),
9614                     MMOFlags);
9615     for (auto *LD : Loads)
9616       if (LD)
9617         DAG.makeEquivalentMemoryOrdering(LD, NewLd);
9618     return NewLd;
9619   };
9620 
9621   // Check if the base load is entirely dereferenceable.
9622   bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
9623       VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
9624 
9625   // LOAD - all consecutive load/undefs (must start/end with a load or be
9626   // entirely dereferenceable). If we have found an entire vector of loads and
9627   // undefs, then return a large load of the entire vector width starting at the
9628   // base pointer. If the vector contains zeros, then attempt to shuffle those
9629   // elements.
9630   if (FirstLoadedElt == 0 &&
9631       (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
9632       (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
9633     if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
9634       return SDValue();
9635 
9636     // Don't create 256-bit non-temporal aligned loads without AVX2 as these
9637     // will lower to regular temporal loads and use the cache.
9638     if (LDBase->isNonTemporal() && LDBase->getAlign() >= Align(32) &&
9639         VT.is256BitVector() && !Subtarget.hasInt256())
9640       return SDValue();
9641 
9642     if (NumElems == 1)
9643       return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
9644 
9645     if (!ZeroMask)
9646       return CreateLoad(VT, LDBase);
9647 
9648     // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
9649     // vector and a zero vector to clear out the zero elements.
9650     if (!IsAfterLegalize && VT.isVector()) {
9651       unsigned NumMaskElts = VT.getVectorNumElements();
9652       if ((NumMaskElts % NumElems) == 0) {
9653         unsigned Scale = NumMaskElts / NumElems;
9654         SmallVector<int, 4> ClearMask(NumMaskElts, -1);
9655         for (unsigned i = 0; i < NumElems; ++i) {
9656           if (UndefMask[i])
9657             continue;
9658           int Offset = ZeroMask[i] ? NumMaskElts : 0;
9659           for (unsigned j = 0; j != Scale; ++j)
9660             ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
9661         }
9662         SDValue V = CreateLoad(VT, LDBase);
9663         SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
9664                                    : DAG.getConstantFP(0.0, DL, VT);
9665         return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
9666       }
9667     }
9668   }
9669 
9670   // If the upper half of a ymm/zmm load is undef then just load the lower half.
9671   if (VT.is256BitVector() || VT.is512BitVector()) {
9672     unsigned HalfNumElems = NumElems / 2;
9673     if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnes()) {
9674       EVT HalfVT =
9675           EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
9676       SDValue HalfLD =
9677           EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
9678                                    DAG, Subtarget, IsAfterLegalize);
9679       if (HalfLD)
9680         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
9681                            HalfLD, DAG.getIntPtrConstant(0, DL));
9682     }
9683   }
9684 
9685   // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
9686   if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
9687       ((LoadSizeInBits == 16 && Subtarget.hasFP16()) || LoadSizeInBits == 32 ||
9688        LoadSizeInBits == 64) &&
9689       ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
9690     MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
9691                                       : MVT::getIntegerVT(LoadSizeInBits);
9692     MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
9693     // Allow v4f32 on SSE1 only targets.
9694     // FIXME: Add more isel patterns so we can just use VT directly.
9695     if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
9696       VecVT = MVT::v4f32;
9697     if (TLI.isTypeLegal(VecVT)) {
9698       SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
9699       SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
9700       SDValue ResNode = DAG.getMemIntrinsicNode(
9701           X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
9702           LDBase->getOriginalAlign(), MachineMemOperand::MOLoad);
9703       for (auto *LD : Loads)
9704         if (LD)
9705           DAG.makeEquivalentMemoryOrdering(LD, ResNode);
9706       return DAG.getBitcast(VT, ResNode);
9707     }
9708   }
9709 
9710   // BROADCAST - match the smallest possible repetition pattern, load that
9711   // scalar/subvector element and then broadcast to the entire vector.
9712   if (ZeroMask.isZero() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
9713       (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
9714     for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
9715       unsigned RepeatSize = SubElems * BaseSizeInBits;
9716       unsigned ScalarSize = std::min(RepeatSize, 64u);
9717       if (!Subtarget.hasAVX2() && ScalarSize < 32)
9718         continue;
9719 
9720       // Don't attempt a 1:N subvector broadcast - it should be caught by
9721       // combineConcatVectorOps, else will cause infinite loops.
9722       if (RepeatSize > ScalarSize && SubElems == 1)
9723         continue;
9724 
9725       bool Match = true;
9726       SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
9727       for (unsigned i = 0; i != NumElems && Match; ++i) {
9728         if (!LoadMask[i])
9729           continue;
9730         SDValue Elt = peekThroughBitcasts(Elts[i]);
9731         if (RepeatedLoads[i % SubElems].isUndef())
9732           RepeatedLoads[i % SubElems] = Elt;
9733         else
9734           Match &= (RepeatedLoads[i % SubElems] == Elt);
9735       }
9736 
9737       // We must have loads at both ends of the repetition.
9738       Match &= !RepeatedLoads.front().isUndef();
9739       Match &= !RepeatedLoads.back().isUndef();
9740       if (!Match)
9741         continue;
9742 
9743       EVT RepeatVT =
9744           VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
9745               ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
9746               : EVT::getFloatingPointVT(ScalarSize);
9747       if (RepeatSize > ScalarSize)
9748         RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
9749                                     RepeatSize / ScalarSize);
9750       EVT BroadcastVT =
9751           EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
9752                            VT.getSizeInBits() / ScalarSize);
9753       if (TLI.isTypeLegal(BroadcastVT)) {
9754         if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
9755                 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize)) {
9756           SDValue Broadcast = RepeatLoad;
9757           if (RepeatSize > ScalarSize) {
9758             while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
9759               Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
9760           } else {
9761             if (!Subtarget.hasAVX2() &&
9762                 !X86::mayFoldLoadIntoBroadcastFromMem(
9763                     RepeatLoad, RepeatVT.getScalarType().getSimpleVT(),
9764                     Subtarget,
9765                     /*AssumeSingleUse=*/true))
9766               return SDValue();
9767             Broadcast =
9768                 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
9769           }
9770           return DAG.getBitcast(VT, Broadcast);
9771         }
9772       }
9773     }
9774   }
9775 
9776   return SDValue();
9777 }
9778 
9779 // Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
9780 // load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
9781 // are consecutive, non-overlapping, and in the right order.
9782 static SDValue combineToConsecutiveLoads(EVT VT, SDValue Op, const SDLoc &DL,
9783                                          SelectionDAG &DAG,
9784                                          const X86Subtarget &Subtarget,
9785                                          bool IsAfterLegalize) {
9786   SmallVector<SDValue, 64> Elts;
9787   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9788     if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
9789       Elts.push_back(Elt);
9790       continue;
9791     }
9792     return SDValue();
9793   }
9794   assert(Elts.size() == VT.getVectorNumElements());
9795   return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
9796                                   IsAfterLegalize);
9797 }
9798 
9799 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
9800                                    unsigned SplatBitSize, LLVMContext &C) {
9801   unsigned ScalarSize = VT.getScalarSizeInBits();
9802 
9803   auto getConstantScalar = [&](const APInt &Val) -> Constant * {
9804     if (VT.isFloatingPoint()) {
9805       if (ScalarSize == 16)
9806         return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
9807       if (ScalarSize == 32)
9808         return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
9809       assert(ScalarSize == 64 && "Unsupported floating point scalar size");
9810       return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
9811     }
9812     return Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
9813   };
9814 
9815   if (ScalarSize == SplatBitSize)
9816     return getConstantScalar(SplatValue);
9817 
9818   unsigned NumElm = SplatBitSize / ScalarSize;
9819   SmallVector<Constant *, 32> ConstantVec;
9820   for (unsigned I = 0; I != NumElm; ++I) {
9821     APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * I);
9822     ConstantVec.push_back(getConstantScalar(Val));
9823   }
9824   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
9825 }
9826 
9827 static bool isFoldableUseOfShuffle(SDNode *N) {
9828   for (auto *U : N->uses()) {
9829     unsigned Opc = U->getOpcode();
9830     // VPERMV/VPERMV3 shuffles can never fold their index operands.
9831     if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
9832       return false;
9833     if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
9834       return false;
9835     if (isTargetShuffle(Opc))
9836       return true;
9837     if (Opc == ISD::BITCAST) // Ignore bitcasts
9838       return isFoldableUseOfShuffle(U);
9839     if (N->hasOneUse()) {
9840       // TODO, there may be some general way to know if a SDNode can
9841       // be folded. We now only know whether an MI is foldable.
9842       if (Opc == X86ISD::VPDPBUSD && U->getOperand(2).getNode() != N)
9843         return false;
9844       return true;
9845     }
9846   }
9847   return false;
9848 }
9849 
9850 /// Attempt to use the vbroadcast instruction to generate a splat value
9851 /// from a splat BUILD_VECTOR which uses:
9852 ///  a. A single scalar load, or a constant.
9853 ///  b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
9854 ///
9855 /// The VBROADCAST node is returned when a pattern is found,
9856 /// or SDValue() otherwise.
9857 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
9858                                            const X86Subtarget &Subtarget,
9859                                            SelectionDAG &DAG) {
9860   // VBROADCAST requires AVX.
9861   // TODO: Splats could be generated for non-AVX CPUs using SSE
9862   // instructions, but there's less potential gain for only 128-bit vectors.
9863   if (!Subtarget.hasAVX())
9864     return SDValue();
9865 
9866   MVT VT = BVOp->getSimpleValueType(0);
9867   unsigned NumElts = VT.getVectorNumElements();
9868   SDLoc dl(BVOp);
9869 
9870   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
9871          "Unsupported vector type for broadcast.");
9872 
9873   // See if the build vector is a repeating sequence of scalars (inc. splat).
9874   SDValue Ld;
9875   BitVector UndefElements;
9876   SmallVector<SDValue, 16> Sequence;
9877   if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
9878     assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
9879     if (Sequence.size() == 1)
9880       Ld = Sequence[0];
9881   }
9882 
9883   // Attempt to use VBROADCASTM
9884   // From this pattern:
9885   // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
9886   // b. t1 = (build_vector t0 t0)
9887   //
9888   // Create (VBROADCASTM v2i1 X)
9889   if (!Sequence.empty() && Subtarget.hasCDI()) {
9890     // If not a splat, are the upper sequence values zeroable?
9891     unsigned SeqLen = Sequence.size();
9892     bool UpperZeroOrUndef =
9893         SeqLen == 1 ||
9894         llvm::all_of(ArrayRef(Sequence).drop_front(), [](SDValue V) {
9895           return !V || V.isUndef() || isNullConstant(V);
9896         });
9897     SDValue Op0 = Sequence[0];
9898     if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
9899                              (Op0.getOpcode() == ISD::ZERO_EXTEND &&
9900                               Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
9901       SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
9902                              ? Op0.getOperand(0)
9903                              : Op0.getOperand(0).getOperand(0);
9904       MVT MaskVT = BOperand.getSimpleValueType();
9905       MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
9906       if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) ||  // for broadcastmb2q
9907           (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
9908         MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
9909         if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
9910           unsigned Scale = 512 / VT.getSizeInBits();
9911           BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
9912         }
9913         SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
9914         if (BcstVT.getSizeInBits() != VT.getSizeInBits())
9915           Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
9916         return DAG.getBitcast(VT, Bcst);
9917       }
9918     }
9919   }
9920 
9921   unsigned NumUndefElts = UndefElements.count();
9922   if (!Ld || (NumElts - NumUndefElts) <= 1) {
9923     APInt SplatValue, Undef;
9924     unsigned SplatBitSize;
9925     bool HasUndef;
9926     // Check if this is a repeated constant pattern suitable for broadcasting.
9927     if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
9928         SplatBitSize > VT.getScalarSizeInBits() &&
9929         SplatBitSize < VT.getSizeInBits()) {
9930       // Avoid replacing with broadcast when it's a use of a shuffle
9931       // instruction to preserve the present custom lowering of shuffles.
9932       if (isFoldableUseOfShuffle(BVOp))
9933         return SDValue();
9934       // replace BUILD_VECTOR with broadcast of the repeated constants.
9935       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9936       LLVMContext *Ctx = DAG.getContext();
9937       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
9938       if (SplatBitSize == 32 || SplatBitSize == 64 ||
9939           (SplatBitSize < 32 && Subtarget.hasAVX2())) {
9940         // Load the constant scalar/subvector and broadcast it.
9941         MVT CVT = MVT::getIntegerVT(SplatBitSize);
9942         Constant *C = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
9943         SDValue CP = DAG.getConstantPool(C, PVT);
9944         unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
9945 
9946         Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
9947         SDVTList Tys = DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
9948         SDValue Ops[] = {DAG.getEntryNode(), CP};
9949         MachinePointerInfo MPI =
9950             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9951         SDValue Brdcst =
9952             DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
9953                                     MPI, Alignment, MachineMemOperand::MOLoad);
9954         return DAG.getBitcast(VT, Brdcst);
9955       }
9956       if (SplatBitSize > 64) {
9957         // Load the vector of constants and broadcast it.
9958         Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
9959         SDValue VCP = DAG.getConstantPool(VecC, PVT);
9960         unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
9961         MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
9962         Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
9963         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9964         SDValue Ops[] = {DAG.getEntryNode(), VCP};
9965         MachinePointerInfo MPI =
9966             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9967         return DAG.getMemIntrinsicNode(X86ISD::SUBV_BROADCAST_LOAD, dl, Tys,
9968                                        Ops, VVT, MPI, Alignment,
9969                                        MachineMemOperand::MOLoad);
9970       }
9971     }
9972 
9973     // If we are moving a scalar into a vector (Ld must be set and all elements
9974     // but 1 are undef) and that operation is not obviously supported by
9975     // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
9976     // That's better than general shuffling and may eliminate a load to GPR and
9977     // move from scalar to vector register.
9978     if (!Ld || NumElts - NumUndefElts != 1)
9979       return SDValue();
9980     unsigned ScalarSize = Ld.getValueSizeInBits();
9981     if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
9982       return SDValue();
9983   }
9984 
9985   bool ConstSplatVal =
9986       (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
9987   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
9988 
9989   // TODO: Handle broadcasts of non-constant sequences.
9990 
9991   // Make sure that all of the users of a non-constant load are from the
9992   // BUILD_VECTOR node.
9993   // FIXME: Is the use count needed for non-constant, non-load case?
9994   if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
9995     return SDValue();
9996 
9997   unsigned ScalarSize = Ld.getValueSizeInBits();
9998   bool IsGE256 = (VT.getSizeInBits() >= 256);
9999 
10000   // When optimizing for size, generate up to 5 extra bytes for a broadcast
10001   // instruction to save 8 or more bytes of constant pool data.
10002   // TODO: If multiple splats are generated to load the same constant,
10003   // it may be detrimental to overall size. There needs to be a way to detect
10004   // that condition to know if this is truly a size win.
10005   bool OptForSize = DAG.shouldOptForSize();
10006 
10007   // Handle broadcasting a single constant scalar from the constant pool
10008   // into a vector.
10009   // On Sandybridge (no AVX2), it is still better to load a constant vector
10010   // from the constant pool and not to broadcast it from a scalar.
10011   // But override that restriction when optimizing for size.
10012   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
10013   if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
10014     EVT CVT = Ld.getValueType();
10015     assert(!CVT.isVector() && "Must not broadcast a vector type");
10016 
10017     // Splat f16, f32, i32, v4f64, v4i64 in all cases with AVX2.
10018     // For size optimization, also splat v2f64 and v2i64, and for size opt
10019     // with AVX2, also splat i8 and i16.
10020     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
10021     if (ScalarSize == 32 ||
10022         (ScalarSize == 64 && (IsGE256 || Subtarget.hasVLX())) ||
10023         CVT == MVT::f16 ||
10024         (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
10025       const Constant *C = nullptr;
10026       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
10027         C = CI->getConstantIntValue();
10028       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
10029         C = CF->getConstantFPValue();
10030 
10031       assert(C && "Invalid constant type");
10032 
10033       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10034       SDValue CP =
10035           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
10036       Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
10037 
10038       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
10039       SDValue Ops[] = {DAG.getEntryNode(), CP};
10040       MachinePointerInfo MPI =
10041           MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
10042       return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
10043                                      MPI, Alignment, MachineMemOperand::MOLoad);
10044     }
10045   }
10046 
10047   // Handle AVX2 in-register broadcasts.
10048   if (!IsLoad && Subtarget.hasInt256() &&
10049       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
10050     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
10051 
10052   // The scalar source must be a normal load.
10053   if (!IsLoad)
10054     return SDValue();
10055 
10056   // Make sure the non-chain result is only used by this build vector.
10057   if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
10058     return SDValue();
10059 
10060   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
10061       (Subtarget.hasVLX() && ScalarSize == 64)) {
10062     auto *LN = cast<LoadSDNode>(Ld);
10063     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
10064     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
10065     SDValue BCast =
10066         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
10067                                 LN->getMemoryVT(), LN->getMemOperand());
10068     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
10069     return BCast;
10070   }
10071 
10072   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
10073   // double since there is no vbroadcastsd xmm
10074   if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
10075       (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
10076     auto *LN = cast<LoadSDNode>(Ld);
10077     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
10078     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
10079     SDValue BCast =
10080         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
10081                                 LN->getMemoryVT(), LN->getMemOperand());
10082     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
10083     return BCast;
10084   }
10085 
10086   if (ScalarSize == 16 && Subtarget.hasFP16() && IsGE256)
10087     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
10088 
10089   // Unsupported broadcast.
10090   return SDValue();
10091 }
10092 
10093 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
10094 /// underlying vector and index.
10095 ///
10096 /// Modifies \p ExtractedFromVec to the real vector and returns the real
10097 /// index.
10098 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
10099                                          SDValue ExtIdx) {
10100   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
10101   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
10102     return Idx;
10103 
10104   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
10105   // lowered this:
10106   //   (extract_vector_elt (v8f32 %1), Constant<6>)
10107   // to:
10108   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
10109   //                           (extract_subvector (v8f32 %0), Constant<4>),
10110   //                           undef)
10111   //                       Constant<0>)
10112   // In this case the vector is the extract_subvector expression and the index
10113   // is 2, as specified by the shuffle.
10114   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
10115   SDValue ShuffleVec = SVOp->getOperand(0);
10116   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
10117   assert(ShuffleVecVT.getVectorElementType() ==
10118          ExtractedFromVec.getSimpleValueType().getVectorElementType());
10119 
10120   int ShuffleIdx = SVOp->getMaskElt(Idx);
10121   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
10122     ExtractedFromVec = ShuffleVec;
10123     return ShuffleIdx;
10124   }
10125   return Idx;
10126 }
10127 
10128 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
10129   MVT VT = Op.getSimpleValueType();
10130 
10131   // Skip if insert_vec_elt is not supported.
10132   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10133   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
10134     return SDValue();
10135 
10136   SDLoc DL(Op);
10137   unsigned NumElems = Op.getNumOperands();
10138 
10139   SDValue VecIn1;
10140   SDValue VecIn2;
10141   SmallVector<unsigned, 4> InsertIndices;
10142   SmallVector<int, 8> Mask(NumElems, -1);
10143 
10144   for (unsigned i = 0; i != NumElems; ++i) {
10145     unsigned Opc = Op.getOperand(i).getOpcode();
10146 
10147     if (Opc == ISD::UNDEF)
10148       continue;
10149 
10150     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
10151       // Quit if more than 1 elements need inserting.
10152       if (InsertIndices.size() > 1)
10153         return SDValue();
10154 
10155       InsertIndices.push_back(i);
10156       continue;
10157     }
10158 
10159     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
10160     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
10161 
10162     // Quit if non-constant index.
10163     if (!isa<ConstantSDNode>(ExtIdx))
10164       return SDValue();
10165     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
10166 
10167     // Quit if extracted from vector of different type.
10168     if (ExtractedFromVec.getValueType() != VT)
10169       return SDValue();
10170 
10171     if (!VecIn1.getNode())
10172       VecIn1 = ExtractedFromVec;
10173     else if (VecIn1 != ExtractedFromVec) {
10174       if (!VecIn2.getNode())
10175         VecIn2 = ExtractedFromVec;
10176       else if (VecIn2 != ExtractedFromVec)
10177         // Quit if more than 2 vectors to shuffle
10178         return SDValue();
10179     }
10180 
10181     if (ExtractedFromVec == VecIn1)
10182       Mask[i] = Idx;
10183     else if (ExtractedFromVec == VecIn2)
10184       Mask[i] = Idx + NumElems;
10185   }
10186 
10187   if (!VecIn1.getNode())
10188     return SDValue();
10189 
10190   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10191   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
10192 
10193   for (unsigned Idx : InsertIndices)
10194     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
10195                      DAG.getIntPtrConstant(Idx, DL));
10196 
10197   return NV;
10198 }
10199 
10200 // Lower BUILD_VECTOR operation for v8bf16, v16bf16 and v32bf16 types.
10201 static SDValue LowerBUILD_VECTORvXbf16(SDValue Op, SelectionDAG &DAG,
10202                                        const X86Subtarget &Subtarget) {
10203   MVT VT = Op.getSimpleValueType();
10204   MVT IVT = VT.changeVectorElementTypeToInteger();
10205   SmallVector<SDValue, 16> NewOps;
10206   for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I)
10207     NewOps.push_back(DAG.getBitcast(MVT::i16, Op.getOperand(I)));
10208   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(), IVT, NewOps);
10209   return DAG.getBitcast(VT, Res);
10210 }
10211 
10212 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
10213 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
10214                                      const X86Subtarget &Subtarget) {
10215 
10216   MVT VT = Op.getSimpleValueType();
10217   assert((VT.getVectorElementType() == MVT::i1) &&
10218          "Unexpected type in LowerBUILD_VECTORvXi1!");
10219 
10220   SDLoc dl(Op);
10221   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
10222       ISD::isBuildVectorAllOnes(Op.getNode()))
10223     return Op;
10224 
10225   uint64_t Immediate = 0;
10226   SmallVector<unsigned, 16> NonConstIdx;
10227   bool IsSplat = true;
10228   bool HasConstElts = false;
10229   int SplatIdx = -1;
10230   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
10231     SDValue In = Op.getOperand(idx);
10232     if (In.isUndef())
10233       continue;
10234     if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
10235       Immediate |= (InC->getZExtValue() & 0x1) << idx;
10236       HasConstElts = true;
10237     } else {
10238       NonConstIdx.push_back(idx);
10239     }
10240     if (SplatIdx < 0)
10241       SplatIdx = idx;
10242     else if (In != Op.getOperand(SplatIdx))
10243       IsSplat = false;
10244   }
10245 
10246   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
10247   if (IsSplat) {
10248     // The build_vector allows the scalar element to be larger than the vector
10249     // element type. We need to mask it to use as a condition unless we know
10250     // the upper bits are zero.
10251     // FIXME: Use computeKnownBits instead of checking specific opcode?
10252     SDValue Cond = Op.getOperand(SplatIdx);
10253     assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
10254     if (Cond.getOpcode() != ISD::SETCC)
10255       Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
10256                          DAG.getConstant(1, dl, MVT::i8));
10257 
10258     // Perform the select in the scalar domain so we can use cmov.
10259     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
10260       SDValue Select = DAG.getSelect(dl, MVT::i32, Cond,
10261                                      DAG.getAllOnesConstant(dl, MVT::i32),
10262                                      DAG.getConstant(0, dl, MVT::i32));
10263       Select = DAG.getBitcast(MVT::v32i1, Select);
10264       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Select, Select);
10265     } else {
10266       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
10267       SDValue Select = DAG.getSelect(dl, ImmVT, Cond,
10268                                      DAG.getAllOnesConstant(dl, ImmVT),
10269                                      DAG.getConstant(0, dl, ImmVT));
10270       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
10271       Select = DAG.getBitcast(VecVT, Select);
10272       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
10273                          DAG.getIntPtrConstant(0, dl));
10274     }
10275   }
10276 
10277   // insert elements one by one
10278   SDValue DstVec;
10279   if (HasConstElts) {
10280     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
10281       SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
10282       SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
10283       ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
10284       ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
10285       DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
10286     } else {
10287       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
10288       SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
10289       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
10290       DstVec = DAG.getBitcast(VecVT, Imm);
10291       DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
10292                            DAG.getIntPtrConstant(0, dl));
10293     }
10294   } else
10295     DstVec = DAG.getUNDEF(VT);
10296 
10297   for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
10298     unsigned InsertIdx = NonConstIdx[i];
10299     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
10300                          Op.getOperand(InsertIdx),
10301                          DAG.getIntPtrConstant(InsertIdx, dl));
10302   }
10303   return DstVec;
10304 }
10305 
10306 LLVM_ATTRIBUTE_UNUSED static bool isHorizOp(unsigned Opcode) {
10307   switch (Opcode) {
10308   case X86ISD::PACKSS:
10309   case X86ISD::PACKUS:
10310   case X86ISD::FHADD:
10311   case X86ISD::FHSUB:
10312   case X86ISD::HADD:
10313   case X86ISD::HSUB:
10314     return true;
10315   }
10316   return false;
10317 }
10318 
10319 /// This is a helper function of LowerToHorizontalOp().
10320 /// This function checks that the build_vector \p N in input implements a
10321 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
10322 /// may not match the layout of an x86 256-bit horizontal instruction.
10323 /// In other words, if this returns true, then some extraction/insertion will
10324 /// be required to produce a valid horizontal instruction.
10325 ///
10326 /// Parameter \p Opcode defines the kind of horizontal operation to match.
10327 /// For example, if \p Opcode is equal to ISD::ADD, then this function
10328 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
10329 /// is equal to ISD::SUB, then this function checks if this is a horizontal
10330 /// arithmetic sub.
10331 ///
10332 /// This function only analyzes elements of \p N whose indices are
10333 /// in range [BaseIdx, LastIdx).
10334 ///
10335 /// TODO: This function was originally used to match both real and fake partial
10336 /// horizontal operations, but the index-matching logic is incorrect for that.
10337 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
10338 /// code because it is only used for partial h-op matching now?
10339 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
10340                                   SelectionDAG &DAG,
10341                                   unsigned BaseIdx, unsigned LastIdx,
10342                                   SDValue &V0, SDValue &V1) {
10343   EVT VT = N->getValueType(0);
10344   assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
10345   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
10346   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
10347          "Invalid Vector in input!");
10348 
10349   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
10350   bool CanFold = true;
10351   unsigned ExpectedVExtractIdx = BaseIdx;
10352   unsigned NumElts = LastIdx - BaseIdx;
10353   V0 = DAG.getUNDEF(VT);
10354   V1 = DAG.getUNDEF(VT);
10355 
10356   // Check if N implements a horizontal binop.
10357   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
10358     SDValue Op = N->getOperand(i + BaseIdx);
10359 
10360     // Skip UNDEFs.
10361     if (Op->isUndef()) {
10362       // Update the expected vector extract index.
10363       if (i * 2 == NumElts)
10364         ExpectedVExtractIdx = BaseIdx;
10365       ExpectedVExtractIdx += 2;
10366       continue;
10367     }
10368 
10369     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
10370 
10371     if (!CanFold)
10372       break;
10373 
10374     SDValue Op0 = Op.getOperand(0);
10375     SDValue Op1 = Op.getOperand(1);
10376 
10377     // Try to match the following pattern:
10378     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
10379     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10380         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10381         Op0.getOperand(0) == Op1.getOperand(0) &&
10382         isa<ConstantSDNode>(Op0.getOperand(1)) &&
10383         isa<ConstantSDNode>(Op1.getOperand(1)));
10384     if (!CanFold)
10385       break;
10386 
10387     unsigned I0 = Op0.getConstantOperandVal(1);
10388     unsigned I1 = Op1.getConstantOperandVal(1);
10389 
10390     if (i * 2 < NumElts) {
10391       if (V0.isUndef()) {
10392         V0 = Op0.getOperand(0);
10393         if (V0.getValueType() != VT)
10394           return false;
10395       }
10396     } else {
10397       if (V1.isUndef()) {
10398         V1 = Op0.getOperand(0);
10399         if (V1.getValueType() != VT)
10400           return false;
10401       }
10402       if (i * 2 == NumElts)
10403         ExpectedVExtractIdx = BaseIdx;
10404     }
10405 
10406     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
10407     if (I0 == ExpectedVExtractIdx)
10408       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
10409     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
10410       // Try to match the following dag sequence:
10411       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
10412       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
10413     } else
10414       CanFold = false;
10415 
10416     ExpectedVExtractIdx += 2;
10417   }
10418 
10419   return CanFold;
10420 }
10421 
10422 /// Emit a sequence of two 128-bit horizontal add/sub followed by
10423 /// a concat_vector.
10424 ///
10425 /// This is a helper function of LowerToHorizontalOp().
10426 /// This function expects two 256-bit vectors called V0 and V1.
10427 /// At first, each vector is split into two separate 128-bit vectors.
10428 /// Then, the resulting 128-bit vectors are used to implement two
10429 /// horizontal binary operations.
10430 ///
10431 /// The kind of horizontal binary operation is defined by \p X86Opcode.
10432 ///
10433 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
10434 /// the two new horizontal binop.
10435 /// When Mode is set, the first horizontal binop dag node would take as input
10436 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
10437 /// horizontal binop dag node would take as input the lower 128-bit of V1
10438 /// and the upper 128-bit of V1.
10439 ///   Example:
10440 ///     HADD V0_LO, V0_HI
10441 ///     HADD V1_LO, V1_HI
10442 ///
10443 /// Otherwise, the first horizontal binop dag node takes as input the lower
10444 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
10445 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
10446 ///   Example:
10447 ///     HADD V0_LO, V1_LO
10448 ///     HADD V0_HI, V1_HI
10449 ///
10450 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
10451 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
10452 /// the upper 128-bits of the result.
10453 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
10454                                      const SDLoc &DL, SelectionDAG &DAG,
10455                                      unsigned X86Opcode, bool Mode,
10456                                      bool isUndefLO, bool isUndefHI) {
10457   MVT VT = V0.getSimpleValueType();
10458   assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
10459          "Invalid nodes in input!");
10460 
10461   unsigned NumElts = VT.getVectorNumElements();
10462   SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
10463   SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
10464   SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
10465   SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
10466   MVT NewVT = V0_LO.getSimpleValueType();
10467 
10468   SDValue LO = DAG.getUNDEF(NewVT);
10469   SDValue HI = DAG.getUNDEF(NewVT);
10470 
10471   if (Mode) {
10472     // Don't emit a horizontal binop if the result is expected to be UNDEF.
10473     if (!isUndefLO && !V0->isUndef())
10474       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
10475     if (!isUndefHI && !V1->isUndef())
10476       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
10477   } else {
10478     // Don't emit a horizontal binop if the result is expected to be UNDEF.
10479     if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
10480       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
10481 
10482     if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
10483       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
10484   }
10485 
10486   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
10487 }
10488 
10489 /// Returns true iff \p BV builds a vector with the result equivalent to
10490 /// the result of ADDSUB/SUBADD operation.
10491 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
10492 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
10493 /// \p Opnd0 and \p Opnd1.
10494 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
10495                              const X86Subtarget &Subtarget, SelectionDAG &DAG,
10496                              SDValue &Opnd0, SDValue &Opnd1,
10497                              unsigned &NumExtracts,
10498                              bool &IsSubAdd) {
10499 
10500   MVT VT = BV->getSimpleValueType(0);
10501   if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
10502     return false;
10503 
10504   unsigned NumElts = VT.getVectorNumElements();
10505   SDValue InVec0 = DAG.getUNDEF(VT);
10506   SDValue InVec1 = DAG.getUNDEF(VT);
10507 
10508   NumExtracts = 0;
10509 
10510   // Odd-numbered elements in the input build vector are obtained from
10511   // adding/subtracting two integer/float elements.
10512   // Even-numbered elements in the input build vector are obtained from
10513   // subtracting/adding two integer/float elements.
10514   unsigned Opc[2] = {0, 0};
10515   for (unsigned i = 0, e = NumElts; i != e; ++i) {
10516     SDValue Op = BV->getOperand(i);
10517 
10518     // Skip 'undef' values.
10519     unsigned Opcode = Op.getOpcode();
10520     if (Opcode == ISD::UNDEF)
10521       continue;
10522 
10523     // Early exit if we found an unexpected opcode.
10524     if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
10525       return false;
10526 
10527     SDValue Op0 = Op.getOperand(0);
10528     SDValue Op1 = Op.getOperand(1);
10529 
10530     // Try to match the following pattern:
10531     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
10532     // Early exit if we cannot match that sequence.
10533     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10534         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10535         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
10536         Op0.getOperand(1) != Op1.getOperand(1))
10537       return false;
10538 
10539     unsigned I0 = Op0.getConstantOperandVal(1);
10540     if (I0 != i)
10541       return false;
10542 
10543     // We found a valid add/sub node, make sure its the same opcode as previous
10544     // elements for this parity.
10545     if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
10546       return false;
10547     Opc[i % 2] = Opcode;
10548 
10549     // Update InVec0 and InVec1.
10550     if (InVec0.isUndef()) {
10551       InVec0 = Op0.getOperand(0);
10552       if (InVec0.getSimpleValueType() != VT)
10553         return false;
10554     }
10555     if (InVec1.isUndef()) {
10556       InVec1 = Op1.getOperand(0);
10557       if (InVec1.getSimpleValueType() != VT)
10558         return false;
10559     }
10560 
10561     // Make sure that operands in input to each add/sub node always
10562     // come from a same pair of vectors.
10563     if (InVec0 != Op0.getOperand(0)) {
10564       if (Opcode == ISD::FSUB)
10565         return false;
10566 
10567       // FADD is commutable. Try to commute the operands
10568       // and then test again.
10569       std::swap(Op0, Op1);
10570       if (InVec0 != Op0.getOperand(0))
10571         return false;
10572     }
10573 
10574     if (InVec1 != Op1.getOperand(0))
10575       return false;
10576 
10577     // Increment the number of extractions done.
10578     ++NumExtracts;
10579   }
10580 
10581   // Ensure we have found an opcode for both parities and that they are
10582   // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
10583   // inputs are undef.
10584   if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
10585       InVec0.isUndef() || InVec1.isUndef())
10586     return false;
10587 
10588   IsSubAdd = Opc[0] == ISD::FADD;
10589 
10590   Opnd0 = InVec0;
10591   Opnd1 = InVec1;
10592   return true;
10593 }
10594 
10595 /// Returns true if is possible to fold MUL and an idiom that has already been
10596 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
10597 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
10598 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
10599 ///
10600 /// Prior to calling this function it should be known that there is some
10601 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
10602 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
10603 /// before replacement of such SDNode with ADDSUB operation. Thus the number
10604 /// of \p Opnd0 uses is expected to be equal to 2.
10605 /// For example, this function may be called for the following IR:
10606 ///    %AB = fmul fast <2 x double> %A, %B
10607 ///    %Sub = fsub fast <2 x double> %AB, %C
10608 ///    %Add = fadd fast <2 x double> %AB, %C
10609 ///    %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
10610 ///                            <2 x i32> <i32 0, i32 3>
10611 /// There is a def for %Addsub here, which potentially can be replaced by
10612 /// X86ISD::ADDSUB operation:
10613 ///    %Addsub = X86ISD::ADDSUB %AB, %C
10614 /// and such ADDSUB can further be replaced with FMADDSUB:
10615 ///    %Addsub = FMADDSUB %A, %B, %C.
10616 ///
10617 /// The main reason why this method is called before the replacement of the
10618 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
10619 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
10620 /// FMADDSUB is.
10621 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
10622                                  SelectionDAG &DAG,
10623                                  SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
10624                                  unsigned ExpectedUses) {
10625   if (Opnd0.getOpcode() != ISD::FMUL ||
10626       !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
10627     return false;
10628 
10629   // FIXME: These checks must match the similar ones in
10630   // DAGCombiner::visitFADDForFMACombine. It would be good to have one
10631   // function that would answer if it is Ok to fuse MUL + ADD to FMADD
10632   // or MUL + ADDSUB to FMADDSUB.
10633   const TargetOptions &Options = DAG.getTarget().Options;
10634   bool AllowFusion =
10635       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
10636   if (!AllowFusion)
10637     return false;
10638 
10639   Opnd2 = Opnd1;
10640   Opnd1 = Opnd0.getOperand(1);
10641   Opnd0 = Opnd0.getOperand(0);
10642 
10643   return true;
10644 }
10645 
10646 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
10647 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
10648 /// X86ISD::FMSUBADD node.
10649 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
10650                                        const X86Subtarget &Subtarget,
10651                                        SelectionDAG &DAG) {
10652   SDValue Opnd0, Opnd1;
10653   unsigned NumExtracts;
10654   bool IsSubAdd;
10655   if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
10656                         IsSubAdd))
10657     return SDValue();
10658 
10659   MVT VT = BV->getSimpleValueType(0);
10660   SDLoc DL(BV);
10661 
10662   // Try to generate X86ISD::FMADDSUB node here.
10663   SDValue Opnd2;
10664   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
10665     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
10666     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
10667   }
10668 
10669   // We only support ADDSUB.
10670   if (IsSubAdd)
10671     return SDValue();
10672 
10673   // There are no known X86 targets with 512-bit ADDSUB instructions!
10674   // Convert to blend(fsub,fadd).
10675   if (VT.is512BitVector()) {
10676     SmallVector<int> Mask;
10677     for (int I = 0, E = VT.getVectorNumElements(); I != E; I += 2) {
10678         Mask.push_back(I);
10679         Mask.push_back(I + E + 1);
10680     }
10681     SDValue Sub = DAG.getNode(ISD::FSUB, DL, VT, Opnd0, Opnd1);
10682     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, Opnd0, Opnd1);
10683     return DAG.getVectorShuffle(VT, DL, Sub, Add, Mask);
10684   }
10685 
10686   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
10687 }
10688 
10689 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
10690                              unsigned &HOpcode, SDValue &V0, SDValue &V1) {
10691   // Initialize outputs to known values.
10692   MVT VT = BV->getSimpleValueType(0);
10693   HOpcode = ISD::DELETED_NODE;
10694   V0 = DAG.getUNDEF(VT);
10695   V1 = DAG.getUNDEF(VT);
10696 
10697   // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
10698   // half of the result is calculated independently from the 128-bit halves of
10699   // the inputs, so that makes the index-checking logic below more complicated.
10700   unsigned NumElts = VT.getVectorNumElements();
10701   unsigned GenericOpcode = ISD::DELETED_NODE;
10702   unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
10703   unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
10704   unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
10705   for (unsigned i = 0; i != Num128BitChunks; ++i) {
10706     for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
10707       // Ignore undef elements.
10708       SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
10709       if (Op.isUndef())
10710         continue;
10711 
10712       // If there's an opcode mismatch, we're done.
10713       if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
10714         return false;
10715 
10716       // Initialize horizontal opcode.
10717       if (HOpcode == ISD::DELETED_NODE) {
10718         GenericOpcode = Op.getOpcode();
10719         switch (GenericOpcode) {
10720         case ISD::ADD: HOpcode = X86ISD::HADD; break;
10721         case ISD::SUB: HOpcode = X86ISD::HSUB; break;
10722         case ISD::FADD: HOpcode = X86ISD::FHADD; break;
10723         case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
10724         default: return false;
10725         }
10726       }
10727 
10728       SDValue Op0 = Op.getOperand(0);
10729       SDValue Op1 = Op.getOperand(1);
10730       if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10731           Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10732           Op0.getOperand(0) != Op1.getOperand(0) ||
10733           !isa<ConstantSDNode>(Op0.getOperand(1)) ||
10734           !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
10735         return false;
10736 
10737       // The source vector is chosen based on which 64-bit half of the
10738       // destination vector is being calculated.
10739       if (j < NumEltsIn64Bits) {
10740         if (V0.isUndef())
10741           V0 = Op0.getOperand(0);
10742       } else {
10743         if (V1.isUndef())
10744           V1 = Op0.getOperand(0);
10745       }
10746 
10747       SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
10748       if (SourceVec != Op0.getOperand(0))
10749         return false;
10750 
10751       // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
10752       unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
10753       unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
10754       unsigned ExpectedIndex = i * NumEltsIn128Bits +
10755                                (j % NumEltsIn64Bits) * 2;
10756       if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
10757         continue;
10758 
10759       // If this is not a commutative op, this does not match.
10760       if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
10761         return false;
10762 
10763       // Addition is commutative, so try swapping the extract indexes.
10764       // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
10765       if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
10766         continue;
10767 
10768       // Extract indexes do not match horizontal requirement.
10769       return false;
10770     }
10771   }
10772   // We matched. Opcode and operands are returned by reference as arguments.
10773   return true;
10774 }
10775 
10776 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
10777                                     SelectionDAG &DAG, unsigned HOpcode,
10778                                     SDValue V0, SDValue V1) {
10779   // If either input vector is not the same size as the build vector,
10780   // extract/insert the low bits to the correct size.
10781   // This is free (examples: zmm --> xmm, xmm --> ymm).
10782   MVT VT = BV->getSimpleValueType(0);
10783   unsigned Width = VT.getSizeInBits();
10784   if (V0.getValueSizeInBits() > Width)
10785     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
10786   else if (V0.getValueSizeInBits() < Width)
10787     V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
10788 
10789   if (V1.getValueSizeInBits() > Width)
10790     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
10791   else if (V1.getValueSizeInBits() < Width)
10792     V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
10793 
10794   unsigned NumElts = VT.getVectorNumElements();
10795   APInt DemandedElts = APInt::getAllOnes(NumElts);
10796   for (unsigned i = 0; i != NumElts; ++i)
10797     if (BV->getOperand(i).isUndef())
10798       DemandedElts.clearBit(i);
10799 
10800   // If we don't need the upper xmm, then perform as a xmm hop.
10801   unsigned HalfNumElts = NumElts / 2;
10802   if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
10803     MVT HalfVT = VT.getHalfNumVectorElementsVT();
10804     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
10805     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
10806     SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
10807     return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
10808   }
10809 
10810   return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
10811 }
10812 
10813 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
10814 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
10815                                    const X86Subtarget &Subtarget,
10816                                    SelectionDAG &DAG) {
10817   // We need at least 2 non-undef elements to make this worthwhile by default.
10818   unsigned NumNonUndefs =
10819       count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
10820   if (NumNonUndefs < 2)
10821     return SDValue();
10822 
10823   // There are 4 sets of horizontal math operations distinguished by type:
10824   // int/FP at 128-bit/256-bit. Each type was introduced with a different
10825   // subtarget feature. Try to match those "native" patterns first.
10826   MVT VT = BV->getSimpleValueType(0);
10827   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
10828       ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
10829       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
10830       ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
10831     unsigned HOpcode;
10832     SDValue V0, V1;
10833     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
10834       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
10835   }
10836 
10837   // Try harder to match 256-bit ops by using extract/concat.
10838   if (!Subtarget.hasAVX() || !VT.is256BitVector())
10839     return SDValue();
10840 
10841   // Count the number of UNDEF operands in the build_vector in input.
10842   unsigned NumElts = VT.getVectorNumElements();
10843   unsigned Half = NumElts / 2;
10844   unsigned NumUndefsLO = 0;
10845   unsigned NumUndefsHI = 0;
10846   for (unsigned i = 0, e = Half; i != e; ++i)
10847     if (BV->getOperand(i)->isUndef())
10848       NumUndefsLO++;
10849 
10850   for (unsigned i = Half, e = NumElts; i != e; ++i)
10851     if (BV->getOperand(i)->isUndef())
10852       NumUndefsHI++;
10853 
10854   SDLoc DL(BV);
10855   SDValue InVec0, InVec1;
10856   if (VT == MVT::v8i32 || VT == MVT::v16i16) {
10857     SDValue InVec2, InVec3;
10858     unsigned X86Opcode;
10859     bool CanFold = true;
10860 
10861     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
10862         isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
10863                               InVec3) &&
10864         ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
10865         ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
10866       X86Opcode = X86ISD::HADD;
10867     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
10868                                    InVec1) &&
10869              isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
10870                                    InVec3) &&
10871              ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
10872              ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
10873       X86Opcode = X86ISD::HSUB;
10874     else
10875       CanFold = false;
10876 
10877     if (CanFold) {
10878       // Do not try to expand this build_vector into a pair of horizontal
10879       // add/sub if we can emit a pair of scalar add/sub.
10880       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
10881         return SDValue();
10882 
10883       // Convert this build_vector into a pair of horizontal binops followed by
10884       // a concat vector. We must adjust the outputs from the partial horizontal
10885       // matching calls above to account for undefined vector halves.
10886       SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
10887       SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
10888       assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
10889       bool isUndefLO = NumUndefsLO == Half;
10890       bool isUndefHI = NumUndefsHI == Half;
10891       return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
10892                                    isUndefHI);
10893     }
10894   }
10895 
10896   if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
10897       VT == MVT::v16i16) {
10898     unsigned X86Opcode;
10899     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
10900       X86Opcode = X86ISD::HADD;
10901     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
10902                                    InVec1))
10903       X86Opcode = X86ISD::HSUB;
10904     else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
10905                                    InVec1))
10906       X86Opcode = X86ISD::FHADD;
10907     else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
10908                                    InVec1))
10909       X86Opcode = X86ISD::FHSUB;
10910     else
10911       return SDValue();
10912 
10913     // Don't try to expand this build_vector into a pair of horizontal add/sub
10914     // if we can simply emit a pair of scalar add/sub.
10915     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
10916       return SDValue();
10917 
10918     // Convert this build_vector into two horizontal add/sub followed by
10919     // a concat vector.
10920     bool isUndefLO = NumUndefsLO == Half;
10921     bool isUndefHI = NumUndefsHI == Half;
10922     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
10923                                  isUndefLO, isUndefHI);
10924   }
10925 
10926   return SDValue();
10927 }
10928 
10929 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
10930                           SelectionDAG &DAG);
10931 
10932 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
10933 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
10934 /// just apply the bit to the vectors.
10935 /// NOTE: Its not in our interest to start make a general purpose vectorizer
10936 /// from this, but enough scalar bit operations are created from the later
10937 /// legalization + scalarization stages to need basic support.
10938 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
10939                                        const X86Subtarget &Subtarget,
10940                                        SelectionDAG &DAG) {
10941   SDLoc DL(Op);
10942   MVT VT = Op->getSimpleValueType(0);
10943   unsigned NumElems = VT.getVectorNumElements();
10944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10945 
10946   // Check that all elements have the same opcode.
10947   // TODO: Should we allow UNDEFS and if so how many?
10948   unsigned Opcode = Op->getOperand(0).getOpcode();
10949   for (unsigned i = 1; i < NumElems; ++i)
10950     if (Opcode != Op->getOperand(i).getOpcode())
10951       return SDValue();
10952 
10953   // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
10954   bool IsShift = false;
10955   switch (Opcode) {
10956   default:
10957     return SDValue();
10958   case ISD::SHL:
10959   case ISD::SRL:
10960   case ISD::SRA:
10961     IsShift = true;
10962     break;
10963   case ISD::AND:
10964   case ISD::XOR:
10965   case ISD::OR:
10966     // Don't do this if the buildvector is a splat - we'd replace one
10967     // constant with an entire vector.
10968     if (Op->getSplatValue())
10969       return SDValue();
10970     if (!TLI.isOperationLegalOrPromote(Opcode, VT))
10971       return SDValue();
10972     break;
10973   }
10974 
10975   SmallVector<SDValue, 4> LHSElts, RHSElts;
10976   for (SDValue Elt : Op->ops()) {
10977     SDValue LHS = Elt.getOperand(0);
10978     SDValue RHS = Elt.getOperand(1);
10979 
10980     // We expect the canonicalized RHS operand to be the constant.
10981     if (!isa<ConstantSDNode>(RHS))
10982       return SDValue();
10983 
10984     // Extend shift amounts.
10985     if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
10986       if (!IsShift)
10987         return SDValue();
10988       RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
10989     }
10990 
10991     LHSElts.push_back(LHS);
10992     RHSElts.push_back(RHS);
10993   }
10994 
10995   // Limit to shifts by uniform immediates.
10996   // TODO: Only accept vXi8/vXi64 special cases?
10997   // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
10998   if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
10999     return SDValue();
11000 
11001   SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
11002   SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
11003   SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
11004 
11005   if (!IsShift)
11006     return Res;
11007 
11008   // Immediately lower the shift to ensure the constant build vector doesn't
11009   // get converted to a constant pool before the shift is lowered.
11010   return LowerShift(Res, Subtarget, DAG);
11011 }
11012 
11013 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
11014 /// functionality to do this, so it's all zeros, all ones, or some derivation
11015 /// that is cheap to calculate.
11016 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
11017                                          const X86Subtarget &Subtarget) {
11018   SDLoc DL(Op);
11019   MVT VT = Op.getSimpleValueType();
11020 
11021   // Vectors containing all zeros can be matched by pxor and xorps.
11022   if (ISD::isBuildVectorAllZeros(Op.getNode()))
11023     return Op;
11024 
11025   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
11026   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
11027   // vpcmpeqd on 256-bit vectors.
11028   if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
11029     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
11030       return Op;
11031 
11032     return getOnesVector(VT, DAG, DL);
11033   }
11034 
11035   return SDValue();
11036 }
11037 
11038 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
11039 /// from a vector of source values and a vector of extraction indices.
11040 /// The vectors might be manipulated to match the type of the permute op.
11041 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
11042                                      SDLoc &DL, SelectionDAG &DAG,
11043                                      const X86Subtarget &Subtarget) {
11044   MVT ShuffleVT = VT;
11045   EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
11046   unsigned NumElts = VT.getVectorNumElements();
11047   unsigned SizeInBits = VT.getSizeInBits();
11048 
11049   // Adjust IndicesVec to match VT size.
11050   assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
11051          "Illegal variable permute mask size");
11052   if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
11053     // Narrow/widen the indices vector to the correct size.
11054     if (IndicesVec.getValueSizeInBits() > SizeInBits)
11055       IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
11056                                     NumElts * VT.getScalarSizeInBits());
11057     else if (IndicesVec.getValueSizeInBits() < SizeInBits)
11058       IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
11059                                   SDLoc(IndicesVec), SizeInBits);
11060     // Zero-extend the index elements within the vector.
11061     if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
11062       IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
11063                                IndicesVT, IndicesVec);
11064   }
11065   IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
11066 
11067   // Handle SrcVec that don't match VT type.
11068   if (SrcVec.getValueSizeInBits() != SizeInBits) {
11069     if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
11070       // Handle larger SrcVec by treating it as a larger permute.
11071       unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
11072       VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
11073       IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
11074       IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
11075                                   Subtarget, DAG, SDLoc(IndicesVec));
11076       SDValue NewSrcVec =
11077           createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
11078       if (NewSrcVec)
11079         return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
11080       return SDValue();
11081     } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
11082       // Widen smaller SrcVec to match VT.
11083       SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
11084     } else
11085       return SDValue();
11086   }
11087 
11088   auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
11089     assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
11090     EVT SrcVT = Idx.getValueType();
11091     unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
11092     uint64_t IndexScale = 0;
11093     uint64_t IndexOffset = 0;
11094 
11095     // If we're scaling a smaller permute op, then we need to repeat the
11096     // indices, scaling and offsetting them as well.
11097     // e.g. v4i32 -> v16i8 (Scale = 4)
11098     // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
11099     // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
11100     for (uint64_t i = 0; i != Scale; ++i) {
11101       IndexScale |= Scale << (i * NumDstBits);
11102       IndexOffset |= i << (i * NumDstBits);
11103     }
11104 
11105     Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
11106                       DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
11107     Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
11108                       DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
11109     return Idx;
11110   };
11111 
11112   unsigned Opcode = 0;
11113   switch (VT.SimpleTy) {
11114   default:
11115     break;
11116   case MVT::v16i8:
11117     if (Subtarget.hasSSSE3())
11118       Opcode = X86ISD::PSHUFB;
11119     break;
11120   case MVT::v8i16:
11121     if (Subtarget.hasVLX() && Subtarget.hasBWI())
11122       Opcode = X86ISD::VPERMV;
11123     else if (Subtarget.hasSSSE3()) {
11124       Opcode = X86ISD::PSHUFB;
11125       ShuffleVT = MVT::v16i8;
11126     }
11127     break;
11128   case MVT::v4f32:
11129   case MVT::v4i32:
11130     if (Subtarget.hasAVX()) {
11131       Opcode = X86ISD::VPERMILPV;
11132       ShuffleVT = MVT::v4f32;
11133     } else if (Subtarget.hasSSSE3()) {
11134       Opcode = X86ISD::PSHUFB;
11135       ShuffleVT = MVT::v16i8;
11136     }
11137     break;
11138   case MVT::v2f64:
11139   case MVT::v2i64:
11140     if (Subtarget.hasAVX()) {
11141       // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
11142       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
11143       Opcode = X86ISD::VPERMILPV;
11144       ShuffleVT = MVT::v2f64;
11145     } else if (Subtarget.hasSSE41()) {
11146       // SSE41 can compare v2i64 - select between indices 0 and 1.
11147       return DAG.getSelectCC(
11148           DL, IndicesVec,
11149           getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
11150           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
11151           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
11152           ISD::CondCode::SETEQ);
11153     }
11154     break;
11155   case MVT::v32i8:
11156     if (Subtarget.hasVLX() && Subtarget.hasVBMI())
11157       Opcode = X86ISD::VPERMV;
11158     else if (Subtarget.hasXOP()) {
11159       SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
11160       SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
11161       SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
11162       SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
11163       return DAG.getNode(
11164           ISD::CONCAT_VECTORS, DL, VT,
11165           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
11166           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
11167     } else if (Subtarget.hasAVX()) {
11168       SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
11169       SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
11170       SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
11171       SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
11172       auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
11173                               ArrayRef<SDValue> Ops) {
11174         // Permute Lo and Hi and then select based on index range.
11175         // This works as SHUFB uses bits[3:0] to permute elements and we don't
11176         // care about the bit[7] as its just an index vector.
11177         SDValue Idx = Ops[2];
11178         EVT VT = Idx.getValueType();
11179         return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
11180                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
11181                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
11182                                ISD::CondCode::SETGT);
11183       };
11184       SDValue Ops[] = {LoLo, HiHi, IndicesVec};
11185       return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
11186                               PSHUFBBuilder);
11187     }
11188     break;
11189   case MVT::v16i16:
11190     if (Subtarget.hasVLX() && Subtarget.hasBWI())
11191       Opcode = X86ISD::VPERMV;
11192     else if (Subtarget.hasAVX()) {
11193       // Scale to v32i8 and perform as v32i8.
11194       IndicesVec = ScaleIndices(IndicesVec, 2);
11195       return DAG.getBitcast(
11196           VT, createVariablePermute(
11197                   MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
11198                   DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
11199     }
11200     break;
11201   case MVT::v8f32:
11202   case MVT::v8i32:
11203     if (Subtarget.hasAVX2())
11204       Opcode = X86ISD::VPERMV;
11205     else if (Subtarget.hasAVX()) {
11206       SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
11207       SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
11208                                           {0, 1, 2, 3, 0, 1, 2, 3});
11209       SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
11210                                           {4, 5, 6, 7, 4, 5, 6, 7});
11211       if (Subtarget.hasXOP())
11212         return DAG.getBitcast(
11213             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
11214                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
11215       // Permute Lo and Hi and then select based on index range.
11216       // This works as VPERMILPS only uses index bits[0:1] to permute elements.
11217       SDValue Res = DAG.getSelectCC(
11218           DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
11219           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
11220           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
11221           ISD::CondCode::SETGT);
11222       return DAG.getBitcast(VT, Res);
11223     }
11224     break;
11225   case MVT::v4i64:
11226   case MVT::v4f64:
11227     if (Subtarget.hasAVX512()) {
11228       if (!Subtarget.hasVLX()) {
11229         MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
11230         SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
11231                                 SDLoc(SrcVec));
11232         IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
11233                                     DAG, SDLoc(IndicesVec));
11234         SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
11235                                             DAG, Subtarget);
11236         return extract256BitVector(Res, 0, DAG, DL);
11237       }
11238       Opcode = X86ISD::VPERMV;
11239     } else if (Subtarget.hasAVX()) {
11240       SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
11241       SDValue LoLo =
11242           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
11243       SDValue HiHi =
11244           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
11245       // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
11246       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
11247       if (Subtarget.hasXOP())
11248         return DAG.getBitcast(
11249             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
11250                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
11251       // Permute Lo and Hi and then select based on index range.
11252       // This works as VPERMILPD only uses index bit[1] to permute elements.
11253       SDValue Res = DAG.getSelectCC(
11254           DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
11255           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
11256           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
11257           ISD::CondCode::SETGT);
11258       return DAG.getBitcast(VT, Res);
11259     }
11260     break;
11261   case MVT::v64i8:
11262     if (Subtarget.hasVBMI())
11263       Opcode = X86ISD::VPERMV;
11264     break;
11265   case MVT::v32i16:
11266     if (Subtarget.hasBWI())
11267       Opcode = X86ISD::VPERMV;
11268     break;
11269   case MVT::v16f32:
11270   case MVT::v16i32:
11271   case MVT::v8f64:
11272   case MVT::v8i64:
11273     if (Subtarget.hasAVX512())
11274       Opcode = X86ISD::VPERMV;
11275     break;
11276   }
11277   if (!Opcode)
11278     return SDValue();
11279 
11280   assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
11281          (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
11282          "Illegal variable permute shuffle type");
11283 
11284   uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
11285   if (Scale > 1)
11286     IndicesVec = ScaleIndices(IndicesVec, Scale);
11287 
11288   EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
11289   IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
11290 
11291   SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
11292   SDValue Res = Opcode == X86ISD::VPERMV
11293                     ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
11294                     : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
11295   return DAG.getBitcast(VT, Res);
11296 }
11297 
11298 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
11299 // reasoned to be a permutation of a vector by indices in a non-constant vector.
11300 // (build_vector (extract_elt V, (extract_elt I, 0)),
11301 //               (extract_elt V, (extract_elt I, 1)),
11302 //                    ...
11303 // ->
11304 // (vpermv I, V)
11305 //
11306 // TODO: Handle undefs
11307 // TODO: Utilize pshufb and zero mask blending to support more efficient
11308 // construction of vectors with constant-0 elements.
11309 static SDValue
11310 LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
11311                                    const X86Subtarget &Subtarget) {
11312   SDValue SrcVec, IndicesVec;
11313   // Check for a match of the permute source vector and permute index elements.
11314   // This is done by checking that the i-th build_vector operand is of the form:
11315   // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
11316   for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
11317     SDValue Op = V.getOperand(Idx);
11318     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11319       return SDValue();
11320 
11321     // If this is the first extract encountered in V, set the source vector,
11322     // otherwise verify the extract is from the previously defined source
11323     // vector.
11324     if (!SrcVec)
11325       SrcVec = Op.getOperand(0);
11326     else if (SrcVec != Op.getOperand(0))
11327       return SDValue();
11328     SDValue ExtractedIndex = Op->getOperand(1);
11329     // Peek through extends.
11330     if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
11331         ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
11332       ExtractedIndex = ExtractedIndex.getOperand(0);
11333     if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11334       return SDValue();
11335 
11336     // If this is the first extract from the index vector candidate, set the
11337     // indices vector, otherwise verify the extract is from the previously
11338     // defined indices vector.
11339     if (!IndicesVec)
11340       IndicesVec = ExtractedIndex.getOperand(0);
11341     else if (IndicesVec != ExtractedIndex.getOperand(0))
11342       return SDValue();
11343 
11344     auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
11345     if (!PermIdx || PermIdx->getAPIntValue() != Idx)
11346       return SDValue();
11347   }
11348 
11349   SDLoc DL(V);
11350   MVT VT = V.getSimpleValueType();
11351   return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
11352 }
11353 
11354 SDValue
11355 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
11356   SDLoc dl(Op);
11357 
11358   MVT VT = Op.getSimpleValueType();
11359   MVT EltVT = VT.getVectorElementType();
11360   MVT OpEltVT = Op.getOperand(0).getSimpleValueType();
11361   unsigned NumElems = Op.getNumOperands();
11362 
11363   // Generate vectors for predicate vectors.
11364   if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
11365     return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
11366 
11367   if (VT.getVectorElementType() == MVT::bf16 &&
11368       (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16()))
11369     return LowerBUILD_VECTORvXbf16(Op, DAG, Subtarget);
11370 
11371   if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
11372     return VectorConstant;
11373 
11374   unsigned EVTBits = EltVT.getSizeInBits();
11375   APInt UndefMask = APInt::getZero(NumElems);
11376   APInt FrozenUndefMask = APInt::getZero(NumElems);
11377   APInt ZeroMask = APInt::getZero(NumElems);
11378   APInt NonZeroMask = APInt::getZero(NumElems);
11379   bool IsAllConstants = true;
11380   bool OneUseFrozenUndefs = true;
11381   SmallSet<SDValue, 8> Values;
11382   unsigned NumConstants = NumElems;
11383   for (unsigned i = 0; i < NumElems; ++i) {
11384     SDValue Elt = Op.getOperand(i);
11385     if (Elt.isUndef()) {
11386       UndefMask.setBit(i);
11387       continue;
11388     }
11389     if (ISD::isFreezeUndef(Elt.getNode())) {
11390       OneUseFrozenUndefs = OneUseFrozenUndefs && Elt->hasOneUse();
11391       FrozenUndefMask.setBit(i);
11392       continue;
11393     }
11394     Values.insert(Elt);
11395     if (!isIntOrFPConstant(Elt)) {
11396       IsAllConstants = false;
11397       NumConstants--;
11398     }
11399     if (X86::isZeroNode(Elt)) {
11400       ZeroMask.setBit(i);
11401     } else {
11402       NonZeroMask.setBit(i);
11403     }
11404   }
11405 
11406   // All undef vector. Return an UNDEF.
11407   if (UndefMask.isAllOnes())
11408     return DAG.getUNDEF(VT);
11409 
11410   // All undef/freeze(undef) vector. Return a FREEZE UNDEF.
11411   if (OneUseFrozenUndefs && (UndefMask | FrozenUndefMask).isAllOnes())
11412     return DAG.getFreeze(DAG.getUNDEF(VT));
11413 
11414   // All undef/freeze(undef)/zero vector. Return a zero vector.
11415   if ((UndefMask | FrozenUndefMask | ZeroMask).isAllOnes())
11416     return getZeroVector(VT, Subtarget, DAG, dl);
11417 
11418   // If we have multiple FREEZE-UNDEF operands, we are likely going to end up
11419   // lowering into a suboptimal insertion sequence. Instead, thaw the UNDEF in
11420   // our source BUILD_VECTOR, create another FREEZE-UNDEF splat BUILD_VECTOR,
11421   // and blend the FREEZE-UNDEF operands back in.
11422   // FIXME: is this worthwhile even for a single FREEZE-UNDEF operand?
11423   if (unsigned NumFrozenUndefElts = FrozenUndefMask.popcount();
11424       NumFrozenUndefElts >= 2 && NumFrozenUndefElts < NumElems) {
11425     SmallVector<int, 16> BlendMask(NumElems, -1);
11426     SmallVector<SDValue, 16> Elts(NumElems, DAG.getUNDEF(OpEltVT));
11427     for (unsigned i = 0; i < NumElems; ++i) {
11428       if (UndefMask[i]) {
11429         BlendMask[i] = -1;
11430         continue;
11431       }
11432       BlendMask[i] = i;
11433       if (!FrozenUndefMask[i])
11434         Elts[i] = Op.getOperand(i);
11435       else
11436         BlendMask[i] += NumElems;
11437     }
11438     SDValue EltsBV = DAG.getBuildVector(VT, dl, Elts);
11439     SDValue FrozenUndefElt = DAG.getFreeze(DAG.getUNDEF(OpEltVT));
11440     SDValue FrozenUndefBV = DAG.getSplatBuildVector(VT, dl, FrozenUndefElt);
11441     return DAG.getVectorShuffle(VT, dl, EltsBV, FrozenUndefBV, BlendMask);
11442   }
11443 
11444   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
11445 
11446   // If the upper elts of a ymm/zmm are undef/freeze(undef)/zero then we might
11447   // be better off lowering to a smaller build vector and padding with
11448   // undef/zero.
11449   if ((VT.is256BitVector() || VT.is512BitVector()) &&
11450       !isFoldableUseOfShuffle(BV)) {
11451     unsigned UpperElems = NumElems / 2;
11452     APInt UndefOrZeroMask = FrozenUndefMask | UndefMask | ZeroMask;
11453     unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countl_one();
11454     if (NumUpperUndefsOrZeros >= UpperElems) {
11455       if (VT.is512BitVector() &&
11456           NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
11457         UpperElems = NumElems - (NumElems / 4);
11458       // If freeze(undef) is in any upper elements, force to zero.
11459       bool UndefUpper = UndefMask.countl_one() >= UpperElems;
11460       MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
11461       SDValue NewBV =
11462           DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
11463       return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
11464     }
11465   }
11466 
11467   if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
11468     return AddSub;
11469   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
11470     return HorizontalOp;
11471   if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
11472     return Broadcast;
11473   if (SDValue BitOp = lowerBuildVectorToBitOp(BV, Subtarget, DAG))
11474     return BitOp;
11475 
11476   unsigned NumZero = ZeroMask.popcount();
11477   unsigned NumNonZero = NonZeroMask.popcount();
11478 
11479   // If we are inserting one variable into a vector of non-zero constants, try
11480   // to avoid loading each constant element as a scalar. Load the constants as a
11481   // vector and then insert the variable scalar element. If insertion is not
11482   // supported, fall back to a shuffle to get the scalar blended with the
11483   // constants. Insertion into a zero vector is handled as a special-case
11484   // somewhere below here.
11485   if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
11486       (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
11487        isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
11488     // Create an all-constant vector. The variable element in the old
11489     // build vector is replaced by undef in the constant vector. Save the
11490     // variable scalar element and its index for use in the insertelement.
11491     LLVMContext &Context = *DAG.getContext();
11492     Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
11493     SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
11494     SDValue VarElt;
11495     SDValue InsIndex;
11496     for (unsigned i = 0; i != NumElems; ++i) {
11497       SDValue Elt = Op.getOperand(i);
11498       if (auto *C = dyn_cast<ConstantSDNode>(Elt))
11499         ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
11500       else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
11501         ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
11502       else if (!Elt.isUndef()) {
11503         assert(!VarElt.getNode() && !InsIndex.getNode() &&
11504                "Expected one variable element in this vector");
11505         VarElt = Elt;
11506         InsIndex = DAG.getVectorIdxConstant(i, dl);
11507       }
11508     }
11509     Constant *CV = ConstantVector::get(ConstVecOps);
11510     SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
11511 
11512     // The constants we just created may not be legal (eg, floating point). We
11513     // must lower the vector right here because we can not guarantee that we'll
11514     // legalize it before loading it. This is also why we could not just create
11515     // a new build vector here. If the build vector contains illegal constants,
11516     // it could get split back up into a series of insert elements.
11517     // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
11518     SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
11519     MachineFunction &MF = DAG.getMachineFunction();
11520     MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
11521     SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
11522     unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
11523     unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
11524     if (InsertC < NumEltsInLow128Bits)
11525       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
11526 
11527     // There's no good way to insert into the high elements of a >128-bit
11528     // vector, so use shuffles to avoid an extract/insert sequence.
11529     assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
11530     assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
11531     SmallVector<int, 8> ShuffleMask;
11532     unsigned NumElts = VT.getVectorNumElements();
11533     for (unsigned i = 0; i != NumElts; ++i)
11534       ShuffleMask.push_back(i == InsertC ? NumElts : i);
11535     SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
11536     return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
11537   }
11538 
11539   // Special case for single non-zero, non-undef, element.
11540   if (NumNonZero == 1) {
11541     unsigned Idx = NonZeroMask.countr_zero();
11542     SDValue Item = Op.getOperand(Idx);
11543 
11544     // If we have a constant or non-constant insertion into the low element of
11545     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
11546     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
11547     // depending on what the source datatype is.
11548     if (Idx == 0) {
11549       if (NumZero == 0)
11550         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
11551 
11552       if (EltVT == MVT::i32 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
11553           EltVT == MVT::f64 || (EltVT == MVT::i64 && Subtarget.is64Bit()) ||
11554           (EltVT == MVT::i16 && Subtarget.hasFP16())) {
11555         assert((VT.is128BitVector() || VT.is256BitVector() ||
11556                 VT.is512BitVector()) &&
11557                "Expected an SSE value type!");
11558         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
11559         // Turn it into a MOVL (i.e. movsh, movss, movsd, movw or movd) to a
11560         // zero vector.
11561         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
11562       }
11563 
11564       // We can't directly insert an i8 or i16 into a vector, so zero extend
11565       // it to i32 first.
11566       if (EltVT == MVT::i16 || EltVT == MVT::i8) {
11567         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
11568         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
11569         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
11570         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
11571         return DAG.getBitcast(VT, Item);
11572       }
11573     }
11574 
11575     // Is it a vector logical left shift?
11576     if (NumElems == 2 && Idx == 1 &&
11577         X86::isZeroNode(Op.getOperand(0)) &&
11578         !X86::isZeroNode(Op.getOperand(1))) {
11579       unsigned NumBits = VT.getSizeInBits();
11580       return getVShift(true, VT,
11581                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11582                                    VT, Op.getOperand(1)),
11583                        NumBits/2, DAG, *this, dl);
11584     }
11585 
11586     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
11587       return SDValue();
11588 
11589     // Otherwise, if this is a vector with i32 or f32 elements, and the element
11590     // is a non-constant being inserted into an element other than the low one,
11591     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
11592     // movd/movss) to move this into the low element, then shuffle it into
11593     // place.
11594     if (EVTBits == 32) {
11595       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
11596       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
11597     }
11598   }
11599 
11600   // Splat is obviously ok. Let legalizer expand it to a shuffle.
11601   if (Values.size() == 1) {
11602     if (EVTBits == 32) {
11603       // Instead of a shuffle like this:
11604       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
11605       // Check if it's possible to issue this instead.
11606       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
11607       unsigned Idx = NonZeroMask.countr_zero();
11608       SDValue Item = Op.getOperand(Idx);
11609       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
11610         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
11611     }
11612     return SDValue();
11613   }
11614 
11615   // A vector full of immediates; various special cases are already
11616   // handled, so this is best done with a single constant-pool load.
11617   if (IsAllConstants)
11618     return SDValue();
11619 
11620   if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
11621       return V;
11622 
11623   // See if we can use a vector load to get all of the elements.
11624   {
11625     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
11626     if (SDValue LD =
11627             EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
11628       return LD;
11629   }
11630 
11631   // If this is a splat of pairs of 32-bit elements, we can use a narrower
11632   // build_vector and broadcast it.
11633   // TODO: We could probably generalize this more.
11634   if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
11635     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
11636                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
11637     auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
11638       // Make sure all the even/odd operands match.
11639       for (unsigned i = 2; i != NumElems; ++i)
11640         if (Ops[i % 2] != Op.getOperand(i))
11641           return false;
11642       return true;
11643     };
11644     if (CanSplat(Op, NumElems, Ops)) {
11645       MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
11646       MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
11647       // Create a new build vector and cast to v2i64/v2f64.
11648       SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
11649                                      DAG.getBuildVector(NarrowVT, dl, Ops));
11650       // Broadcast from v2i64/v2f64 and cast to final VT.
11651       MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
11652       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
11653                                             NewBV));
11654     }
11655   }
11656 
11657   // For AVX-length vectors, build the individual 128-bit pieces and use
11658   // shuffles to put them in place.
11659   if (VT.getSizeInBits() > 128) {
11660     MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
11661 
11662     // Build both the lower and upper subvector.
11663     SDValue Lower =
11664         DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
11665     SDValue Upper = DAG.getBuildVector(
11666         HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
11667 
11668     // Recreate the wider vector with the lower and upper part.
11669     return concatSubVectors(Lower, Upper, DAG, dl);
11670   }
11671 
11672   // Let legalizer expand 2-wide build_vectors.
11673   if (EVTBits == 64) {
11674     if (NumNonZero == 1) {
11675       // One half is zero or undef.
11676       unsigned Idx = NonZeroMask.countr_zero();
11677       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
11678                                Op.getOperand(Idx));
11679       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
11680     }
11681     return SDValue();
11682   }
11683 
11684   // If element VT is < 32 bits, convert it to inserts into a zero vector.
11685   if (EVTBits == 8 && NumElems == 16)
11686     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeroMask, NumNonZero, NumZero,
11687                                           DAG, Subtarget))
11688       return V;
11689 
11690   if (EltVT == MVT::i16 && NumElems == 8)
11691     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeroMask, NumNonZero, NumZero,
11692                                           DAG, Subtarget))
11693       return V;
11694 
11695   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
11696   if (EVTBits == 32 && NumElems == 4)
11697     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
11698       return V;
11699 
11700   // If element VT is == 32 bits, turn it into a number of shuffles.
11701   if (NumElems == 4 && NumZero > 0) {
11702     SmallVector<SDValue, 8> Ops(NumElems);
11703     for (unsigned i = 0; i < 4; ++i) {
11704       bool isZero = !NonZeroMask[i];
11705       if (isZero)
11706         Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
11707       else
11708         Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
11709     }
11710 
11711     for (unsigned i = 0; i < 2; ++i) {
11712       switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
11713         default: llvm_unreachable("Unexpected NonZero count");
11714         case 0:
11715           Ops[i] = Ops[i*2];  // Must be a zero vector.
11716           break;
11717         case 1:
11718           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
11719           break;
11720         case 2:
11721           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
11722           break;
11723         case 3:
11724           Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
11725           break;
11726       }
11727     }
11728 
11729     bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
11730     bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
11731     int MaskVec[] = {
11732       Reverse1 ? 1 : 0,
11733       Reverse1 ? 0 : 1,
11734       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
11735       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
11736     };
11737     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
11738   }
11739 
11740   assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
11741 
11742   // Check for a build vector from mostly shuffle plus few inserting.
11743   if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
11744     return Sh;
11745 
11746   // For SSE 4.1, use insertps to put the high elements into the low element.
11747   if (Subtarget.hasSSE41() && EltVT != MVT::f16) {
11748     SDValue Result;
11749     if (!Op.getOperand(0).isUndef())
11750       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
11751     else
11752       Result = DAG.getUNDEF(VT);
11753 
11754     for (unsigned i = 1; i < NumElems; ++i) {
11755       if (Op.getOperand(i).isUndef()) continue;
11756       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
11757                            Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
11758     }
11759     return Result;
11760   }
11761 
11762   // Otherwise, expand into a number of unpckl*, start by extending each of
11763   // our (non-undef) elements to the full vector width with the element in the
11764   // bottom slot of the vector (which generates no code for SSE).
11765   SmallVector<SDValue, 8> Ops(NumElems);
11766   for (unsigned i = 0; i < NumElems; ++i) {
11767     if (!Op.getOperand(i).isUndef())
11768       Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
11769     else
11770       Ops[i] = DAG.getUNDEF(VT);
11771   }
11772 
11773   // Next, we iteratively mix elements, e.g. for v4f32:
11774   //   Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
11775   //         : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
11776   //   Step 2: unpcklpd X, Y ==>    <3, 2, 1, 0>
11777   for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
11778     // Generate scaled UNPCKL shuffle mask.
11779     SmallVector<int, 16> Mask;
11780     for(unsigned i = 0; i != Scale; ++i)
11781       Mask.push_back(i);
11782     for (unsigned i = 0; i != Scale; ++i)
11783       Mask.push_back(NumElems+i);
11784     Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
11785 
11786     for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
11787       Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
11788   }
11789   return Ops[0];
11790 }
11791 
11792 // 256-bit AVX can use the vinsertf128 instruction
11793 // to create 256-bit vectors from two other 128-bit ones.
11794 // TODO: Detect subvector broadcast here instead of DAG combine?
11795 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
11796                                       const X86Subtarget &Subtarget) {
11797   SDLoc dl(Op);
11798   MVT ResVT = Op.getSimpleValueType();
11799 
11800   assert((ResVT.is256BitVector() ||
11801           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
11802 
11803   unsigned NumOperands = Op.getNumOperands();
11804   unsigned NumFreezeUndef = 0;
11805   unsigned NumZero = 0;
11806   unsigned NumNonZero = 0;
11807   unsigned NonZeros = 0;
11808   for (unsigned i = 0; i != NumOperands; ++i) {
11809     SDValue SubVec = Op.getOperand(i);
11810     if (SubVec.isUndef())
11811       continue;
11812     if (ISD::isFreezeUndef(SubVec.getNode())) {
11813         // If the freeze(undef) has multiple uses then we must fold to zero.
11814         if (SubVec.hasOneUse())
11815           ++NumFreezeUndef;
11816         else
11817           ++NumZero;
11818     }
11819     else if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
11820       ++NumZero;
11821     else {
11822       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
11823       NonZeros |= 1 << i;
11824       ++NumNonZero;
11825     }
11826   }
11827 
11828   // If we have more than 2 non-zeros, build each half separately.
11829   if (NumNonZero > 2) {
11830     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
11831     ArrayRef<SDUse> Ops = Op->ops();
11832     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11833                              Ops.slice(0, NumOperands/2));
11834     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11835                              Ops.slice(NumOperands/2));
11836     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
11837   }
11838 
11839   // Otherwise, build it up through insert_subvectors.
11840   SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
11841                         : (NumFreezeUndef ? DAG.getFreeze(DAG.getUNDEF(ResVT))
11842                                           : DAG.getUNDEF(ResVT));
11843 
11844   MVT SubVT = Op.getOperand(0).getSimpleValueType();
11845   unsigned NumSubElems = SubVT.getVectorNumElements();
11846   for (unsigned i = 0; i != NumOperands; ++i) {
11847     if ((NonZeros & (1 << i)) == 0)
11848       continue;
11849 
11850     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
11851                       Op.getOperand(i),
11852                       DAG.getIntPtrConstant(i * NumSubElems, dl));
11853   }
11854 
11855   return Vec;
11856 }
11857 
11858 // Returns true if the given node is a type promotion (by concatenating i1
11859 // zeros) of the result of a node that already zeros all upper bits of
11860 // k-register.
11861 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
11862 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
11863                                        const X86Subtarget &Subtarget,
11864                                        SelectionDAG & DAG) {
11865   SDLoc dl(Op);
11866   MVT ResVT = Op.getSimpleValueType();
11867   unsigned NumOperands = Op.getNumOperands();
11868 
11869   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
11870          "Unexpected number of operands in CONCAT_VECTORS");
11871 
11872   uint64_t Zeros = 0;
11873   uint64_t NonZeros = 0;
11874   for (unsigned i = 0; i != NumOperands; ++i) {
11875     SDValue SubVec = Op.getOperand(i);
11876     if (SubVec.isUndef())
11877       continue;
11878     assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
11879     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
11880       Zeros |= (uint64_t)1 << i;
11881     else
11882       NonZeros |= (uint64_t)1 << i;
11883   }
11884 
11885   unsigned NumElems = ResVT.getVectorNumElements();
11886 
11887   // If we are inserting non-zero vector and there are zeros in LSBs and undef
11888   // in the MSBs we need to emit a KSHIFTL. The generic lowering to
11889   // insert_subvector will give us two kshifts.
11890   if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
11891       Log2_64(NonZeros) != NumOperands - 1) {
11892     MVT ShiftVT = ResVT;
11893     if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
11894       ShiftVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
11895     unsigned Idx = Log2_64(NonZeros);
11896     SDValue SubVec = Op.getOperand(Idx);
11897     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
11898     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ShiftVT,
11899                          DAG.getUNDEF(ShiftVT), SubVec,
11900                          DAG.getIntPtrConstant(0, dl));
11901     Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, SubVec,
11902                      DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
11903     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
11904                        DAG.getIntPtrConstant(0, dl));
11905   }
11906 
11907   // If there are zero or one non-zeros we can handle this very simply.
11908   if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
11909     SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
11910     if (!NonZeros)
11911       return Vec;
11912     unsigned Idx = Log2_64(NonZeros);
11913     SDValue SubVec = Op.getOperand(Idx);
11914     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
11915     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
11916                        DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
11917   }
11918 
11919   if (NumOperands > 2) {
11920     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
11921     ArrayRef<SDUse> Ops = Op->ops();
11922     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11923                              Ops.slice(0, NumOperands/2));
11924     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11925                              Ops.slice(NumOperands/2));
11926     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
11927   }
11928 
11929   assert(llvm::popcount(NonZeros) == 2 && "Simple cases not handled?");
11930 
11931   if (ResVT.getVectorNumElements() >= 16)
11932     return Op; // The operation is legal with KUNPCK
11933 
11934   SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
11935                             DAG.getUNDEF(ResVT), Op.getOperand(0),
11936                             DAG.getIntPtrConstant(0, dl));
11937   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
11938                      DAG.getIntPtrConstant(NumElems/2, dl));
11939 }
11940 
11941 static SDValue LowerCONCAT_VECTORS(SDValue Op,
11942                                    const X86Subtarget &Subtarget,
11943                                    SelectionDAG &DAG) {
11944   MVT VT = Op.getSimpleValueType();
11945   if (VT.getVectorElementType() == MVT::i1)
11946     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
11947 
11948   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
11949          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
11950           Op.getNumOperands() == 4)));
11951 
11952   // AVX can use the vinsertf128 instruction to create 256-bit vectors
11953   // from two other 128-bit ones.
11954 
11955   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
11956   return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
11957 }
11958 
11959 //===----------------------------------------------------------------------===//
11960 // Vector shuffle lowering
11961 //
11962 // This is an experimental code path for lowering vector shuffles on x86. It is
11963 // designed to handle arbitrary vector shuffles and blends, gracefully
11964 // degrading performance as necessary. It works hard to recognize idiomatic
11965 // shuffles and lower them to optimal instruction patterns without leaving
11966 // a framework that allows reasonably efficient handling of all vector shuffle
11967 // patterns.
11968 //===----------------------------------------------------------------------===//
11969 
11970 /// Tiny helper function to identify a no-op mask.
11971 ///
11972 /// This is a somewhat boring predicate function. It checks whether the mask
11973 /// array input, which is assumed to be a single-input shuffle mask of the kind
11974 /// used by the X86 shuffle instructions (not a fully general
11975 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
11976 /// in-place shuffle are 'no-op's.
11977 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
11978   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11979     assert(Mask[i] >= -1 && "Out of bound mask element!");
11980     if (Mask[i] >= 0 && Mask[i] != i)
11981       return false;
11982   }
11983   return true;
11984 }
11985 
11986 /// Test whether there are elements crossing LaneSizeInBits lanes in this
11987 /// shuffle mask.
11988 ///
11989 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
11990 /// and we routinely test for these.
11991 static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
11992                                       unsigned ScalarSizeInBits,
11993                                       ArrayRef<int> Mask) {
11994   assert(LaneSizeInBits && ScalarSizeInBits &&
11995          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
11996          "Illegal shuffle lane size");
11997   int LaneSize = LaneSizeInBits / ScalarSizeInBits;
11998   int Size = Mask.size();
11999   for (int i = 0; i < Size; ++i)
12000     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
12001       return true;
12002   return false;
12003 }
12004 
12005 /// Test whether there are elements crossing 128-bit lanes in this
12006 /// shuffle mask.
12007 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
12008   return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
12009 }
12010 
12011 /// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
12012 /// from multiple lanes - this is different to isLaneCrossingShuffleMask to
12013 /// better support 'repeated mask + lane permute' style shuffles.
12014 static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
12015                                    unsigned ScalarSizeInBits,
12016                                    ArrayRef<int> Mask) {
12017   assert(LaneSizeInBits && ScalarSizeInBits &&
12018          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
12019          "Illegal shuffle lane size");
12020   int NumElts = Mask.size();
12021   int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
12022   int NumLanes = NumElts / NumEltsPerLane;
12023   if (NumLanes > 1) {
12024     for (int i = 0; i != NumLanes; ++i) {
12025       int SrcLane = -1;
12026       for (int j = 0; j != NumEltsPerLane; ++j) {
12027         int M = Mask[(i * NumEltsPerLane) + j];
12028         if (M < 0)
12029           continue;
12030         int Lane = (M % NumElts) / NumEltsPerLane;
12031         if (SrcLane >= 0 && SrcLane != Lane)
12032           return true;
12033         SrcLane = Lane;
12034       }
12035     }
12036   }
12037   return false;
12038 }
12039 
12040 /// Test whether a shuffle mask is equivalent within each sub-lane.
12041 ///
12042 /// This checks a shuffle mask to see if it is performing the same
12043 /// lane-relative shuffle in each sub-lane. This trivially implies
12044 /// that it is also not lane-crossing. It may however involve a blend from the
12045 /// same lane of a second vector.
12046 ///
12047 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
12048 /// non-trivial to compute in the face of undef lanes. The representation is
12049 /// suitable for use with existing 128-bit shuffles as entries from the second
12050 /// vector have been remapped to [LaneSize, 2*LaneSize).
12051 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
12052                                   ArrayRef<int> Mask,
12053                                   SmallVectorImpl<int> &RepeatedMask) {
12054   auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
12055   RepeatedMask.assign(LaneSize, -1);
12056   int Size = Mask.size();
12057   for (int i = 0; i < Size; ++i) {
12058     assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
12059     if (Mask[i] < 0)
12060       continue;
12061     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
12062       // This entry crosses lanes, so there is no way to model this shuffle.
12063       return false;
12064 
12065     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
12066     // Adjust second vector indices to start at LaneSize instead of Size.
12067     int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
12068                                 : Mask[i] % LaneSize + LaneSize;
12069     if (RepeatedMask[i % LaneSize] < 0)
12070       // This is the first non-undef entry in this slot of a 128-bit lane.
12071       RepeatedMask[i % LaneSize] = LocalM;
12072     else if (RepeatedMask[i % LaneSize] != LocalM)
12073       // Found a mismatch with the repeated mask.
12074       return false;
12075   }
12076   return true;
12077 }
12078 
12079 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
12080 static bool
12081 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
12082                                 SmallVectorImpl<int> &RepeatedMask) {
12083   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
12084 }
12085 
12086 static bool
12087 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
12088   SmallVector<int, 32> RepeatedMask;
12089   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
12090 }
12091 
12092 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
12093 static bool
12094 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
12095                                 SmallVectorImpl<int> &RepeatedMask) {
12096   return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
12097 }
12098 
12099 /// Test whether a target shuffle mask is equivalent within each sub-lane.
12100 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
12101 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
12102                                         unsigned EltSizeInBits,
12103                                         ArrayRef<int> Mask,
12104                                         SmallVectorImpl<int> &RepeatedMask) {
12105   int LaneSize = LaneSizeInBits / EltSizeInBits;
12106   RepeatedMask.assign(LaneSize, SM_SentinelUndef);
12107   int Size = Mask.size();
12108   for (int i = 0; i < Size; ++i) {
12109     assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
12110     if (Mask[i] == SM_SentinelUndef)
12111       continue;
12112     if (Mask[i] == SM_SentinelZero) {
12113       if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
12114         return false;
12115       RepeatedMask[i % LaneSize] = SM_SentinelZero;
12116       continue;
12117     }
12118     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
12119       // This entry crosses lanes, so there is no way to model this shuffle.
12120       return false;
12121 
12122     // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
12123     // later vector indices to start at multiples of LaneSize instead of Size.
12124     int LaneM = Mask[i] / Size;
12125     int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
12126     if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
12127       // This is the first non-undef entry in this slot of a 128-bit lane.
12128       RepeatedMask[i % LaneSize] = LocalM;
12129     else if (RepeatedMask[i % LaneSize] != LocalM)
12130       // Found a mismatch with the repeated mask.
12131       return false;
12132   }
12133   return true;
12134 }
12135 
12136 /// Test whether a target shuffle mask is equivalent within each sub-lane.
12137 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
12138 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
12139                                         ArrayRef<int> Mask,
12140                                         SmallVectorImpl<int> &RepeatedMask) {
12141   return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
12142                                      Mask, RepeatedMask);
12143 }
12144 
12145 /// Checks whether the vector elements referenced by two shuffle masks are
12146 /// equivalent.
12147 static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
12148                                 int Idx, int ExpectedIdx) {
12149   assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
12150          ExpectedIdx < MaskSize && "Out of range element index");
12151   if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
12152     return false;
12153 
12154   switch (Op.getOpcode()) {
12155   case ISD::BUILD_VECTOR:
12156     // If the values are build vectors, we can look through them to find
12157     // equivalent inputs that make the shuffles equivalent.
12158     // TODO: Handle MaskSize != Op.getNumOperands()?
12159     if (MaskSize == (int)Op.getNumOperands() &&
12160         MaskSize == (int)ExpectedOp.getNumOperands())
12161       return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
12162     break;
12163   case X86ISD::VBROADCAST:
12164   case X86ISD::VBROADCAST_LOAD:
12165     // TODO: Handle MaskSize != Op.getValueType().getVectorNumElements()?
12166     return (Op == ExpectedOp &&
12167             (int)Op.getValueType().getVectorNumElements() == MaskSize);
12168   case X86ISD::HADD:
12169   case X86ISD::HSUB:
12170   case X86ISD::FHADD:
12171   case X86ISD::FHSUB:
12172   case X86ISD::PACKSS:
12173   case X86ISD::PACKUS:
12174     // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
12175     // TODO: Handle MaskSize != NumElts?
12176     // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
12177     if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
12178       MVT VT = Op.getSimpleValueType();
12179       int NumElts = VT.getVectorNumElements();
12180       if (MaskSize == NumElts) {
12181         int NumLanes = VT.getSizeInBits() / 128;
12182         int NumEltsPerLane = NumElts / NumLanes;
12183         int NumHalfEltsPerLane = NumEltsPerLane / 2;
12184         bool SameLane =
12185             (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
12186         bool SameElt =
12187             (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
12188         return SameLane && SameElt;
12189       }
12190     }
12191     break;
12192   }
12193 
12194   return false;
12195 }
12196 
12197 /// Checks whether a shuffle mask is equivalent to an explicit list of
12198 /// arguments.
12199 ///
12200 /// This is a fast way to test a shuffle mask against a fixed pattern:
12201 ///
12202 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
12203 ///
12204 /// It returns true if the mask is exactly as wide as the argument list, and
12205 /// each element of the mask is either -1 (signifying undef) or the value given
12206 /// in the argument.
12207 static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
12208                                 SDValue V1 = SDValue(),
12209                                 SDValue V2 = SDValue()) {
12210   int Size = Mask.size();
12211   if (Size != (int)ExpectedMask.size())
12212     return false;
12213 
12214   for (int i = 0; i < Size; ++i) {
12215     assert(Mask[i] >= -1 && "Out of bound mask element!");
12216     int MaskIdx = Mask[i];
12217     int ExpectedIdx = ExpectedMask[i];
12218     if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
12219       SDValue MaskV = MaskIdx < Size ? V1 : V2;
12220       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
12221       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
12222       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
12223       if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
12224         return false;
12225     }
12226   }
12227   return true;
12228 }
12229 
12230 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
12231 ///
12232 /// The masks must be exactly the same width.
12233 ///
12234 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
12235 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
12236 ///
12237 /// SM_SentinelZero is accepted as a valid negative index but must match in
12238 /// both, or via a known bits test.
12239 static bool isTargetShuffleEquivalent(MVT VT, ArrayRef<int> Mask,
12240                                       ArrayRef<int> ExpectedMask,
12241                                       const SelectionDAG &DAG,
12242                                       SDValue V1 = SDValue(),
12243                                       SDValue V2 = SDValue()) {
12244   int Size = Mask.size();
12245   if (Size != (int)ExpectedMask.size())
12246     return false;
12247   assert(llvm::all_of(ExpectedMask,
12248                       [Size](int M) { return isInRange(M, 0, 2 * Size); }) &&
12249          "Illegal target shuffle mask");
12250 
12251   // Check for out-of-range target shuffle mask indices.
12252   if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
12253     return false;
12254 
12255   // Don't use V1/V2 if they're not the same size as the shuffle mask type.
12256   if (V1 && (V1.getValueSizeInBits() != VT.getSizeInBits() ||
12257              !V1.getValueType().isVector()))
12258     V1 = SDValue();
12259   if (V2 && (V2.getValueSizeInBits() != VT.getSizeInBits() ||
12260              !V2.getValueType().isVector()))
12261     V2 = SDValue();
12262 
12263   APInt ZeroV1 = APInt::getZero(Size);
12264   APInt ZeroV2 = APInt::getZero(Size);
12265 
12266   for (int i = 0; i < Size; ++i) {
12267     int MaskIdx = Mask[i];
12268     int ExpectedIdx = ExpectedMask[i];
12269     if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
12270       continue;
12271     if (MaskIdx == SM_SentinelZero) {
12272       // If we need this expected index to be a zero element, then update the
12273       // relevant zero mask and perform the known bits at the end to minimize
12274       // repeated computes.
12275       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
12276       if (ExpectedV &&
12277           Size == (int)ExpectedV.getValueType().getVectorNumElements()) {
12278         int BitIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
12279         APInt &ZeroMask = ExpectedIdx < Size ? ZeroV1 : ZeroV2;
12280         ZeroMask.setBit(BitIdx);
12281         continue;
12282       }
12283     }
12284     if (MaskIdx >= 0) {
12285       SDValue MaskV = MaskIdx < Size ? V1 : V2;
12286       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
12287       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
12288       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
12289       if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
12290         continue;
12291     }
12292     return false;
12293   }
12294   return (ZeroV1.isZero() || DAG.MaskedVectorIsZero(V1, ZeroV1)) &&
12295          (ZeroV2.isZero() || DAG.MaskedVectorIsZero(V2, ZeroV2));
12296 }
12297 
12298 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
12299 // instructions.
12300 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT,
12301                                   const SelectionDAG &DAG) {
12302   if (VT != MVT::v8i32 && VT != MVT::v8f32)
12303     return false;
12304 
12305   SmallVector<int, 8> Unpcklwd;
12306   createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
12307                           /* Unary = */ false);
12308   SmallVector<int, 8> Unpckhwd;
12309   createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
12310                           /* Unary = */ false);
12311   bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd, DAG) ||
12312                          isTargetShuffleEquivalent(VT, Mask, Unpckhwd, DAG));
12313   return IsUnpackwdMask;
12314 }
12315 
12316 static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask,
12317                                       const SelectionDAG &DAG) {
12318   // Create 128-bit vector type based on mask size.
12319   MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
12320   MVT VT = MVT::getVectorVT(EltVT, Mask.size());
12321 
12322   // We can't assume a canonical shuffle mask, so try the commuted version too.
12323   SmallVector<int, 4> CommutedMask(Mask);
12324   ShuffleVectorSDNode::commuteMask(CommutedMask);
12325 
12326   // Match any of unary/binary or low/high.
12327   for (unsigned i = 0; i != 4; ++i) {
12328     SmallVector<int, 16> UnpackMask;
12329     createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
12330     if (isTargetShuffleEquivalent(VT, Mask, UnpackMask, DAG) ||
12331         isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask, DAG))
12332       return true;
12333   }
12334   return false;
12335 }
12336 
12337 /// Return true if a shuffle mask chooses elements identically in its top and
12338 /// bottom halves. For example, any splat mask has the same top and bottom
12339 /// halves. If an element is undefined in only one half of the mask, the halves
12340 /// are not considered identical.
12341 static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
12342   assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
12343   unsigned HalfSize = Mask.size() / 2;
12344   for (unsigned i = 0; i != HalfSize; ++i) {
12345     if (Mask[i] != Mask[i + HalfSize])
12346       return false;
12347   }
12348   return true;
12349 }
12350 
12351 /// Get a 4-lane 8-bit shuffle immediate for a mask.
12352 ///
12353 /// This helper function produces an 8-bit shuffle immediate corresponding to
12354 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
12355 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
12356 /// example.
12357 ///
12358 /// NB: We rely heavily on "undef" masks preserving the input lane.
12359 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
12360   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
12361   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
12362   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
12363   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
12364   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
12365 
12366   // If the mask only uses one non-undef element, then fully 'splat' it to
12367   // improve later broadcast matching.
12368   int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
12369   assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
12370 
12371   int FirstElt = Mask[FirstIndex];
12372   if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
12373     return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
12374 
12375   unsigned Imm = 0;
12376   Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
12377   Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
12378   Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
12379   Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
12380   return Imm;
12381 }
12382 
12383 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
12384                                           SelectionDAG &DAG) {
12385   return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
12386 }
12387 
12388 // The Shuffle result is as follow:
12389 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
12390 // Each Zeroable's element correspond to a particular Mask's element.
12391 // As described in computeZeroableShuffleElements function.
12392 //
12393 // The function looks for a sub-mask that the nonzero elements are in
12394 // increasing order. If such sub-mask exist. The function returns true.
12395 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
12396                                      ArrayRef<int> Mask, const EVT &VectorType,
12397                                      bool &IsZeroSideLeft) {
12398   int NextElement = -1;
12399   // Check if the Mask's nonzero elements are in increasing order.
12400   for (int i = 0, e = Mask.size(); i < e; i++) {
12401     // Checks if the mask's zeros elements are built from only zeros.
12402     assert(Mask[i] >= -1 && "Out of bound mask element!");
12403     if (Mask[i] < 0)
12404       return false;
12405     if (Zeroable[i])
12406       continue;
12407     // Find the lowest non zero element
12408     if (NextElement < 0) {
12409       NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
12410       IsZeroSideLeft = NextElement != 0;
12411     }
12412     // Exit if the mask's non zero elements are not in increasing order.
12413     if (NextElement != Mask[i])
12414       return false;
12415     NextElement++;
12416   }
12417   return true;
12418 }
12419 
12420 /// Try to lower a shuffle with a single PSHUFB of V1 or V2.
12421 static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
12422                                       ArrayRef<int> Mask, SDValue V1,
12423                                       SDValue V2, const APInt &Zeroable,
12424                                       const X86Subtarget &Subtarget,
12425                                       SelectionDAG &DAG) {
12426   int Size = Mask.size();
12427   int LaneSize = 128 / VT.getScalarSizeInBits();
12428   const int NumBytes = VT.getSizeInBits() / 8;
12429   const int NumEltBytes = VT.getScalarSizeInBits() / 8;
12430 
12431   assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
12432          (Subtarget.hasAVX2() && VT.is256BitVector()) ||
12433          (Subtarget.hasBWI() && VT.is512BitVector()));
12434 
12435   SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
12436   // Sign bit set in i8 mask means zero element.
12437   SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
12438 
12439   SDValue V;
12440   for (int i = 0; i < NumBytes; ++i) {
12441     int M = Mask[i / NumEltBytes];
12442     if (M < 0) {
12443       PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
12444       continue;
12445     }
12446     if (Zeroable[i / NumEltBytes]) {
12447       PSHUFBMask[i] = ZeroMask;
12448       continue;
12449     }
12450 
12451     // We can only use a single input of V1 or V2.
12452     SDValue SrcV = (M >= Size ? V2 : V1);
12453     if (V && V != SrcV)
12454       return SDValue();
12455     V = SrcV;
12456     M %= Size;
12457 
12458     // PSHUFB can't cross lanes, ensure this doesn't happen.
12459     if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
12460       return SDValue();
12461 
12462     M = M % LaneSize;
12463     M = M * NumEltBytes + (i % NumEltBytes);
12464     PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
12465   }
12466   assert(V && "Failed to find a source input");
12467 
12468   MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
12469   return DAG.getBitcast(
12470       VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
12471                       DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
12472 }
12473 
12474 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
12475                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
12476                            const SDLoc &dl);
12477 
12478 // X86 has dedicated shuffle that can be lowered to VEXPAND
12479 static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
12480                                     const APInt &Zeroable,
12481                                     ArrayRef<int> Mask, SDValue &V1,
12482                                     SDValue &V2, SelectionDAG &DAG,
12483                                     const X86Subtarget &Subtarget) {
12484   bool IsLeftZeroSide = true;
12485   if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
12486                                 IsLeftZeroSide))
12487     return SDValue();
12488   unsigned VEXPANDMask = (~Zeroable).getZExtValue();
12489   MVT IntegerType =
12490       MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
12491   SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
12492   unsigned NumElts = VT.getVectorNumElements();
12493   assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
12494          "Unexpected number of vector elements");
12495   SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
12496                               Subtarget, DAG, DL);
12497   SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
12498   SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
12499   return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
12500 }
12501 
12502 static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
12503                                   unsigned &UnpackOpcode, bool IsUnary,
12504                                   ArrayRef<int> TargetMask, const SDLoc &DL,
12505                                   SelectionDAG &DAG,
12506                                   const X86Subtarget &Subtarget) {
12507   int NumElts = VT.getVectorNumElements();
12508 
12509   bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
12510   for (int i = 0; i != NumElts; i += 2) {
12511     int M1 = TargetMask[i + 0];
12512     int M2 = TargetMask[i + 1];
12513     Undef1 &= (SM_SentinelUndef == M1);
12514     Undef2 &= (SM_SentinelUndef == M2);
12515     Zero1 &= isUndefOrZero(M1);
12516     Zero2 &= isUndefOrZero(M2);
12517   }
12518   assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
12519          "Zeroable shuffle detected");
12520 
12521   // Attempt to match the target mask against the unpack lo/hi mask patterns.
12522   SmallVector<int, 64> Unpckl, Unpckh;
12523   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
12524   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG, V1,
12525                                 (IsUnary ? V1 : V2))) {
12526     UnpackOpcode = X86ISD::UNPCKL;
12527     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
12528     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
12529     return true;
12530   }
12531 
12532   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
12533   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG, V1,
12534                                 (IsUnary ? V1 : V2))) {
12535     UnpackOpcode = X86ISD::UNPCKH;
12536     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
12537     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
12538     return true;
12539   }
12540 
12541   // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
12542   if (IsUnary && (Zero1 || Zero2)) {
12543     // Don't bother if we can blend instead.
12544     if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
12545         isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
12546       return false;
12547 
12548     bool MatchLo = true, MatchHi = true;
12549     for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
12550       int M = TargetMask[i];
12551 
12552       // Ignore if the input is known to be zero or the index is undef.
12553       if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
12554           (M == SM_SentinelUndef))
12555         continue;
12556 
12557       MatchLo &= (M == Unpckl[i]);
12558       MatchHi &= (M == Unpckh[i]);
12559     }
12560 
12561     if (MatchLo || MatchHi) {
12562       UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
12563       V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
12564       V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
12565       return true;
12566     }
12567   }
12568 
12569   // If a binary shuffle, commute and try again.
12570   if (!IsUnary) {
12571     ShuffleVectorSDNode::commuteMask(Unpckl);
12572     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG)) {
12573       UnpackOpcode = X86ISD::UNPCKL;
12574       std::swap(V1, V2);
12575       return true;
12576     }
12577 
12578     ShuffleVectorSDNode::commuteMask(Unpckh);
12579     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG)) {
12580       UnpackOpcode = X86ISD::UNPCKH;
12581       std::swap(V1, V2);
12582       return true;
12583     }
12584   }
12585 
12586   return false;
12587 }
12588 
12589 // X86 has dedicated unpack instructions that can handle specific blend
12590 // operations: UNPCKH and UNPCKL.
12591 static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
12592                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
12593                                      SelectionDAG &DAG) {
12594   SmallVector<int, 8> Unpckl;
12595   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
12596   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
12597     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
12598 
12599   SmallVector<int, 8> Unpckh;
12600   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
12601   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
12602     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
12603 
12604   // Commute and try again.
12605   ShuffleVectorSDNode::commuteMask(Unpckl);
12606   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
12607     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
12608 
12609   ShuffleVectorSDNode::commuteMask(Unpckh);
12610   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
12611     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
12612 
12613   return SDValue();
12614 }
12615 
12616 /// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
12617 /// followed by unpack 256-bit.
12618 static SDValue lowerShuffleWithUNPCK256(const SDLoc &DL, MVT VT,
12619                                         ArrayRef<int> Mask, SDValue V1,
12620                                         SDValue V2, SelectionDAG &DAG) {
12621   SmallVector<int, 32> Unpckl, Unpckh;
12622   createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
12623   createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
12624 
12625   unsigned UnpackOpcode;
12626   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
12627     UnpackOpcode = X86ISD::UNPCKL;
12628   else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
12629     UnpackOpcode = X86ISD::UNPCKH;
12630   else
12631     return SDValue();
12632 
12633   // This is a "natural" unpack operation (rather than the 128-bit sectored
12634   // operation implemented by AVX). We need to rearrange 64-bit chunks of the
12635   // input in order to use the x86 instruction.
12636   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
12637                             DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
12638   V1 = DAG.getBitcast(VT, V1);
12639   return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
12640 }
12641 
12642 // Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
12643 // source into the lower elements and zeroing the upper elements.
12644 static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
12645                                  ArrayRef<int> Mask, const APInt &Zeroable,
12646                                  const X86Subtarget &Subtarget) {
12647   if (!VT.is512BitVector() && !Subtarget.hasVLX())
12648     return false;
12649 
12650   unsigned NumElts = Mask.size();
12651   unsigned EltSizeInBits = VT.getScalarSizeInBits();
12652   unsigned MaxScale = 64 / EltSizeInBits;
12653 
12654   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
12655     unsigned SrcEltBits = EltSizeInBits * Scale;
12656     if (SrcEltBits < 32 && !Subtarget.hasBWI())
12657       continue;
12658     unsigned NumSrcElts = NumElts / Scale;
12659     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
12660       continue;
12661     unsigned UpperElts = NumElts - NumSrcElts;
12662     if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
12663       continue;
12664     SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
12665     SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
12666     DstVT = MVT::getIntegerVT(EltSizeInBits);
12667     if ((NumSrcElts * EltSizeInBits) >= 128) {
12668       // ISD::TRUNCATE
12669       DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
12670     } else {
12671       // X86ISD::VTRUNC
12672       DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
12673     }
12674     return true;
12675   }
12676 
12677   return false;
12678 }
12679 
12680 // Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
12681 // element padding to the final DstVT.
12682 static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
12683                                   const X86Subtarget &Subtarget,
12684                                   SelectionDAG &DAG, bool ZeroUppers) {
12685   MVT SrcVT = Src.getSimpleValueType();
12686   MVT DstSVT = DstVT.getScalarType();
12687   unsigned NumDstElts = DstVT.getVectorNumElements();
12688   unsigned NumSrcElts = SrcVT.getVectorNumElements();
12689   unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
12690 
12691   if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
12692     return SDValue();
12693 
12694   // Perform a direct ISD::TRUNCATE if possible.
12695   if (NumSrcElts == NumDstElts)
12696     return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
12697 
12698   if (NumSrcElts > NumDstElts) {
12699     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
12700     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
12701     return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
12702   }
12703 
12704   if ((NumSrcElts * DstEltSizeInBits) >= 128) {
12705     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
12706     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
12707     return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
12708                           DstVT.getSizeInBits());
12709   }
12710 
12711   // Non-VLX targets must truncate from a 512-bit type, so we need to
12712   // widen, truncate and then possibly extract the original subvector.
12713   if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
12714     SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
12715     return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
12716   }
12717 
12718   // Fallback to a X86ISD::VTRUNC, padding if necessary.
12719   MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
12720   SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
12721   if (DstVT != TruncVT)
12722     Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
12723                            DstVT.getSizeInBits());
12724   return Trunc;
12725 }
12726 
12727 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
12728 //
12729 // An example is the following:
12730 //
12731 // t0: ch = EntryToken
12732 //           t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
12733 //         t25: v4i32 = truncate t2
12734 //       t41: v8i16 = bitcast t25
12735 //       t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
12736 //       Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
12737 //     t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
12738 //   t18: v2i64 = bitcast t51
12739 //
12740 // One can just use a single vpmovdw instruction, without avx512vl we need to
12741 // use the zmm variant and extract the lower subvector, padding with zeroes.
12742 // TODO: Merge with lowerShuffleAsVTRUNC.
12743 static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, MVT VT, SDValue V1,
12744                                      SDValue V2, ArrayRef<int> Mask,
12745                                      const APInt &Zeroable,
12746                                      const X86Subtarget &Subtarget,
12747                                      SelectionDAG &DAG) {
12748   assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
12749   if (!Subtarget.hasAVX512())
12750     return SDValue();
12751 
12752   unsigned NumElts = VT.getVectorNumElements();
12753   unsigned EltSizeInBits = VT.getScalarSizeInBits();
12754   unsigned MaxScale = 64 / EltSizeInBits;
12755   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
12756     unsigned SrcEltBits = EltSizeInBits * Scale;
12757     unsigned NumSrcElts = NumElts / Scale;
12758     unsigned UpperElts = NumElts - NumSrcElts;
12759     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
12760         !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
12761       continue;
12762 
12763     // Attempt to find a matching source truncation, but as a fall back VLX
12764     // cases can use the VPMOV directly.
12765     SDValue Src = peekThroughBitcasts(V1);
12766     if (Src.getOpcode() == ISD::TRUNCATE &&
12767         Src.getScalarValueSizeInBits() == SrcEltBits) {
12768       Src = Src.getOperand(0);
12769     } else if (Subtarget.hasVLX()) {
12770       MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
12771       MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
12772       Src = DAG.getBitcast(SrcVT, Src);
12773       // Don't do this if PACKSS/PACKUS could perform it cheaper.
12774       if (Scale == 2 &&
12775           ((DAG.ComputeNumSignBits(Src) > EltSizeInBits) ||
12776            (DAG.computeKnownBits(Src).countMinLeadingZeros() >= EltSizeInBits)))
12777         return SDValue();
12778     } else
12779       return SDValue();
12780 
12781     // VPMOVWB is only available with avx512bw.
12782     if (!Subtarget.hasBWI() && Src.getScalarValueSizeInBits() < 32)
12783       return SDValue();
12784 
12785     bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
12786     return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
12787   }
12788 
12789   return SDValue();
12790 }
12791 
12792 // Attempt to match binary shuffle patterns as a truncate.
12793 static SDValue lowerShuffleAsVTRUNC(const SDLoc &DL, MVT VT, SDValue V1,
12794                                     SDValue V2, ArrayRef<int> Mask,
12795                                     const APInt &Zeroable,
12796                                     const X86Subtarget &Subtarget,
12797                                     SelectionDAG &DAG) {
12798   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12799          "Unexpected VTRUNC type");
12800   if (!Subtarget.hasAVX512())
12801     return SDValue();
12802 
12803   unsigned NumElts = VT.getVectorNumElements();
12804   unsigned EltSizeInBits = VT.getScalarSizeInBits();
12805   unsigned MaxScale = 64 / EltSizeInBits;
12806   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
12807     // TODO: Support non-BWI VPMOVWB truncations?
12808     unsigned SrcEltBits = EltSizeInBits * Scale;
12809     if (SrcEltBits < 32 && !Subtarget.hasBWI())
12810       continue;
12811 
12812     // Match shuffle <Ofs,Ofs+Scale,Ofs+2*Scale,..,undef_or_zero,undef_or_zero>
12813     // Bail if the V2 elements are undef.
12814     unsigned NumHalfSrcElts = NumElts / Scale;
12815     unsigned NumSrcElts = 2 * NumHalfSrcElts;
12816     for (unsigned Offset = 0; Offset != Scale; ++Offset) {
12817       if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, Offset, Scale) ||
12818           isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
12819         continue;
12820 
12821       // The elements beyond the truncation must be undef/zero.
12822       unsigned UpperElts = NumElts - NumSrcElts;
12823       if (UpperElts > 0 &&
12824           !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
12825         continue;
12826       bool UndefUppers =
12827           UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
12828 
12829       // For offset truncations, ensure that the concat is cheap.
12830       if (Offset) {
12831         auto IsCheapConcat = [&](SDValue Lo, SDValue Hi) {
12832           if (Lo.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12833               Hi.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12834             return Lo.getOperand(0) == Hi.getOperand(0);
12835           if (ISD::isNormalLoad(Lo.getNode()) &&
12836               ISD::isNormalLoad(Hi.getNode())) {
12837             auto *LDLo = cast<LoadSDNode>(Lo);
12838             auto *LDHi = cast<LoadSDNode>(Hi);
12839             return DAG.areNonVolatileConsecutiveLoads(
12840                 LDHi, LDLo, Lo.getValueType().getStoreSize(), 1);
12841           }
12842           return false;
12843         };
12844         if (!IsCheapConcat(V1, V2))
12845           continue;
12846       }
12847 
12848       // As we're using both sources then we need to concat them together
12849       // and truncate from the double-sized src.
12850       MVT ConcatVT = MVT::getVectorVT(VT.getScalarType(), NumElts * 2);
12851       SDValue Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
12852 
12853       MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
12854       MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
12855       Src = DAG.getBitcast(SrcVT, Src);
12856 
12857       // Shift the offset'd elements into place for the truncation.
12858       // TODO: Use getTargetVShiftByConstNode.
12859       if (Offset)
12860         Src = DAG.getNode(
12861             X86ISD::VSRLI, DL, SrcVT, Src,
12862             DAG.getTargetConstant(Offset * EltSizeInBits, DL, MVT::i8));
12863 
12864       return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
12865     }
12866   }
12867 
12868   return SDValue();
12869 }
12870 
12871 /// Check whether a compaction lowering can be done by dropping even/odd
12872 /// elements and compute how many times even/odd elements must be dropped.
12873 ///
12874 /// This handles shuffles which take every Nth element where N is a power of
12875 /// two. Example shuffle masks:
12876 ///
12877 /// (even)
12878 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
12879 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
12880 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
12881 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
12882 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
12883 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
12884 ///
12885 /// (odd)
12886 ///  N = 1:  1,  3,  5,  7,  9, 11, 13, 15,  0,  2,  4,  6,  8, 10, 12, 14
12887 ///  N = 1:  1,  3,  5,  7,  9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31
12888 ///
12889 /// Any of these lanes can of course be undef.
12890 ///
12891 /// This routine only supports N <= 3.
12892 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
12893 /// for larger N.
12894 ///
12895 /// \returns N above, or the number of times even/odd elements must be dropped
12896 /// if there is such a number. Otherwise returns zero.
12897 static int canLowerByDroppingElements(ArrayRef<int> Mask, bool MatchEven,
12898                                       bool IsSingleInput) {
12899   // The modulus for the shuffle vector entries is based on whether this is
12900   // a single input or not.
12901   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
12902   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
12903          "We should only be called with masks with a power-of-2 size!");
12904 
12905   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
12906   int Offset = MatchEven ? 0 : 1;
12907 
12908   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
12909   // and 2^3 simultaneously. This is because we may have ambiguity with
12910   // partially undef inputs.
12911   bool ViableForN[3] = {true, true, true};
12912 
12913   for (int i = 0, e = Mask.size(); i < e; ++i) {
12914     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
12915     // want.
12916     if (Mask[i] < 0)
12917       continue;
12918 
12919     bool IsAnyViable = false;
12920     for (unsigned j = 0; j != std::size(ViableForN); ++j)
12921       if (ViableForN[j]) {
12922         uint64_t N = j + 1;
12923 
12924         // The shuffle mask must be equal to (i * 2^N) % M.
12925         if ((uint64_t)(Mask[i] - Offset) == (((uint64_t)i << N) & ModMask))
12926           IsAnyViable = true;
12927         else
12928           ViableForN[j] = false;
12929       }
12930     // Early exit if we exhaust the possible powers of two.
12931     if (!IsAnyViable)
12932       break;
12933   }
12934 
12935   for (unsigned j = 0; j != std::size(ViableForN); ++j)
12936     if (ViableForN[j])
12937       return j + 1;
12938 
12939   // Return 0 as there is no viable power of two.
12940   return 0;
12941 }
12942 
12943 // X86 has dedicated pack instructions that can handle specific truncation
12944 // operations: PACKSS and PACKUS.
12945 // Checks for compaction shuffle masks if MaxStages > 1.
12946 // TODO: Add support for matching multiple PACKSS/PACKUS stages.
12947 static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
12948                                  unsigned &PackOpcode, ArrayRef<int> TargetMask,
12949                                  const SelectionDAG &DAG,
12950                                  const X86Subtarget &Subtarget,
12951                                  unsigned MaxStages = 1) {
12952   unsigned NumElts = VT.getVectorNumElements();
12953   unsigned BitSize = VT.getScalarSizeInBits();
12954   assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
12955          "Illegal maximum compaction");
12956 
12957   auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
12958     unsigned NumSrcBits = PackVT.getScalarSizeInBits();
12959     unsigned NumPackedBits = NumSrcBits - BitSize;
12960     N1 = peekThroughBitcasts(N1);
12961     N2 = peekThroughBitcasts(N2);
12962     unsigned NumBits1 = N1.getScalarValueSizeInBits();
12963     unsigned NumBits2 = N2.getScalarValueSizeInBits();
12964     bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
12965     bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
12966     if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
12967         (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
12968       return false;
12969     if (Subtarget.hasSSE41() || BitSize == 8) {
12970       APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
12971       if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
12972           (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
12973         V1 = N1;
12974         V2 = N2;
12975         SrcVT = PackVT;
12976         PackOpcode = X86ISD::PACKUS;
12977         return true;
12978       }
12979     }
12980     bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
12981     bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
12982     if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
12983          DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
12984         (N2.isUndef() || IsZero2 || IsAllOnes2 ||
12985          DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
12986       V1 = N1;
12987       V2 = N2;
12988       SrcVT = PackVT;
12989       PackOpcode = X86ISD::PACKSS;
12990       return true;
12991     }
12992     return false;
12993   };
12994 
12995   // Attempt to match against wider and wider compaction patterns.
12996   for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
12997     MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
12998     MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
12999 
13000     // Try binary shuffle.
13001     SmallVector<int, 32> BinaryMask;
13002     createPackShuffleMask(VT, BinaryMask, false, NumStages);
13003     if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, DAG, V1, V2))
13004       if (MatchPACK(V1, V2, PackVT))
13005         return true;
13006 
13007     // Try unary shuffle.
13008     SmallVector<int, 32> UnaryMask;
13009     createPackShuffleMask(VT, UnaryMask, true, NumStages);
13010     if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, DAG, V1))
13011       if (MatchPACK(V1, V1, PackVT))
13012         return true;
13013   }
13014 
13015   return false;
13016 }
13017 
13018 static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
13019                                     SDValue V1, SDValue V2, SelectionDAG &DAG,
13020                                     const X86Subtarget &Subtarget) {
13021   MVT PackVT;
13022   unsigned PackOpcode;
13023   unsigned SizeBits = VT.getSizeInBits();
13024   unsigned EltBits = VT.getScalarSizeInBits();
13025   unsigned MaxStages = Log2_32(64 / EltBits);
13026   if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
13027                             Subtarget, MaxStages))
13028     return SDValue();
13029 
13030   unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
13031   unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
13032 
13033   // Don't lower multi-stage packs on AVX512, truncation is better.
13034   if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
13035     return SDValue();
13036 
13037   // Pack to the largest type possible:
13038   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
13039   unsigned MaxPackBits = 16;
13040   if (CurrentEltBits > 16 &&
13041       (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
13042     MaxPackBits = 32;
13043 
13044   // Repeatedly pack down to the target size.
13045   SDValue Res;
13046   for (unsigned i = 0; i != NumStages; ++i) {
13047     unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
13048     unsigned NumSrcElts = SizeBits / SrcEltBits;
13049     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
13050     MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
13051     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
13052     MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
13053     Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
13054                       DAG.getBitcast(SrcVT, V2));
13055     V1 = V2 = Res;
13056     CurrentEltBits /= 2;
13057   }
13058   assert(Res && Res.getValueType() == VT &&
13059          "Failed to lower compaction shuffle");
13060   return Res;
13061 }
13062 
13063 /// Try to emit a bitmask instruction for a shuffle.
13064 ///
13065 /// This handles cases where we can model a blend exactly as a bitmask due to
13066 /// one of the inputs being zeroable.
13067 static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
13068                                      SDValue V2, ArrayRef<int> Mask,
13069                                      const APInt &Zeroable,
13070                                      const X86Subtarget &Subtarget,
13071                                      SelectionDAG &DAG) {
13072   MVT MaskVT = VT;
13073   MVT EltVT = VT.getVectorElementType();
13074   SDValue Zero, AllOnes;
13075   // Use f64 if i64 isn't legal.
13076   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
13077     EltVT = MVT::f64;
13078     MaskVT = MVT::getVectorVT(EltVT, Mask.size());
13079   }
13080 
13081   MVT LogicVT = VT;
13082   if (EltVT == MVT::f32 || EltVT == MVT::f64) {
13083     Zero = DAG.getConstantFP(0.0, DL, EltVT);
13084     APFloat AllOnesValue =
13085         APFloat::getAllOnesValue(SelectionDAG::EVTToAPFloatSemantics(EltVT));
13086     AllOnes = DAG.getConstantFP(AllOnesValue, DL, EltVT);
13087     LogicVT =
13088         MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
13089   } else {
13090     Zero = DAG.getConstant(0, DL, EltVT);
13091     AllOnes = DAG.getAllOnesConstant(DL, EltVT);
13092   }
13093 
13094   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
13095   SDValue V;
13096   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
13097     if (Zeroable[i])
13098       continue;
13099     if (Mask[i] % Size != i)
13100       return SDValue(); // Not a blend.
13101     if (!V)
13102       V = Mask[i] < Size ? V1 : V2;
13103     else if (V != (Mask[i] < Size ? V1 : V2))
13104       return SDValue(); // Can only let one input through the mask.
13105 
13106     VMaskOps[i] = AllOnes;
13107   }
13108   if (!V)
13109     return SDValue(); // No non-zeroable elements!
13110 
13111   SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
13112   VMask = DAG.getBitcast(LogicVT, VMask);
13113   V = DAG.getBitcast(LogicVT, V);
13114   SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
13115   return DAG.getBitcast(VT, And);
13116 }
13117 
13118 /// Try to emit a blend instruction for a shuffle using bit math.
13119 ///
13120 /// This is used as a fallback approach when first class blend instructions are
13121 /// unavailable. Currently it is only suitable for integer vectors, but could
13122 /// be generalized for floating point vectors if desirable.
13123 static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
13124                                       SDValue V2, ArrayRef<int> Mask,
13125                                       SelectionDAG &DAG) {
13126   assert(VT.isInteger() && "Only supports integer vector types!");
13127   MVT EltVT = VT.getVectorElementType();
13128   SDValue Zero = DAG.getConstant(0, DL, EltVT);
13129   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
13130   SmallVector<SDValue, 16> MaskOps;
13131   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
13132     if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
13133       return SDValue(); // Shuffled input!
13134     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
13135   }
13136 
13137   SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
13138   return getBitSelect(DL, VT, V1, V2, V1Mask, DAG);
13139 }
13140 
13141 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
13142                                     SDValue PreservedSrc,
13143                                     const X86Subtarget &Subtarget,
13144                                     SelectionDAG &DAG);
13145 
13146 static bool matchShuffleAsBlend(MVT VT, SDValue V1, SDValue V2,
13147                                 MutableArrayRef<int> Mask,
13148                                 const APInt &Zeroable, bool &ForceV1Zero,
13149                                 bool &ForceV2Zero, uint64_t &BlendMask) {
13150   bool V1IsZeroOrUndef =
13151       V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
13152   bool V2IsZeroOrUndef =
13153       V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
13154 
13155   BlendMask = 0;
13156   ForceV1Zero = false, ForceV2Zero = false;
13157   assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
13158 
13159   int NumElts = Mask.size();
13160   int NumLanes = VT.getSizeInBits() / 128;
13161   int NumEltsPerLane = NumElts / NumLanes;
13162   assert((NumLanes * NumEltsPerLane) == NumElts && "Value type mismatch");
13163 
13164   // For 32/64-bit elements, if we only reference one input (plus any undefs),
13165   // then ensure the blend mask part for that lane just references that input.
13166   bool ForceWholeLaneMasks =
13167       VT.is256BitVector() && VT.getScalarSizeInBits() >= 32;
13168 
13169   // Attempt to generate the binary blend mask. If an input is zero then
13170   // we can use any lane.
13171   for (int Lane = 0; Lane != NumLanes; ++Lane) {
13172     // Keep track of the inputs used per lane.
13173     bool LaneV1InUse = false;
13174     bool LaneV2InUse = false;
13175     uint64_t LaneBlendMask = 0;
13176     for (int LaneElt = 0; LaneElt != NumEltsPerLane; ++LaneElt) {
13177       int Elt = (Lane * NumEltsPerLane) + LaneElt;
13178       int M = Mask[Elt];
13179       if (M == SM_SentinelUndef)
13180         continue;
13181       if (M == Elt || (0 <= M && M < NumElts &&
13182                      IsElementEquivalent(NumElts, V1, V1, M, Elt))) {
13183         Mask[Elt] = Elt;
13184         LaneV1InUse = true;
13185         continue;
13186       }
13187       if (M == (Elt + NumElts) ||
13188           (NumElts <= M &&
13189            IsElementEquivalent(NumElts, V2, V2, M - NumElts, Elt))) {
13190         LaneBlendMask |= 1ull << LaneElt;
13191         Mask[Elt] = Elt + NumElts;
13192         LaneV2InUse = true;
13193         continue;
13194       }
13195       if (Zeroable[Elt]) {
13196         if (V1IsZeroOrUndef) {
13197           ForceV1Zero = true;
13198           Mask[Elt] = Elt;
13199           LaneV1InUse = true;
13200           continue;
13201         }
13202         if (V2IsZeroOrUndef) {
13203           ForceV2Zero = true;
13204           LaneBlendMask |= 1ull << LaneElt;
13205           Mask[Elt] = Elt + NumElts;
13206           LaneV2InUse = true;
13207           continue;
13208         }
13209       }
13210       return false;
13211     }
13212 
13213     // If we only used V2 then splat the lane blend mask to avoid any demanded
13214     // elts from V1 in this lane (the V1 equivalent is implicit with a zero
13215     // blend mask bit).
13216     if (ForceWholeLaneMasks && LaneV2InUse && !LaneV1InUse)
13217       LaneBlendMask = (1ull << NumEltsPerLane) - 1;
13218 
13219     BlendMask |= LaneBlendMask << (Lane * NumEltsPerLane);
13220   }
13221   return true;
13222 }
13223 
13224 static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
13225                                             int Scale) {
13226   uint64_t ScaledMask = 0;
13227   for (int i = 0; i != Size; ++i)
13228     if (BlendMask & (1ull << i))
13229       ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
13230   return ScaledMask;
13231 }
13232 
13233 /// Try to emit a blend instruction for a shuffle.
13234 ///
13235 /// This doesn't do any checks for the availability of instructions for blending
13236 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
13237 /// be matched in the backend with the type given. What it does check for is
13238 /// that the shuffle mask is a blend, or convertible into a blend with zero.
13239 static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
13240                                    SDValue V2, ArrayRef<int> Original,
13241                                    const APInt &Zeroable,
13242                                    const X86Subtarget &Subtarget,
13243                                    SelectionDAG &DAG) {
13244   uint64_t BlendMask = 0;
13245   bool ForceV1Zero = false, ForceV2Zero = false;
13246   SmallVector<int, 64> Mask(Original);
13247   if (!matchShuffleAsBlend(VT, V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
13248                            BlendMask))
13249     return SDValue();
13250 
13251   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
13252   if (ForceV1Zero)
13253     V1 = getZeroVector(VT, Subtarget, DAG, DL);
13254   if (ForceV2Zero)
13255     V2 = getZeroVector(VT, Subtarget, DAG, DL);
13256 
13257   unsigned NumElts = VT.getVectorNumElements();
13258 
13259   switch (VT.SimpleTy) {
13260   case MVT::v4i64:
13261   case MVT::v8i32:
13262     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
13263     [[fallthrough]];
13264   case MVT::v4f64:
13265   case MVT::v8f32:
13266     assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
13267     [[fallthrough]];
13268   case MVT::v2f64:
13269   case MVT::v2i64:
13270   case MVT::v4f32:
13271   case MVT::v4i32:
13272   case MVT::v8i16:
13273     assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
13274     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
13275                        DAG.getTargetConstant(BlendMask, DL, MVT::i8));
13276   case MVT::v16i16: {
13277     assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
13278     SmallVector<int, 8> RepeatedMask;
13279     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
13280       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
13281       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
13282       BlendMask = 0;
13283       for (int i = 0; i < 8; ++i)
13284         if (RepeatedMask[i] >= 8)
13285           BlendMask |= 1ull << i;
13286       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
13287                          DAG.getTargetConstant(BlendMask, DL, MVT::i8));
13288     }
13289     // Use PBLENDW for lower/upper lanes and then blend lanes.
13290     // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
13291     // merge to VSELECT where useful.
13292     uint64_t LoMask = BlendMask & 0xFF;
13293     uint64_t HiMask = (BlendMask >> 8) & 0xFF;
13294     if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
13295       SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
13296                                DAG.getTargetConstant(LoMask, DL, MVT::i8));
13297       SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
13298                                DAG.getTargetConstant(HiMask, DL, MVT::i8));
13299       return DAG.getVectorShuffle(
13300           MVT::v16i16, DL, Lo, Hi,
13301           {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
13302     }
13303     [[fallthrough]];
13304   }
13305   case MVT::v32i8:
13306     assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
13307     [[fallthrough]];
13308   case MVT::v16i8: {
13309     assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
13310 
13311     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
13312     if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
13313                                                Subtarget, DAG))
13314       return Masked;
13315 
13316     if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
13317       MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
13318       SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
13319       return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
13320     }
13321 
13322     // If we have VPTERNLOG, we can use that as a bit blend.
13323     if (Subtarget.hasVLX())
13324       if (SDValue BitBlend =
13325               lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
13326         return BitBlend;
13327 
13328     // Scale the blend by the number of bytes per element.
13329     int Scale = VT.getScalarSizeInBits() / 8;
13330 
13331     // This form of blend is always done on bytes. Compute the byte vector
13332     // type.
13333     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
13334 
13335     // x86 allows load folding with blendvb from the 2nd source operand. But
13336     // we are still using LLVM select here (see comment below), so that's V1.
13337     // If V2 can be load-folded and V1 cannot be load-folded, then commute to
13338     // allow that load-folding possibility.
13339     if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
13340       ShuffleVectorSDNode::commuteMask(Mask);
13341       std::swap(V1, V2);
13342     }
13343 
13344     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
13345     // mix of LLVM's code generator and the x86 backend. We tell the code
13346     // generator that boolean values in the elements of an x86 vector register
13347     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
13348     // mapping a select to operand #1, and 'false' mapping to operand #2. The
13349     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
13350     // of the element (the remaining are ignored) and 0 in that high bit would
13351     // mean operand #1 while 1 in the high bit would mean operand #2. So while
13352     // the LLVM model for boolean values in vector elements gets the relevant
13353     // bit set, it is set backwards and over constrained relative to x86's
13354     // actual model.
13355     SmallVector<SDValue, 32> VSELECTMask;
13356     for (int i = 0, Size = Mask.size(); i < Size; ++i)
13357       for (int j = 0; j < Scale; ++j)
13358         VSELECTMask.push_back(
13359             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
13360                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
13361                                           MVT::i8));
13362 
13363     V1 = DAG.getBitcast(BlendVT, V1);
13364     V2 = DAG.getBitcast(BlendVT, V2);
13365     return DAG.getBitcast(
13366         VT,
13367         DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
13368                       V1, V2));
13369   }
13370   case MVT::v16f32:
13371   case MVT::v8f64:
13372   case MVT::v8i64:
13373   case MVT::v16i32:
13374   case MVT::v32i16:
13375   case MVT::v64i8: {
13376     // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
13377     bool OptForSize = DAG.shouldOptForSize();
13378     if (!OptForSize) {
13379       if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
13380                                                  Subtarget, DAG))
13381         return Masked;
13382     }
13383 
13384     // Otherwise load an immediate into a GPR, cast to k-register, and use a
13385     // masked move.
13386     MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
13387     SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
13388     return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
13389   }
13390   default:
13391     llvm_unreachable("Not a supported integer vector type!");
13392   }
13393 }
13394 
13395 /// Try to lower as a blend of elements from two inputs followed by
13396 /// a single-input permutation.
13397 ///
13398 /// This matches the pattern where we can blend elements from two inputs and
13399 /// then reduce the shuffle to a single-input permutation.
13400 static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
13401                                              SDValue V1, SDValue V2,
13402                                              ArrayRef<int> Mask,
13403                                              SelectionDAG &DAG,
13404                                              bool ImmBlends = false) {
13405   // We build up the blend mask while checking whether a blend is a viable way
13406   // to reduce the shuffle.
13407   SmallVector<int, 32> BlendMask(Mask.size(), -1);
13408   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
13409 
13410   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
13411     if (Mask[i] < 0)
13412       continue;
13413 
13414     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
13415 
13416     if (BlendMask[Mask[i] % Size] < 0)
13417       BlendMask[Mask[i] % Size] = Mask[i];
13418     else if (BlendMask[Mask[i] % Size] != Mask[i])
13419       return SDValue(); // Can't blend in the needed input!
13420 
13421     PermuteMask[i] = Mask[i] % Size;
13422   }
13423 
13424   // If only immediate blends, then bail if the blend mask can't be widened to
13425   // i16.
13426   unsigned EltSize = VT.getScalarSizeInBits();
13427   if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
13428     return SDValue();
13429 
13430   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
13431   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
13432 }
13433 
13434 /// Try to lower as an unpack of elements from two inputs followed by
13435 /// a single-input permutation.
13436 ///
13437 /// This matches the pattern where we can unpack elements from two inputs and
13438 /// then reduce the shuffle to a single-input (wider) permutation.
13439 static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
13440                                              SDValue V1, SDValue V2,
13441                                              ArrayRef<int> Mask,
13442                                              SelectionDAG &DAG) {
13443   int NumElts = Mask.size();
13444   int NumLanes = VT.getSizeInBits() / 128;
13445   int NumLaneElts = NumElts / NumLanes;
13446   int NumHalfLaneElts = NumLaneElts / 2;
13447 
13448   bool MatchLo = true, MatchHi = true;
13449   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
13450 
13451   // Determine UNPCKL/UNPCKH type and operand order.
13452   for (int Elt = 0; Elt != NumElts; ++Elt) {
13453     int M = Mask[Elt];
13454     if (M < 0)
13455       continue;
13456 
13457     // Normalize the mask value depending on whether it's V1 or V2.
13458     int NormM = M;
13459     SDValue &Op = Ops[Elt & 1];
13460     if (M < NumElts && (Op.isUndef() || Op == V1))
13461       Op = V1;
13462     else if (NumElts <= M && (Op.isUndef() || Op == V2)) {
13463       Op = V2;
13464       NormM -= NumElts;
13465     } else
13466       return SDValue();
13467 
13468     bool MatchLoAnyLane = false, MatchHiAnyLane = false;
13469     for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
13470       int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
13471       MatchLoAnyLane |= isUndefOrInRange(NormM, Lo, Mid);
13472       MatchHiAnyLane |= isUndefOrInRange(NormM, Mid, Hi);
13473       if (MatchLoAnyLane || MatchHiAnyLane) {
13474         assert((MatchLoAnyLane ^ MatchHiAnyLane) &&
13475                "Failed to match UNPCKLO/UNPCKHI");
13476         break;
13477       }
13478     }
13479     MatchLo &= MatchLoAnyLane;
13480     MatchHi &= MatchHiAnyLane;
13481     if (!MatchLo && !MatchHi)
13482       return SDValue();
13483   }
13484   assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
13485 
13486   // Element indices have changed after unpacking. Calculate permute mask
13487   // so that they will be put back to the position as dictated by the
13488   // original shuffle mask indices.
13489   SmallVector<int, 32> PermuteMask(NumElts, -1);
13490   for (int Elt = 0; Elt != NumElts; ++Elt) {
13491     int M = Mask[Elt];
13492     if (M < 0)
13493       continue;
13494     int NormM = M;
13495     if (NumElts <= M)
13496       NormM -= NumElts;
13497     bool IsFirstOp = M < NumElts;
13498     int BaseMaskElt =
13499         NumLaneElts * (NormM / NumLaneElts) + (2 * (NormM % NumHalfLaneElts));
13500     if ((IsFirstOp && V1 == Ops[0]) || (!IsFirstOp && V2 == Ops[0]))
13501       PermuteMask[Elt] = BaseMaskElt;
13502     else if ((IsFirstOp && V1 == Ops[1]) || (!IsFirstOp && V2 == Ops[1]))
13503       PermuteMask[Elt] = BaseMaskElt + 1;
13504     assert(PermuteMask[Elt] != -1 &&
13505            "Input mask element is defined but failed to assign permute mask");
13506   }
13507 
13508   unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
13509   SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
13510   return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
13511 }
13512 
13513 /// Try to lower a shuffle as a permute of the inputs followed by an
13514 /// UNPCK instruction.
13515 ///
13516 /// This specifically targets cases where we end up with alternating between
13517 /// the two inputs, and so can permute them into something that feeds a single
13518 /// UNPCK instruction. Note that this routine only targets integer vectors
13519 /// because for floating point vectors we have a generalized SHUFPS lowering
13520 /// strategy that handles everything that doesn't *exactly* match an unpack,
13521 /// making this clever lowering unnecessary.
13522 static SDValue lowerShuffleAsPermuteAndUnpack(const SDLoc &DL, MVT VT,
13523                                               SDValue V1, SDValue V2,
13524                                               ArrayRef<int> Mask,
13525                                               const X86Subtarget &Subtarget,
13526                                               SelectionDAG &DAG) {
13527   int Size = Mask.size();
13528   assert(Mask.size() >= 2 && "Single element masks are invalid.");
13529 
13530   // This routine only supports 128-bit integer dual input vectors.
13531   if (VT.isFloatingPoint() || !VT.is128BitVector() || V2.isUndef())
13532     return SDValue();
13533 
13534   int NumLoInputs =
13535       count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
13536   int NumHiInputs =
13537       count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
13538 
13539   bool UnpackLo = NumLoInputs >= NumHiInputs;
13540 
13541   auto TryUnpack = [&](int ScalarSize, int Scale) {
13542     SmallVector<int, 16> V1Mask((unsigned)Size, -1);
13543     SmallVector<int, 16> V2Mask((unsigned)Size, -1);
13544 
13545     for (int i = 0; i < Size; ++i) {
13546       if (Mask[i] < 0)
13547         continue;
13548 
13549       // Each element of the unpack contains Scale elements from this mask.
13550       int UnpackIdx = i / Scale;
13551 
13552       // We only handle the case where V1 feeds the first slots of the unpack.
13553       // We rely on canonicalization to ensure this is the case.
13554       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
13555         return SDValue();
13556 
13557       // Setup the mask for this input. The indexing is tricky as we have to
13558       // handle the unpack stride.
13559       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
13560       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
13561           Mask[i] % Size;
13562     }
13563 
13564     // If we will have to shuffle both inputs to use the unpack, check whether
13565     // we can just unpack first and shuffle the result. If so, skip this unpack.
13566     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
13567         !isNoopShuffleMask(V2Mask))
13568       return SDValue();
13569 
13570     // Shuffle the inputs into place.
13571     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
13572     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
13573 
13574     // Cast the inputs to the type we will use to unpack them.
13575     MVT UnpackVT =
13576         MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
13577     V1 = DAG.getBitcast(UnpackVT, V1);
13578     V2 = DAG.getBitcast(UnpackVT, V2);
13579 
13580     // Unpack the inputs and cast the result back to the desired type.
13581     return DAG.getBitcast(
13582         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
13583                         UnpackVT, V1, V2));
13584   };
13585 
13586   // We try each unpack from the largest to the smallest to try and find one
13587   // that fits this mask.
13588   int OrigScalarSize = VT.getScalarSizeInBits();
13589   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
13590     if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
13591       return Unpack;
13592 
13593   // If we're shuffling with a zero vector then we're better off not doing
13594   // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
13595   if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
13596       ISD::isBuildVectorAllZeros(V2.getNode()))
13597     return SDValue();
13598 
13599   // If none of the unpack-rooted lowerings worked (or were profitable) try an
13600   // initial unpack.
13601   if (NumLoInputs == 0 || NumHiInputs == 0) {
13602     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
13603            "We have to have *some* inputs!");
13604     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
13605 
13606     // FIXME: We could consider the total complexity of the permute of each
13607     // possible unpacking. Or at the least we should consider how many
13608     // half-crossings are created.
13609     // FIXME: We could consider commuting the unpacks.
13610 
13611     SmallVector<int, 32> PermMask((unsigned)Size, -1);
13612     for (int i = 0; i < Size; ++i) {
13613       if (Mask[i] < 0)
13614         continue;
13615 
13616       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
13617 
13618       PermMask[i] =
13619           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
13620     }
13621     return DAG.getVectorShuffle(
13622         VT, DL,
13623         DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL, DL, VT,
13624                     V1, V2),
13625         DAG.getUNDEF(VT), PermMask);
13626   }
13627 
13628   return SDValue();
13629 }
13630 
13631 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
13632 /// permuting the elements of the result in place.
13633 static SDValue lowerShuffleAsByteRotateAndPermute(
13634     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13635     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13636   if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
13637       (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
13638       (VT.is512BitVector() && !Subtarget.hasBWI()))
13639     return SDValue();
13640 
13641   // We don't currently support lane crossing permutes.
13642   if (is128BitLaneCrossingShuffleMask(VT, Mask))
13643     return SDValue();
13644 
13645   int Scale = VT.getScalarSizeInBits() / 8;
13646   int NumLanes = VT.getSizeInBits() / 128;
13647   int NumElts = VT.getVectorNumElements();
13648   int NumEltsPerLane = NumElts / NumLanes;
13649 
13650   // Determine range of mask elts.
13651   bool Blend1 = true;
13652   bool Blend2 = true;
13653   std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
13654   std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
13655   for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
13656     for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
13657       int M = Mask[Lane + Elt];
13658       if (M < 0)
13659         continue;
13660       if (M < NumElts) {
13661         Blend1 &= (M == (Lane + Elt));
13662         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
13663         M = M % NumEltsPerLane;
13664         Range1.first = std::min(Range1.first, M);
13665         Range1.second = std::max(Range1.second, M);
13666       } else {
13667         M -= NumElts;
13668         Blend2 &= (M == (Lane + Elt));
13669         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
13670         M = M % NumEltsPerLane;
13671         Range2.first = std::min(Range2.first, M);
13672         Range2.second = std::max(Range2.second, M);
13673       }
13674     }
13675   }
13676 
13677   // Bail if we don't need both elements.
13678   // TODO - it might be worth doing this for unary shuffles if the permute
13679   // can be widened.
13680   if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
13681       !(0 <= Range2.first && Range2.second < NumEltsPerLane))
13682     return SDValue();
13683 
13684   if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
13685     return SDValue();
13686 
13687   // Rotate the 2 ops so we can access both ranges, then permute the result.
13688   auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
13689     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
13690     SDValue Rotate = DAG.getBitcast(
13691         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
13692                         DAG.getBitcast(ByteVT, Lo),
13693                         DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
13694     SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
13695     for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
13696       for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
13697         int M = Mask[Lane + Elt];
13698         if (M < 0)
13699           continue;
13700         if (M < NumElts)
13701           PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
13702         else
13703           PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
13704       }
13705     }
13706     return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
13707   };
13708 
13709   // Check if the ranges are small enough to rotate from either direction.
13710   if (Range2.second < Range1.first)
13711     return RotateAndPermute(V1, V2, Range1.first, 0);
13712   if (Range1.second < Range2.first)
13713     return RotateAndPermute(V2, V1, Range2.first, NumElts);
13714   return SDValue();
13715 }
13716 
13717 static bool isBroadcastShuffleMask(ArrayRef<int> Mask) {
13718   return isUndefOrEqual(Mask, 0);
13719 }
13720 
13721 static bool isNoopOrBroadcastShuffleMask(ArrayRef<int> Mask) {
13722   return isNoopShuffleMask(Mask) || isBroadcastShuffleMask(Mask);
13723 }
13724 
13725 /// Check if the Mask consists of the same element repeated multiple times.
13726 static bool isSingleElementRepeatedMask(ArrayRef<int> Mask) {
13727   size_t NumUndefs = 0;
13728   std::optional<int> UniqueElt;
13729   for (int Elt : Mask) {
13730     if (Elt == SM_SentinelUndef) {
13731       NumUndefs++;
13732       continue;
13733     }
13734     if (UniqueElt.has_value() && UniqueElt.value() != Elt)
13735       return false;
13736     UniqueElt = Elt;
13737   }
13738   // Make sure the element is repeated enough times by checking the number of
13739   // undefs is small.
13740   return NumUndefs <= Mask.size() / 2 && UniqueElt.has_value();
13741 }
13742 
13743 /// Generic routine to decompose a shuffle and blend into independent
13744 /// blends and permutes.
13745 ///
13746 /// This matches the extremely common pattern for handling combined
13747 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
13748 /// operations. It will try to pick the best arrangement of shuffles and
13749 /// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
13750 static SDValue lowerShuffleAsDecomposedShuffleMerge(
13751     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13752     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13753   int NumElts = Mask.size();
13754   int NumLanes = VT.getSizeInBits() / 128;
13755   int NumEltsPerLane = NumElts / NumLanes;
13756 
13757   // Shuffle the input elements into the desired positions in V1 and V2 and
13758   // unpack/blend them together.
13759   bool IsAlternating = true;
13760   SmallVector<int, 32> V1Mask(NumElts, -1);
13761   SmallVector<int, 32> V2Mask(NumElts, -1);
13762   SmallVector<int, 32> FinalMask(NumElts, -1);
13763   for (int i = 0; i < NumElts; ++i) {
13764     int M = Mask[i];
13765     if (M >= 0 && M < NumElts) {
13766       V1Mask[i] = M;
13767       FinalMask[i] = i;
13768       IsAlternating &= (i & 1) == 0;
13769     } else if (M >= NumElts) {
13770       V2Mask[i] = M - NumElts;
13771       FinalMask[i] = i + NumElts;
13772       IsAlternating &= (i & 1) == 1;
13773     }
13774   }
13775 
13776   // If we effectively only demand the 0'th element of \p Input, and not only
13777   // as 0'th element, then broadcast said input,
13778   // and change \p InputMask to be a no-op (identity) mask.
13779   auto canonicalizeBroadcastableInput = [DL, VT, &Subtarget,
13780                                          &DAG](SDValue &Input,
13781                                                MutableArrayRef<int> InputMask) {
13782     unsigned EltSizeInBits = Input.getScalarValueSizeInBits();
13783     if (!Subtarget.hasAVX2() && (!Subtarget.hasAVX() || EltSizeInBits < 32 ||
13784                                  !X86::mayFoldLoad(Input, Subtarget)))
13785       return;
13786     if (isNoopShuffleMask(InputMask))
13787       return;
13788     assert(isBroadcastShuffleMask(InputMask) &&
13789            "Expected to demand only the 0'th element.");
13790     Input = DAG.getNode(X86ISD::VBROADCAST, DL, VT, Input);
13791     for (auto I : enumerate(InputMask)) {
13792       int &InputMaskElt = I.value();
13793       if (InputMaskElt >= 0)
13794         InputMaskElt = I.index();
13795     }
13796   };
13797 
13798   // Currently, we may need to produce one shuffle per input, and blend results.
13799   // It is possible that the shuffle for one of the inputs is already a no-op.
13800   // See if we can simplify non-no-op shuffles into broadcasts,
13801   // which we consider to be strictly better than an arbitrary shuffle.
13802   if (isNoopOrBroadcastShuffleMask(V1Mask) &&
13803       isNoopOrBroadcastShuffleMask(V2Mask)) {
13804     canonicalizeBroadcastableInput(V1, V1Mask);
13805     canonicalizeBroadcastableInput(V2, V2Mask);
13806   }
13807 
13808   // Try to lower with the simpler initial blend/unpack/rotate strategies unless
13809   // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
13810   // the shuffle may be able to fold with a load or other benefit. However, when
13811   // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
13812   // pre-shuffle first is a better strategy.
13813   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
13814     // Only prefer immediate blends to unpack/rotate.
13815     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
13816                                                           DAG, true))
13817       return BlendPerm;
13818     // If either input vector provides only a single element which is repeated
13819     // multiple times, unpacking from both input vectors would generate worse
13820     // code. e.g. for
13821     // t5: v16i8 = vector_shuffle<16,0,16,1,16,2,16,3,16,4,16,5,16,6,16,7> t2, t4
13822     // it is better to process t4 first to create a vector of t4[0], then unpack
13823     // that vector with t2.
13824     if (!isSingleElementRepeatedMask(V1Mask) &&
13825         !isSingleElementRepeatedMask(V2Mask))
13826       if (SDValue UnpackPerm =
13827               lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask, DAG))
13828         return UnpackPerm;
13829     if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
13830             DL, VT, V1, V2, Mask, Subtarget, DAG))
13831       return RotatePerm;
13832     // Unpack/rotate failed - try again with variable blends.
13833     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
13834                                                           DAG))
13835       return BlendPerm;
13836     if (VT.getScalarSizeInBits() >= 32)
13837       if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
13838               DL, VT, V1, V2, Mask, Subtarget, DAG))
13839         return PermUnpack;
13840   }
13841 
13842   // If the final mask is an alternating blend of vXi8/vXi16, convert to an
13843   // UNPCKL(SHUFFLE, SHUFFLE) pattern.
13844   // TODO: It doesn't have to be alternating - but each lane mustn't have more
13845   // than half the elements coming from each source.
13846   if (IsAlternating && VT.getScalarSizeInBits() < 32) {
13847     V1Mask.assign(NumElts, -1);
13848     V2Mask.assign(NumElts, -1);
13849     FinalMask.assign(NumElts, -1);
13850     for (int i = 0; i != NumElts; i += NumEltsPerLane)
13851       for (int j = 0; j != NumEltsPerLane; ++j) {
13852         int M = Mask[i + j];
13853         if (M >= 0 && M < NumElts) {
13854           V1Mask[i + (j / 2)] = M;
13855           FinalMask[i + j] = i + (j / 2);
13856         } else if (M >= NumElts) {
13857           V2Mask[i + (j / 2)] = M - NumElts;
13858           FinalMask[i + j] = i + (j / 2) + NumElts;
13859         }
13860       }
13861   }
13862 
13863   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
13864   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
13865   return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
13866 }
13867 
13868 /// Try to lower a vector shuffle as a bit rotation.
13869 ///
13870 /// Look for a repeated rotation pattern in each sub group.
13871 /// Returns a ISD::ROTL element rotation amount or -1 if failed.
13872 static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
13873   int NumElts = Mask.size();
13874   assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
13875 
13876   int RotateAmt = -1;
13877   for (int i = 0; i != NumElts; i += NumSubElts) {
13878     for (int j = 0; j != NumSubElts; ++j) {
13879       int M = Mask[i + j];
13880       if (M < 0)
13881         continue;
13882       if (!isInRange(M, i, i + NumSubElts))
13883         return -1;
13884       int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
13885       if (0 <= RotateAmt && Offset != RotateAmt)
13886         return -1;
13887       RotateAmt = Offset;
13888     }
13889   }
13890   return RotateAmt;
13891 }
13892 
13893 static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
13894                                    const X86Subtarget &Subtarget,
13895                                    ArrayRef<int> Mask) {
13896   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
13897   assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
13898 
13899   // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
13900   int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
13901   int MaxSubElts = 64 / EltSizeInBits;
13902   for (int NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
13903     int RotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
13904     if (RotateAmt < 0)
13905       continue;
13906 
13907     int NumElts = Mask.size();
13908     MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
13909     RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
13910     return RotateAmt * EltSizeInBits;
13911   }
13912 
13913   return -1;
13914 }
13915 
13916 /// Lower shuffle using X86ISD::VROTLI rotations.
13917 static SDValue lowerShuffleAsBitRotate(const SDLoc &DL, MVT VT, SDValue V1,
13918                                        ArrayRef<int> Mask,
13919                                        const X86Subtarget &Subtarget,
13920                                        SelectionDAG &DAG) {
13921   // Only XOP + AVX512 targets have bit rotation instructions.
13922   // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
13923   bool IsLegal =
13924       (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
13925   if (!IsLegal && Subtarget.hasSSE3())
13926     return SDValue();
13927 
13928   MVT RotateVT;
13929   int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
13930                                           Subtarget, Mask);
13931   if (RotateAmt < 0)
13932     return SDValue();
13933 
13934   // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
13935   // expanded to OR(SRL,SHL), will be more efficient, but if they can
13936   // widen to vXi16 or more then existing lowering should will be better.
13937   if (!IsLegal) {
13938     if ((RotateAmt % 16) == 0)
13939       return SDValue();
13940     // TODO: Use getTargetVShiftByConstNode.
13941     unsigned ShlAmt = RotateAmt;
13942     unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
13943     V1 = DAG.getBitcast(RotateVT, V1);
13944     SDValue SHL = DAG.getNode(X86ISD::VSHLI, DL, RotateVT, V1,
13945                               DAG.getTargetConstant(ShlAmt, DL, MVT::i8));
13946     SDValue SRL = DAG.getNode(X86ISD::VSRLI, DL, RotateVT, V1,
13947                               DAG.getTargetConstant(SrlAmt, DL, MVT::i8));
13948     SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
13949     return DAG.getBitcast(VT, Rot);
13950   }
13951 
13952   SDValue Rot =
13953       DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
13954                   DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
13955   return DAG.getBitcast(VT, Rot);
13956 }
13957 
13958 /// Try to match a vector shuffle as an element rotation.
13959 ///
13960 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
13961 static int matchShuffleAsElementRotate(SDValue &V1, SDValue &V2,
13962                                        ArrayRef<int> Mask) {
13963   int NumElts = Mask.size();
13964 
13965   // We need to detect various ways of spelling a rotation:
13966   //   [11, 12, 13, 14, 15,  0,  1,  2]
13967   //   [-1, 12, 13, 14, -1, -1,  1, -1]
13968   //   [-1, -1, -1, -1, -1, -1,  1,  2]
13969   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
13970   //   [-1,  4,  5,  6, -1, -1,  9, -1]
13971   //   [-1,  4,  5,  6, -1, -1, -1, -1]
13972   int Rotation = 0;
13973   SDValue Lo, Hi;
13974   for (int i = 0; i < NumElts; ++i) {
13975     int M = Mask[i];
13976     assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
13977            "Unexpected mask index.");
13978     if (M < 0)
13979       continue;
13980 
13981     // Determine where a rotated vector would have started.
13982     int StartIdx = i - (M % NumElts);
13983     if (StartIdx == 0)
13984       // The identity rotation isn't interesting, stop.
13985       return -1;
13986 
13987     // If we found the tail of a vector the rotation must be the missing
13988     // front. If we found the head of a vector, it must be how much of the
13989     // head.
13990     int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
13991 
13992     if (Rotation == 0)
13993       Rotation = CandidateRotation;
13994     else if (Rotation != CandidateRotation)
13995       // The rotations don't match, so we can't match this mask.
13996       return -1;
13997 
13998     // Compute which value this mask is pointing at.
13999     SDValue MaskV = M < NumElts ? V1 : V2;
14000 
14001     // Compute which of the two target values this index should be assigned
14002     // to. This reflects whether the high elements are remaining or the low
14003     // elements are remaining.
14004     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
14005 
14006     // Either set up this value if we've not encountered it before, or check
14007     // that it remains consistent.
14008     if (!TargetV)
14009       TargetV = MaskV;
14010     else if (TargetV != MaskV)
14011       // This may be a rotation, but it pulls from the inputs in some
14012       // unsupported interleaving.
14013       return -1;
14014   }
14015 
14016   // Check that we successfully analyzed the mask, and normalize the results.
14017   assert(Rotation != 0 && "Failed to locate a viable rotation!");
14018   assert((Lo || Hi) && "Failed to find a rotated input vector!");
14019   if (!Lo)
14020     Lo = Hi;
14021   else if (!Hi)
14022     Hi = Lo;
14023 
14024   V1 = Lo;
14025   V2 = Hi;
14026 
14027   return Rotation;
14028 }
14029 
14030 /// Try to lower a vector shuffle as a byte rotation.
14031 ///
14032 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
14033 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
14034 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
14035 /// try to generically lower a vector shuffle through such an pattern. It
14036 /// does not check for the profitability of lowering either as PALIGNR or
14037 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
14038 /// This matches shuffle vectors that look like:
14039 ///
14040 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
14041 ///
14042 /// Essentially it concatenates V1 and V2, shifts right by some number of
14043 /// elements, and takes the low elements as the result. Note that while this is
14044 /// specified as a *right shift* because x86 is little-endian, it is a *left
14045 /// rotate* of the vector lanes.
14046 static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
14047                                     ArrayRef<int> Mask) {
14048   // Don't accept any shuffles with zero elements.
14049   if (isAnyZero(Mask))
14050     return -1;
14051 
14052   // PALIGNR works on 128-bit lanes.
14053   SmallVector<int, 16> RepeatedMask;
14054   if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
14055     return -1;
14056 
14057   int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
14058   if (Rotation <= 0)
14059     return -1;
14060 
14061   // PALIGNR rotates bytes, so we need to scale the
14062   // rotation based on how many bytes are in the vector lane.
14063   int NumElts = RepeatedMask.size();
14064   int Scale = 16 / NumElts;
14065   return Rotation * Scale;
14066 }
14067 
14068 static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
14069                                         SDValue V2, ArrayRef<int> Mask,
14070                                         const X86Subtarget &Subtarget,
14071                                         SelectionDAG &DAG) {
14072   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
14073 
14074   SDValue Lo = V1, Hi = V2;
14075   int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
14076   if (ByteRotation <= 0)
14077     return SDValue();
14078 
14079   // Cast the inputs to i8 vector of correct length to match PALIGNR or
14080   // PSLLDQ/PSRLDQ.
14081   MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
14082   Lo = DAG.getBitcast(ByteVT, Lo);
14083   Hi = DAG.getBitcast(ByteVT, Hi);
14084 
14085   // SSSE3 targets can use the palignr instruction.
14086   if (Subtarget.hasSSSE3()) {
14087     assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
14088            "512-bit PALIGNR requires BWI instructions");
14089     return DAG.getBitcast(
14090         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
14091                         DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
14092   }
14093 
14094   assert(VT.is128BitVector() &&
14095          "Rotate-based lowering only supports 128-bit lowering!");
14096   assert(Mask.size() <= 16 &&
14097          "Can shuffle at most 16 bytes in a 128-bit vector!");
14098   assert(ByteVT == MVT::v16i8 &&
14099          "SSE2 rotate lowering only needed for v16i8!");
14100 
14101   // Default SSE2 implementation
14102   int LoByteShift = 16 - ByteRotation;
14103   int HiByteShift = ByteRotation;
14104 
14105   SDValue LoShift =
14106       DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
14107                   DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
14108   SDValue HiShift =
14109       DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
14110                   DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
14111   return DAG.getBitcast(VT,
14112                         DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
14113 }
14114 
14115 /// Try to lower a vector shuffle as a dword/qword rotation.
14116 ///
14117 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
14118 /// rotation of the concatenation of two vectors; This routine will
14119 /// try to generically lower a vector shuffle through such an pattern.
14120 ///
14121 /// Essentially it concatenates V1 and V2, shifts right by some number of
14122 /// elements, and takes the low elements as the result. Note that while this is
14123 /// specified as a *right shift* because x86 is little-endian, it is a *left
14124 /// rotate* of the vector lanes.
14125 static SDValue lowerShuffleAsVALIGN(const SDLoc &DL, MVT VT, SDValue V1,
14126                                     SDValue V2, ArrayRef<int> Mask,
14127                                     const X86Subtarget &Subtarget,
14128                                     SelectionDAG &DAG) {
14129   assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
14130          "Only 32-bit and 64-bit elements are supported!");
14131 
14132   // 128/256-bit vectors are only supported with VLX.
14133   assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
14134          && "VLX required for 128/256-bit vectors");
14135 
14136   SDValue Lo = V1, Hi = V2;
14137   int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
14138   if (Rotation <= 0)
14139     return SDValue();
14140 
14141   return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
14142                      DAG.getTargetConstant(Rotation, DL, MVT::i8));
14143 }
14144 
14145 /// Try to lower a vector shuffle as a byte shift sequence.
14146 static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
14147                                            SDValue V2, ArrayRef<int> Mask,
14148                                            const APInt &Zeroable,
14149                                            const X86Subtarget &Subtarget,
14150                                            SelectionDAG &DAG) {
14151   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
14152   assert(VT.is128BitVector() && "Only 128-bit vectors supported");
14153 
14154   // We need a shuffle that has zeros at one/both ends and a sequential
14155   // shuffle from one source within.
14156   unsigned ZeroLo = Zeroable.countr_one();
14157   unsigned ZeroHi = Zeroable.countl_one();
14158   if (!ZeroLo && !ZeroHi)
14159     return SDValue();
14160 
14161   unsigned NumElts = Mask.size();
14162   unsigned Len = NumElts - (ZeroLo + ZeroHi);
14163   if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
14164     return SDValue();
14165 
14166   unsigned Scale = VT.getScalarSizeInBits() / 8;
14167   ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
14168   if (!isUndefOrInRange(StubMask, 0, NumElts) &&
14169       !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
14170     return SDValue();
14171 
14172   SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
14173   Res = DAG.getBitcast(MVT::v16i8, Res);
14174 
14175   // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
14176   // inner sequential set of elements, possibly offset:
14177   // 01234567 --> zzzzzz01 --> 1zzzzzzz
14178   // 01234567 --> 4567zzzz --> zzzzz456
14179   // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
14180   if (ZeroLo == 0) {
14181     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
14182     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
14183                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
14184     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
14185                       DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
14186   } else if (ZeroHi == 0) {
14187     unsigned Shift = Mask[ZeroLo] % NumElts;
14188     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
14189                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
14190     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
14191                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
14192   } else if (!Subtarget.hasSSSE3()) {
14193     // If we don't have PSHUFB then its worth avoiding an AND constant mask
14194     // by performing 3 byte shifts. Shuffle combining can kick in above that.
14195     // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
14196     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
14197     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
14198                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
14199     Shift += Mask[ZeroLo] % NumElts;
14200     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
14201                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
14202     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
14203                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
14204   } else
14205     return SDValue();
14206 
14207   return DAG.getBitcast(VT, Res);
14208 }
14209 
14210 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
14211 ///
14212 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
14213 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
14214 /// matches elements from one of the input vectors shuffled to the left or
14215 /// right with zeroable elements 'shifted in'. It handles both the strictly
14216 /// bit-wise element shifts and the byte shift across an entire 128-bit double
14217 /// quad word lane.
14218 ///
14219 /// PSHL : (little-endian) left bit shift.
14220 /// [ zz, 0, zz,  2 ]
14221 /// [ -1, 4, zz, -1 ]
14222 /// PSRL : (little-endian) right bit shift.
14223 /// [  1, zz,  3, zz]
14224 /// [ -1, -1,  7, zz]
14225 /// PSLLDQ : (little-endian) left byte shift
14226 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
14227 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
14228 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
14229 /// PSRLDQ : (little-endian) right byte shift
14230 /// [  5, 6,  7, zz, zz, zz, zz, zz]
14231 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
14232 /// [  1, 2, -1, -1, -1, -1, zz, zz]
14233 static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
14234                                unsigned ScalarSizeInBits, ArrayRef<int> Mask,
14235                                int MaskOffset, const APInt &Zeroable,
14236                                const X86Subtarget &Subtarget) {
14237   int Size = Mask.size();
14238   unsigned SizeInBits = Size * ScalarSizeInBits;
14239 
14240   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
14241     for (int i = 0; i < Size; i += Scale)
14242       for (int j = 0; j < Shift; ++j)
14243         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
14244           return false;
14245 
14246     return true;
14247   };
14248 
14249   auto MatchShift = [&](int Shift, int Scale, bool Left) {
14250     for (int i = 0; i != Size; i += Scale) {
14251       unsigned Pos = Left ? i + Shift : i;
14252       unsigned Low = Left ? i : i + Shift;
14253       unsigned Len = Scale - Shift;
14254       if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
14255         return -1;
14256     }
14257 
14258     int ShiftEltBits = ScalarSizeInBits * Scale;
14259     bool ByteShift = ShiftEltBits > 64;
14260     Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
14261                   : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
14262     int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
14263 
14264     // Normalize the scale for byte shifts to still produce an i64 element
14265     // type.
14266     Scale = ByteShift ? Scale / 2 : Scale;
14267 
14268     // We need to round trip through the appropriate type for the shift.
14269     MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
14270     ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
14271                         : MVT::getVectorVT(ShiftSVT, Size / Scale);
14272     return (int)ShiftAmt;
14273   };
14274 
14275   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
14276   // keep doubling the size of the integer elements up to that. We can
14277   // then shift the elements of the integer vector by whole multiples of
14278   // their width within the elements of the larger integer vector. Test each
14279   // multiple to see if we can find a match with the moved element indices
14280   // and that the shifted in elements are all zeroable.
14281   unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
14282   for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
14283     for (int Shift = 1; Shift != Scale; ++Shift)
14284       for (bool Left : {true, false})
14285         if (CheckZeros(Shift, Scale, Left)) {
14286           int ShiftAmt = MatchShift(Shift, Scale, Left);
14287           if (0 < ShiftAmt)
14288             return ShiftAmt;
14289         }
14290 
14291   // no match
14292   return -1;
14293 }
14294 
14295 static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
14296                                    SDValue V2, ArrayRef<int> Mask,
14297                                    const APInt &Zeroable,
14298                                    const X86Subtarget &Subtarget,
14299                                    SelectionDAG &DAG, bool BitwiseOnly) {
14300   int Size = Mask.size();
14301   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
14302 
14303   MVT ShiftVT;
14304   SDValue V = V1;
14305   unsigned Opcode;
14306 
14307   // Try to match shuffle against V1 shift.
14308   int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
14309                                      Mask, 0, Zeroable, Subtarget);
14310 
14311   // If V1 failed, try to match shuffle against V2 shift.
14312   if (ShiftAmt < 0) {
14313     ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
14314                                    Mask, Size, Zeroable, Subtarget);
14315     V = V2;
14316   }
14317 
14318   if (ShiftAmt < 0)
14319     return SDValue();
14320 
14321   if (BitwiseOnly && (Opcode == X86ISD::VSHLDQ || Opcode == X86ISD::VSRLDQ))
14322     return SDValue();
14323 
14324   assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
14325          "Illegal integer vector type");
14326   V = DAG.getBitcast(ShiftVT, V);
14327   V = DAG.getNode(Opcode, DL, ShiftVT, V,
14328                   DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
14329   return DAG.getBitcast(VT, V);
14330 }
14331 
14332 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
14333 // Remainder of lower half result is zero and upper half is all undef.
14334 static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
14335                                 ArrayRef<int> Mask, uint64_t &BitLen,
14336                                 uint64_t &BitIdx, const APInt &Zeroable) {
14337   int Size = Mask.size();
14338   int HalfSize = Size / 2;
14339   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
14340   assert(!Zeroable.isAllOnes() && "Fully zeroable shuffle mask");
14341 
14342   // Upper half must be undefined.
14343   if (!isUndefUpperHalf(Mask))
14344     return false;
14345 
14346   // Determine the extraction length from the part of the
14347   // lower half that isn't zeroable.
14348   int Len = HalfSize;
14349   for (; Len > 0; --Len)
14350     if (!Zeroable[Len - 1])
14351       break;
14352   assert(Len > 0 && "Zeroable shuffle mask");
14353 
14354   // Attempt to match first Len sequential elements from the lower half.
14355   SDValue Src;
14356   int Idx = -1;
14357   for (int i = 0; i != Len; ++i) {
14358     int M = Mask[i];
14359     if (M == SM_SentinelUndef)
14360       continue;
14361     SDValue &V = (M < Size ? V1 : V2);
14362     M = M % Size;
14363 
14364     // The extracted elements must start at a valid index and all mask
14365     // elements must be in the lower half.
14366     if (i > M || M >= HalfSize)
14367       return false;
14368 
14369     if (Idx < 0 || (Src == V && Idx == (M - i))) {
14370       Src = V;
14371       Idx = M - i;
14372       continue;
14373     }
14374     return false;
14375   }
14376 
14377   if (!Src || Idx < 0)
14378     return false;
14379 
14380   assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
14381   BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
14382   BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
14383   V1 = Src;
14384   return true;
14385 }
14386 
14387 // INSERTQ: Extract lowest Len elements from lower half of second source and
14388 // insert over first source, starting at Idx.
14389 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
14390 static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
14391                                   ArrayRef<int> Mask, uint64_t &BitLen,
14392                                   uint64_t &BitIdx) {
14393   int Size = Mask.size();
14394   int HalfSize = Size / 2;
14395   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
14396 
14397   // Upper half must be undefined.
14398   if (!isUndefUpperHalf(Mask))
14399     return false;
14400 
14401   for (int Idx = 0; Idx != HalfSize; ++Idx) {
14402     SDValue Base;
14403 
14404     // Attempt to match first source from mask before insertion point.
14405     if (isUndefInRange(Mask, 0, Idx)) {
14406       /* EMPTY */
14407     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
14408       Base = V1;
14409     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
14410       Base = V2;
14411     } else {
14412       continue;
14413     }
14414 
14415     // Extend the extraction length looking to match both the insertion of
14416     // the second source and the remaining elements of the first.
14417     for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
14418       SDValue Insert;
14419       int Len = Hi - Idx;
14420 
14421       // Match insertion.
14422       if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
14423         Insert = V1;
14424       } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
14425         Insert = V2;
14426       } else {
14427         continue;
14428       }
14429 
14430       // Match the remaining elements of the lower half.
14431       if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
14432         /* EMPTY */
14433       } else if ((!Base || (Base == V1)) &&
14434                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
14435         Base = V1;
14436       } else if ((!Base || (Base == V2)) &&
14437                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
14438                                             Size + Hi)) {
14439         Base = V2;
14440       } else {
14441         continue;
14442       }
14443 
14444       BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
14445       BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
14446       V1 = Base;
14447       V2 = Insert;
14448       return true;
14449     }
14450   }
14451 
14452   return false;
14453 }
14454 
14455 /// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
14456 static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
14457                                      SDValue V2, ArrayRef<int> Mask,
14458                                      const APInt &Zeroable, SelectionDAG &DAG) {
14459   uint64_t BitLen, BitIdx;
14460   if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
14461     return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
14462                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
14463                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
14464 
14465   if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
14466     return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
14467                        V2 ? V2 : DAG.getUNDEF(VT),
14468                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
14469                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
14470 
14471   return SDValue();
14472 }
14473 
14474 /// Lower a vector shuffle as a zero or any extension.
14475 ///
14476 /// Given a specific number of elements, element bit width, and extension
14477 /// stride, produce either a zero or any extension based on the available
14478 /// features of the subtarget. The extended elements are consecutive and
14479 /// begin and can start from an offsetted element index in the input; to
14480 /// avoid excess shuffling the offset must either being in the bottom lane
14481 /// or at the start of a higher lane. All extended elements must be from
14482 /// the same lane.
14483 static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
14484     const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
14485     ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14486   assert(Scale > 1 && "Need a scale to extend.");
14487   int EltBits = VT.getScalarSizeInBits();
14488   int NumElements = VT.getVectorNumElements();
14489   int NumEltsPerLane = 128 / EltBits;
14490   int OffsetLane = Offset / NumEltsPerLane;
14491   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14492          "Only 8, 16, and 32 bit elements can be extended.");
14493   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
14494   assert(0 <= Offset && "Extension offset must be positive.");
14495   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
14496          "Extension offset must be in the first lane or start an upper lane.");
14497 
14498   // Check that an index is in same lane as the base offset.
14499   auto SafeOffset = [&](int Idx) {
14500     return OffsetLane == (Idx / NumEltsPerLane);
14501   };
14502 
14503   // Shift along an input so that the offset base moves to the first element.
14504   auto ShuffleOffset = [&](SDValue V) {
14505     if (!Offset)
14506       return V;
14507 
14508     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
14509     for (int i = 0; i * Scale < NumElements; ++i) {
14510       int SrcIdx = i + Offset;
14511       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
14512     }
14513     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
14514   };
14515 
14516   // Found a valid a/zext mask! Try various lowering strategies based on the
14517   // input type and available ISA extensions.
14518   if (Subtarget.hasSSE41()) {
14519     // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
14520     // PUNPCK will catch this in a later shuffle match.
14521     if (Offset && Scale == 2 && VT.is128BitVector())
14522       return SDValue();
14523     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
14524                                  NumElements / Scale);
14525     InputV = DAG.getBitcast(VT, InputV);
14526     InputV = ShuffleOffset(InputV);
14527     InputV = getEXTEND_VECTOR_INREG(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND,
14528                                     DL, ExtVT, InputV, DAG);
14529     return DAG.getBitcast(VT, InputV);
14530   }
14531 
14532   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
14533   InputV = DAG.getBitcast(VT, InputV);
14534 
14535   // For any extends we can cheat for larger element sizes and use shuffle
14536   // instructions that can fold with a load and/or copy.
14537   if (AnyExt && EltBits == 32) {
14538     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
14539                          -1};
14540     return DAG.getBitcast(
14541         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
14542                         DAG.getBitcast(MVT::v4i32, InputV),
14543                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14544   }
14545   if (AnyExt && EltBits == 16 && Scale > 2) {
14546     int PSHUFDMask[4] = {Offset / 2, -1,
14547                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
14548     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
14549                          DAG.getBitcast(MVT::v4i32, InputV),
14550                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
14551     int PSHUFWMask[4] = {1, -1, -1, -1};
14552     unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
14553     return DAG.getBitcast(
14554         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
14555                         DAG.getBitcast(MVT::v8i16, InputV),
14556                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
14557   }
14558 
14559   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
14560   // to 64-bits.
14561   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
14562     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
14563     assert(VT.is128BitVector() && "Unexpected vector width!");
14564 
14565     int LoIdx = Offset * EltBits;
14566     SDValue Lo = DAG.getBitcast(
14567         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
14568                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
14569                                 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
14570 
14571     if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
14572       return DAG.getBitcast(VT, Lo);
14573 
14574     int HiIdx = (Offset + 1) * EltBits;
14575     SDValue Hi = DAG.getBitcast(
14576         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
14577                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
14578                                 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
14579     return DAG.getBitcast(VT,
14580                           DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
14581   }
14582 
14583   // If this would require more than 2 unpack instructions to expand, use
14584   // pshufb when available. We can only use more than 2 unpack instructions
14585   // when zero extending i8 elements which also makes it easier to use pshufb.
14586   if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
14587     assert(NumElements == 16 && "Unexpected byte vector width!");
14588     SDValue PSHUFBMask[16];
14589     for (int i = 0; i < 16; ++i) {
14590       int Idx = Offset + (i / Scale);
14591       if ((i % Scale == 0 && SafeOffset(Idx))) {
14592         PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
14593         continue;
14594       }
14595       PSHUFBMask[i] =
14596           AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
14597     }
14598     InputV = DAG.getBitcast(MVT::v16i8, InputV);
14599     return DAG.getBitcast(
14600         VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
14601                         DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
14602   }
14603 
14604   // If we are extending from an offset, ensure we start on a boundary that
14605   // we can unpack from.
14606   int AlignToUnpack = Offset % (NumElements / Scale);
14607   if (AlignToUnpack) {
14608     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
14609     for (int i = AlignToUnpack; i < NumElements; ++i)
14610       ShMask[i - AlignToUnpack] = i;
14611     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
14612     Offset -= AlignToUnpack;
14613   }
14614 
14615   // Otherwise emit a sequence of unpacks.
14616   do {
14617     unsigned UnpackLoHi = X86ISD::UNPCKL;
14618     if (Offset >= (NumElements / 2)) {
14619       UnpackLoHi = X86ISD::UNPCKH;
14620       Offset -= (NumElements / 2);
14621     }
14622 
14623     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
14624     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
14625                          : getZeroVector(InputVT, Subtarget, DAG, DL);
14626     InputV = DAG.getBitcast(InputVT, InputV);
14627     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
14628     Scale /= 2;
14629     EltBits *= 2;
14630     NumElements /= 2;
14631   } while (Scale > 1);
14632   return DAG.getBitcast(VT, InputV);
14633 }
14634 
14635 /// Try to lower a vector shuffle as a zero extension on any microarch.
14636 ///
14637 /// This routine will try to do everything in its power to cleverly lower
14638 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
14639 /// check for the profitability of this lowering,  it tries to aggressively
14640 /// match this pattern. It will use all of the micro-architectural details it
14641 /// can to emit an efficient lowering. It handles both blends with all-zero
14642 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
14643 /// masking out later).
14644 ///
14645 /// The reason we have dedicated lowering for zext-style shuffles is that they
14646 /// are both incredibly common and often quite performance sensitive.
14647 static SDValue lowerShuffleAsZeroOrAnyExtend(
14648     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14649     const APInt &Zeroable, const X86Subtarget &Subtarget,
14650     SelectionDAG &DAG) {
14651   int Bits = VT.getSizeInBits();
14652   int NumLanes = Bits / 128;
14653   int NumElements = VT.getVectorNumElements();
14654   int NumEltsPerLane = NumElements / NumLanes;
14655   assert(VT.getScalarSizeInBits() <= 32 &&
14656          "Exceeds 32-bit integer zero extension limit");
14657   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
14658 
14659   // Define a helper function to check a particular ext-scale and lower to it if
14660   // valid.
14661   auto Lower = [&](int Scale) -> SDValue {
14662     SDValue InputV;
14663     bool AnyExt = true;
14664     int Offset = 0;
14665     int Matches = 0;
14666     for (int i = 0; i < NumElements; ++i) {
14667       int M = Mask[i];
14668       if (M < 0)
14669         continue; // Valid anywhere but doesn't tell us anything.
14670       if (i % Scale != 0) {
14671         // Each of the extended elements need to be zeroable.
14672         if (!Zeroable[i])
14673           return SDValue();
14674 
14675         // We no longer are in the anyext case.
14676         AnyExt = false;
14677         continue;
14678       }
14679 
14680       // Each of the base elements needs to be consecutive indices into the
14681       // same input vector.
14682       SDValue V = M < NumElements ? V1 : V2;
14683       M = M % NumElements;
14684       if (!InputV) {
14685         InputV = V;
14686         Offset = M - (i / Scale);
14687       } else if (InputV != V)
14688         return SDValue(); // Flip-flopping inputs.
14689 
14690       // Offset must start in the lowest 128-bit lane or at the start of an
14691       // upper lane.
14692       // FIXME: Is it ever worth allowing a negative base offset?
14693       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
14694             (Offset % NumEltsPerLane) == 0))
14695         return SDValue();
14696 
14697       // If we are offsetting, all referenced entries must come from the same
14698       // lane.
14699       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
14700         return SDValue();
14701 
14702       if ((M % NumElements) != (Offset + (i / Scale)))
14703         return SDValue(); // Non-consecutive strided elements.
14704       Matches++;
14705     }
14706 
14707     // If we fail to find an input, we have a zero-shuffle which should always
14708     // have already been handled.
14709     // FIXME: Maybe handle this here in case during blending we end up with one?
14710     if (!InputV)
14711       return SDValue();
14712 
14713     // If we are offsetting, don't extend if we only match a single input, we
14714     // can always do better by using a basic PSHUF or PUNPCK.
14715     if (Offset != 0 && Matches < 2)
14716       return SDValue();
14717 
14718     return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
14719                                                  InputV, Mask, Subtarget, DAG);
14720   };
14721 
14722   // The widest scale possible for extending is to a 64-bit integer.
14723   assert(Bits % 64 == 0 &&
14724          "The number of bits in a vector must be divisible by 64 on x86!");
14725   int NumExtElements = Bits / 64;
14726 
14727   // Each iteration, try extending the elements half as much, but into twice as
14728   // many elements.
14729   for (; NumExtElements < NumElements; NumExtElements *= 2) {
14730     assert(NumElements % NumExtElements == 0 &&
14731            "The input vector size must be divisible by the extended size.");
14732     if (SDValue V = Lower(NumElements / NumExtElements))
14733       return V;
14734   }
14735 
14736   // General extends failed, but 128-bit vectors may be able to use MOVQ.
14737   if (Bits != 128)
14738     return SDValue();
14739 
14740   // Returns one of the source operands if the shuffle can be reduced to a
14741   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
14742   auto CanZExtLowHalf = [&]() {
14743     for (int i = NumElements / 2; i != NumElements; ++i)
14744       if (!Zeroable[i])
14745         return SDValue();
14746     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
14747       return V1;
14748     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
14749       return V2;
14750     return SDValue();
14751   };
14752 
14753   if (SDValue V = CanZExtLowHalf()) {
14754     V = DAG.getBitcast(MVT::v2i64, V);
14755     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
14756     return DAG.getBitcast(VT, V);
14757   }
14758 
14759   // No viable ext lowering found.
14760   return SDValue();
14761 }
14762 
14763 /// Try to get a scalar value for a specific element of a vector.
14764 ///
14765 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
14766 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
14767                                               SelectionDAG &DAG) {
14768   MVT VT = V.getSimpleValueType();
14769   MVT EltVT = VT.getVectorElementType();
14770   V = peekThroughBitcasts(V);
14771 
14772   // If the bitcasts shift the element size, we can't extract an equivalent
14773   // element from it.
14774   MVT NewVT = V.getSimpleValueType();
14775   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
14776     return SDValue();
14777 
14778   if (V.getOpcode() == ISD::BUILD_VECTOR ||
14779       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
14780     // Ensure the scalar operand is the same size as the destination.
14781     // FIXME: Add support for scalar truncation where possible.
14782     SDValue S = V.getOperand(Idx);
14783     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
14784       return DAG.getBitcast(EltVT, S);
14785   }
14786 
14787   return SDValue();
14788 }
14789 
14790 /// Helper to test for a load that can be folded with x86 shuffles.
14791 ///
14792 /// This is particularly important because the set of instructions varies
14793 /// significantly based on whether the operand is a load or not.
14794 static bool isShuffleFoldableLoad(SDValue V) {
14795   return V->hasOneUse() &&
14796          ISD::isNON_EXTLoad(peekThroughOneUseBitcasts(V).getNode());
14797 }
14798 
14799 template<typename T>
14800 static bool isSoftF16(T VT, const X86Subtarget &Subtarget) {
14801   T EltVT = VT.getScalarType();
14802   return EltVT == MVT::bf16 || (EltVT == MVT::f16 && !Subtarget.hasFP16());
14803 }
14804 
14805 /// Try to lower insertion of a single element into a zero vector.
14806 ///
14807 /// This is a common pattern that we have especially efficient patterns to lower
14808 /// across all subtarget feature sets.
14809 static SDValue lowerShuffleAsElementInsertion(
14810     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14811     const APInt &Zeroable, const X86Subtarget &Subtarget,
14812     SelectionDAG &DAG) {
14813   MVT ExtVT = VT;
14814   MVT EltVT = VT.getVectorElementType();
14815   unsigned NumElts = VT.getVectorNumElements();
14816   unsigned EltBits = VT.getScalarSizeInBits();
14817 
14818   if (isSoftF16(EltVT, Subtarget))
14819     return SDValue();
14820 
14821   int V2Index =
14822       find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
14823       Mask.begin();
14824   bool IsV1Constant = getTargetConstantFromNode(V1) != nullptr;
14825   bool IsV1Zeroable = true;
14826   for (int i = 0, Size = Mask.size(); i < Size; ++i)
14827     if (i != V2Index && !Zeroable[i]) {
14828       IsV1Zeroable = false;
14829       break;
14830     }
14831 
14832   // Bail if a non-zero V1 isn't used in place.
14833   if (!IsV1Zeroable) {
14834     SmallVector<int, 8> V1Mask(Mask);
14835     V1Mask[V2Index] = -1;
14836     if (!isNoopShuffleMask(V1Mask))
14837       return SDValue();
14838   }
14839 
14840   // Check for a single input from a SCALAR_TO_VECTOR node.
14841   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
14842   // all the smarts here sunk into that routine. However, the current
14843   // lowering of BUILD_VECTOR makes that nearly impossible until the old
14844   // vector shuffle lowering is dead.
14845   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
14846                                                DAG);
14847   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
14848     // We need to zext the scalar if it is smaller than an i32.
14849     V2S = DAG.getBitcast(EltVT, V2S);
14850     if (EltVT == MVT::i8 || (EltVT == MVT::i16 && !Subtarget.hasFP16())) {
14851       // Using zext to expand a narrow element won't work for non-zero
14852       // insertions. But we can use a masked constant vector if we're
14853       // inserting V2 into the bottom of V1.
14854       if (!IsV1Zeroable && !(IsV1Constant && V2Index == 0))
14855         return SDValue();
14856 
14857       // Zero-extend directly to i32.
14858       ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
14859       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
14860 
14861       // If we're inserting into a constant, mask off the inserted index
14862       // and OR with the zero-extended scalar.
14863       if (!IsV1Zeroable) {
14864         SmallVector<APInt> Bits(NumElts, APInt::getAllOnes(EltBits));
14865         Bits[V2Index] = APInt::getZero(EltBits);
14866         SDValue BitMask = getConstVector(Bits, VT, DAG, DL);
14867         V1 = DAG.getNode(ISD::AND, DL, VT, V1, BitMask);
14868         V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
14869         V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2));
14870         return DAG.getNode(ISD::OR, DL, VT, V1, V2);
14871       }
14872     }
14873     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
14874   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
14875              EltVT == MVT::i16) {
14876     // Either not inserting from the low element of the input or the input
14877     // element size is too small to use VZEXT_MOVL to clear the high bits.
14878     return SDValue();
14879   }
14880 
14881   if (!IsV1Zeroable) {
14882     // If V1 can't be treated as a zero vector we have fewer options to lower
14883     // this. We can't support integer vectors or non-zero targets cheaply.
14884     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
14885     if (!VT.isFloatingPoint() || V2Index != 0)
14886       return SDValue();
14887     if (!VT.is128BitVector())
14888       return SDValue();
14889 
14890     // Otherwise, use MOVSD, MOVSS or MOVSH.
14891     unsigned MovOpc = 0;
14892     if (EltVT == MVT::f16)
14893       MovOpc = X86ISD::MOVSH;
14894     else if (EltVT == MVT::f32)
14895       MovOpc = X86ISD::MOVSS;
14896     else if (EltVT == MVT::f64)
14897       MovOpc = X86ISD::MOVSD;
14898     else
14899       llvm_unreachable("Unsupported floating point element type to handle!");
14900     return DAG.getNode(MovOpc, DL, ExtVT, V1, V2);
14901   }
14902 
14903   // This lowering only works for the low element with floating point vectors.
14904   if (VT.isFloatingPoint() && V2Index != 0)
14905     return SDValue();
14906 
14907   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
14908   if (ExtVT != VT)
14909     V2 = DAG.getBitcast(VT, V2);
14910 
14911   if (V2Index != 0) {
14912     // If we have 4 or fewer lanes we can cheaply shuffle the element into
14913     // the desired position. Otherwise it is more efficient to do a vector
14914     // shift left. We know that we can do a vector shift left because all
14915     // the inputs are zero.
14916     if (VT.isFloatingPoint() || NumElts <= 4) {
14917       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
14918       V2Shuffle[V2Index] = 0;
14919       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
14920     } else {
14921       V2 = DAG.getBitcast(MVT::v16i8, V2);
14922       V2 = DAG.getNode(
14923           X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
14924           DAG.getTargetConstant(V2Index * EltBits / 8, DL, MVT::i8));
14925       V2 = DAG.getBitcast(VT, V2);
14926     }
14927   }
14928   return V2;
14929 }
14930 
14931 /// Try to lower broadcast of a single - truncated - integer element,
14932 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
14933 ///
14934 /// This assumes we have AVX2.
14935 static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
14936                                             int BroadcastIdx,
14937                                             const X86Subtarget &Subtarget,
14938                                             SelectionDAG &DAG) {
14939   assert(Subtarget.hasAVX2() &&
14940          "We can only lower integer broadcasts with AVX2!");
14941 
14942   MVT EltVT = VT.getVectorElementType();
14943   MVT V0VT = V0.getSimpleValueType();
14944 
14945   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
14946   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
14947 
14948   MVT V0EltVT = V0VT.getVectorElementType();
14949   if (!V0EltVT.isInteger())
14950     return SDValue();
14951 
14952   const unsigned EltSize = EltVT.getSizeInBits();
14953   const unsigned V0EltSize = V0EltVT.getSizeInBits();
14954 
14955   // This is only a truncation if the original element type is larger.
14956   if (V0EltSize <= EltSize)
14957     return SDValue();
14958 
14959   assert(((V0EltSize % EltSize) == 0) &&
14960          "Scalar type sizes must all be powers of 2 on x86!");
14961 
14962   const unsigned V0Opc = V0.getOpcode();
14963   const unsigned Scale = V0EltSize / EltSize;
14964   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
14965 
14966   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
14967       V0Opc != ISD::BUILD_VECTOR)
14968     return SDValue();
14969 
14970   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
14971 
14972   // If we're extracting non-least-significant bits, shift so we can truncate.
14973   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
14974   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
14975   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
14976   if (const int OffsetIdx = BroadcastIdx % Scale)
14977     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
14978                          DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
14979 
14980   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
14981                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
14982 }
14983 
14984 /// Test whether this can be lowered with a single SHUFPS instruction.
14985 ///
14986 /// This is used to disable more specialized lowerings when the shufps lowering
14987 /// will happen to be efficient.
14988 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
14989   // This routine only handles 128-bit shufps.
14990   assert(Mask.size() == 4 && "Unsupported mask size!");
14991   assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
14992   assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
14993   assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
14994   assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
14995 
14996   // To lower with a single SHUFPS we need to have the low half and high half
14997   // each requiring a single input.
14998   if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
14999     return false;
15000   if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
15001     return false;
15002 
15003   return true;
15004 }
15005 
15006 /// Test whether the specified input (0 or 1) is in-place blended by the
15007 /// given mask.
15008 ///
15009 /// This returns true if the elements from a particular input are already in the
15010 /// slot required by the given mask and require no permutation.
15011 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
15012   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
15013   int Size = Mask.size();
15014   for (int i = 0; i < Size; ++i)
15015     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
15016       return false;
15017 
15018   return true;
15019 }
15020 
15021 /// If we are extracting two 128-bit halves of a vector and shuffling the
15022 /// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
15023 /// multi-shuffle lowering.
15024 static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
15025                                              SDValue N1, ArrayRef<int> Mask,
15026                                              SelectionDAG &DAG) {
15027   MVT VT = N0.getSimpleValueType();
15028   assert((VT.is128BitVector() &&
15029           (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
15030          "VPERM* family of shuffles requires 32-bit or 64-bit elements");
15031 
15032   // Check that both sources are extracts of the same source vector.
15033   if (N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
15034       N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
15035       N0.getOperand(0) != N1.getOperand(0) ||
15036       !N0.hasOneUse() || !N1.hasOneUse())
15037     return SDValue();
15038 
15039   SDValue WideVec = N0.getOperand(0);
15040   MVT WideVT = WideVec.getSimpleValueType();
15041   if (!WideVT.is256BitVector())
15042     return SDValue();
15043 
15044   // Match extracts of each half of the wide source vector. Commute the shuffle
15045   // if the extract of the low half is N1.
15046   unsigned NumElts = VT.getVectorNumElements();
15047   SmallVector<int, 4> NewMask(Mask);
15048   const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
15049   const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
15050   if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
15051     ShuffleVectorSDNode::commuteMask(NewMask);
15052   else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
15053     return SDValue();
15054 
15055   // Final bailout: if the mask is simple, we are better off using an extract
15056   // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
15057   // because that avoids a constant load from memory.
15058   if (NumElts == 4 &&
15059       (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask, DAG)))
15060     return SDValue();
15061 
15062   // Extend the shuffle mask with undef elements.
15063   NewMask.append(NumElts, -1);
15064 
15065   // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
15066   SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
15067                                       NewMask);
15068   // This is free: ymm -> xmm.
15069   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
15070                      DAG.getIntPtrConstant(0, DL));
15071 }
15072 
15073 /// Try to lower broadcast of a single element.
15074 ///
15075 /// For convenience, this code also bundles all of the subtarget feature set
15076 /// filtering. While a little annoying to re-dispatch on type here, there isn't
15077 /// a convenient way to factor it out.
15078 static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
15079                                        SDValue V2, ArrayRef<int> Mask,
15080                                        const X86Subtarget &Subtarget,
15081                                        SelectionDAG &DAG) {
15082   MVT EltVT = VT.getVectorElementType();
15083   if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
15084         (Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
15085         (Subtarget.hasAVX2() && (VT.isInteger() || EltVT == MVT::f16))))
15086     return SDValue();
15087 
15088   // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
15089   // we can only broadcast from a register with AVX2.
15090   unsigned NumEltBits = VT.getScalarSizeInBits();
15091   unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
15092                         ? X86ISD::MOVDDUP
15093                         : X86ISD::VBROADCAST;
15094   bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
15095 
15096   // Check that the mask is a broadcast.
15097   int BroadcastIdx = getSplatIndex(Mask);
15098   if (BroadcastIdx < 0)
15099     return SDValue();
15100   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
15101                                             "a sorted mask where the broadcast "
15102                                             "comes from V1.");
15103 
15104   // Go up the chain of (vector) values to find a scalar load that we can
15105   // combine with the broadcast.
15106   // TODO: Combine this logic with findEltLoadSrc() used by
15107   //       EltsFromConsecutiveLoads().
15108   int BitOffset = BroadcastIdx * NumEltBits;
15109   SDValue V = V1;
15110   for (;;) {
15111     switch (V.getOpcode()) {
15112     case ISD::BITCAST: {
15113       V = V.getOperand(0);
15114       continue;
15115     }
15116     case ISD::CONCAT_VECTORS: {
15117       int OpBitWidth = V.getOperand(0).getValueSizeInBits();
15118       int OpIdx = BitOffset / OpBitWidth;
15119       V = V.getOperand(OpIdx);
15120       BitOffset %= OpBitWidth;
15121       continue;
15122     }
15123     case ISD::EXTRACT_SUBVECTOR: {
15124       // The extraction index adds to the existing offset.
15125       unsigned EltBitWidth = V.getScalarValueSizeInBits();
15126       unsigned Idx = V.getConstantOperandVal(1);
15127       unsigned BeginOffset = Idx * EltBitWidth;
15128       BitOffset += BeginOffset;
15129       V = V.getOperand(0);
15130       continue;
15131     }
15132     case ISD::INSERT_SUBVECTOR: {
15133       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
15134       int EltBitWidth = VOuter.getScalarValueSizeInBits();
15135       int Idx = (int)V.getConstantOperandVal(2);
15136       int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
15137       int BeginOffset = Idx * EltBitWidth;
15138       int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
15139       if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
15140         BitOffset -= BeginOffset;
15141         V = VInner;
15142       } else {
15143         V = VOuter;
15144       }
15145       continue;
15146     }
15147     }
15148     break;
15149   }
15150   assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
15151   BroadcastIdx = BitOffset / NumEltBits;
15152 
15153   // Do we need to bitcast the source to retrieve the original broadcast index?
15154   bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
15155 
15156   // Check if this is a broadcast of a scalar. We special case lowering
15157   // for scalars so that we can more effectively fold with loads.
15158   // If the original value has a larger element type than the shuffle, the
15159   // broadcast element is in essence truncated. Make that explicit to ease
15160   // folding.
15161   if (BitCastSrc && VT.isInteger())
15162     if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
15163             DL, VT, V, BroadcastIdx, Subtarget, DAG))
15164       return TruncBroadcast;
15165 
15166   // Also check the simpler case, where we can directly reuse the scalar.
15167   if (!BitCastSrc &&
15168       ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
15169        (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
15170     V = V.getOperand(BroadcastIdx);
15171 
15172     // If we can't broadcast from a register, check that the input is a load.
15173     if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
15174       return SDValue();
15175   } else if (ISD::isNormalLoad(V.getNode()) &&
15176              cast<LoadSDNode>(V)->isSimple()) {
15177     // We do not check for one-use of the vector load because a broadcast load
15178     // is expected to be a win for code size, register pressure, and possibly
15179     // uops even if the original vector load is not eliminated.
15180 
15181     // Reduce the vector load and shuffle to a broadcasted scalar load.
15182     LoadSDNode *Ld = cast<LoadSDNode>(V);
15183     SDValue BaseAddr = Ld->getOperand(1);
15184     MVT SVT = VT.getScalarType();
15185     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
15186     assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
15187     SDValue NewAddr =
15188         DAG.getMemBasePlusOffset(BaseAddr, TypeSize::Fixed(Offset), DL);
15189 
15190     // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
15191     // than MOVDDUP.
15192     // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
15193     if (Opcode == X86ISD::VBROADCAST) {
15194       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
15195       SDValue Ops[] = {Ld->getChain(), NewAddr};
15196       V = DAG.getMemIntrinsicNode(
15197           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
15198           DAG.getMachineFunction().getMachineMemOperand(
15199               Ld->getMemOperand(), Offset, SVT.getStoreSize()));
15200       DAG.makeEquivalentMemoryOrdering(Ld, V);
15201       return DAG.getBitcast(VT, V);
15202     }
15203     assert(SVT == MVT::f64 && "Unexpected VT!");
15204     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
15205                     DAG.getMachineFunction().getMachineMemOperand(
15206                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
15207     DAG.makeEquivalentMemoryOrdering(Ld, V);
15208   } else if (!BroadcastFromReg) {
15209     // We can't broadcast from a vector register.
15210     return SDValue();
15211   } else if (BitOffset != 0) {
15212     // We can only broadcast from the zero-element of a vector register,
15213     // but it can be advantageous to broadcast from the zero-element of a
15214     // subvector.
15215     if (!VT.is256BitVector() && !VT.is512BitVector())
15216       return SDValue();
15217 
15218     // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
15219     if (VT == MVT::v4f64 || VT == MVT::v4i64)
15220       return SDValue();
15221 
15222     // Only broadcast the zero-element of a 128-bit subvector.
15223     if ((BitOffset % 128) != 0)
15224       return SDValue();
15225 
15226     assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
15227            "Unexpected bit-offset");
15228     assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
15229            "Unexpected vector size");
15230     unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
15231     V = extract128BitVector(V, ExtractIdx, DAG, DL);
15232   }
15233 
15234   // On AVX we can use VBROADCAST directly for scalar sources.
15235   if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
15236     V = DAG.getBitcast(MVT::f64, V);
15237     if (Subtarget.hasAVX()) {
15238       V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
15239       return DAG.getBitcast(VT, V);
15240     }
15241     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
15242   }
15243 
15244   // If this is a scalar, do the broadcast on this type and bitcast.
15245   if (!V.getValueType().isVector()) {
15246     assert(V.getScalarValueSizeInBits() == NumEltBits &&
15247            "Unexpected scalar size");
15248     MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
15249                                        VT.getVectorNumElements());
15250     return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
15251   }
15252 
15253   // We only support broadcasting from 128-bit vectors to minimize the
15254   // number of patterns we need to deal with in isel. So extract down to
15255   // 128-bits, removing as many bitcasts as possible.
15256   if (V.getValueSizeInBits() > 128)
15257     V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
15258 
15259   // Otherwise cast V to a vector with the same element type as VT, but
15260   // possibly narrower than VT. Then perform the broadcast.
15261   unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
15262   MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
15263   return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
15264 }
15265 
15266 // Check for whether we can use INSERTPS to perform the shuffle. We only use
15267 // INSERTPS when the V1 elements are already in the correct locations
15268 // because otherwise we can just always use two SHUFPS instructions which
15269 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
15270 // perform INSERTPS if a single V1 element is out of place and all V2
15271 // elements are zeroable.
15272 static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
15273                                    unsigned &InsertPSMask,
15274                                    const APInt &Zeroable,
15275                                    ArrayRef<int> Mask, SelectionDAG &DAG) {
15276   assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
15277   assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
15278   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15279 
15280   // Attempt to match INSERTPS with one element from VA or VB being
15281   // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
15282   // are updated.
15283   auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
15284                              ArrayRef<int> CandidateMask) {
15285     unsigned ZMask = 0;
15286     int VADstIndex = -1;
15287     int VBDstIndex = -1;
15288     bool VAUsedInPlace = false;
15289 
15290     for (int i = 0; i < 4; ++i) {
15291       // Synthesize a zero mask from the zeroable elements (includes undefs).
15292       if (Zeroable[i]) {
15293         ZMask |= 1 << i;
15294         continue;
15295       }
15296 
15297       // Flag if we use any VA inputs in place.
15298       if (i == CandidateMask[i]) {
15299         VAUsedInPlace = true;
15300         continue;
15301       }
15302 
15303       // We can only insert a single non-zeroable element.
15304       if (VADstIndex >= 0 || VBDstIndex >= 0)
15305         return false;
15306 
15307       if (CandidateMask[i] < 4) {
15308         // VA input out of place for insertion.
15309         VADstIndex = i;
15310       } else {
15311         // VB input for insertion.
15312         VBDstIndex = i;
15313       }
15314     }
15315 
15316     // Don't bother if we have no (non-zeroable) element for insertion.
15317     if (VADstIndex < 0 && VBDstIndex < 0)
15318       return false;
15319 
15320     // Determine element insertion src/dst indices. The src index is from the
15321     // start of the inserted vector, not the start of the concatenated vector.
15322     unsigned VBSrcIndex = 0;
15323     if (VADstIndex >= 0) {
15324       // If we have a VA input out of place, we use VA as the V2 element
15325       // insertion and don't use the original V2 at all.
15326       VBSrcIndex = CandidateMask[VADstIndex];
15327       VBDstIndex = VADstIndex;
15328       VB = VA;
15329     } else {
15330       VBSrcIndex = CandidateMask[VBDstIndex] - 4;
15331     }
15332 
15333     // If no V1 inputs are used in place, then the result is created only from
15334     // the zero mask and the V2 insertion - so remove V1 dependency.
15335     if (!VAUsedInPlace)
15336       VA = DAG.getUNDEF(MVT::v4f32);
15337 
15338     // Update V1, V2 and InsertPSMask accordingly.
15339     V1 = VA;
15340     V2 = VB;
15341 
15342     // Insert the V2 element into the desired position.
15343     InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
15344     assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
15345     return true;
15346   };
15347 
15348   if (matchAsInsertPS(V1, V2, Mask))
15349     return true;
15350 
15351   // Commute and try again.
15352   SmallVector<int, 4> CommutedMask(Mask);
15353   ShuffleVectorSDNode::commuteMask(CommutedMask);
15354   if (matchAsInsertPS(V2, V1, CommutedMask))
15355     return true;
15356 
15357   return false;
15358 }
15359 
15360 static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
15361                                       ArrayRef<int> Mask, const APInt &Zeroable,
15362                                       SelectionDAG &DAG) {
15363   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
15364   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
15365 
15366   // Attempt to match the insertps pattern.
15367   unsigned InsertPSMask = 0;
15368   if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
15369     return SDValue();
15370 
15371   // Insert the V2 element into the desired position.
15372   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
15373                      DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
15374 }
15375 
15376 /// Handle lowering of 2-lane 64-bit floating point shuffles.
15377 ///
15378 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
15379 /// support for floating point shuffles but not integer shuffles. These
15380 /// instructions will incur a domain crossing penalty on some chips though so
15381 /// it is better to avoid lowering through this for integer vectors where
15382 /// possible.
15383 static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15384                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15385                                  const X86Subtarget &Subtarget,
15386                                  SelectionDAG &DAG) {
15387   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
15388   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
15389   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
15390 
15391   if (V2.isUndef()) {
15392     // Check for being able to broadcast a single element.
15393     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
15394                                                     Mask, Subtarget, DAG))
15395       return Broadcast;
15396 
15397     // Straight shuffle of a single input vector. Simulate this by using the
15398     // single input as both of the "inputs" to this instruction..
15399     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
15400 
15401     if (Subtarget.hasAVX()) {
15402       // If we have AVX, we can use VPERMILPS which will allow folding a load
15403       // into the shuffle.
15404       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
15405                          DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
15406     }
15407 
15408     return DAG.getNode(
15409         X86ISD::SHUFP, DL, MVT::v2f64,
15410         Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
15411         Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
15412         DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
15413   }
15414   assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
15415   assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
15416   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
15417   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
15418 
15419   if (Subtarget.hasAVX2())
15420     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
15421       return Extract;
15422 
15423   // When loading a scalar and then shuffling it into a vector we can often do
15424   // the insertion cheaply.
15425   if (SDValue Insertion = lowerShuffleAsElementInsertion(
15426           DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
15427     return Insertion;
15428   // Try inverting the insertion since for v2 masks it is easy to do and we
15429   // can't reliably sort the mask one way or the other.
15430   int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
15431                         Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
15432   if (SDValue Insertion = lowerShuffleAsElementInsertion(
15433           DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
15434     return Insertion;
15435 
15436   // Try to use one of the special instruction patterns to handle two common
15437   // blend patterns if a zero-blend above didn't work.
15438   if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
15439       isShuffleEquivalent(Mask, {1, 3}, V1, V2))
15440     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
15441       // We can either use a special instruction to load over the low double or
15442       // to move just the low double.
15443       return DAG.getNode(
15444           X86ISD::MOVSD, DL, MVT::v2f64, V2,
15445           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
15446 
15447   if (Subtarget.hasSSE41())
15448     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
15449                                             Zeroable, Subtarget, DAG))
15450       return Blend;
15451 
15452   // Use dedicated unpack instructions for masks that match their pattern.
15453   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
15454     return V;
15455 
15456   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
15457   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
15458                      DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
15459 }
15460 
15461 /// Handle lowering of 2-lane 64-bit integer shuffles.
15462 ///
15463 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
15464 /// the integer unit to minimize domain crossing penalties. However, for blends
15465 /// it falls back to the floating point shuffle operation with appropriate bit
15466 /// casting.
15467 static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15468                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15469                                  const X86Subtarget &Subtarget,
15470                                  SelectionDAG &DAG) {
15471   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
15472   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
15473   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
15474 
15475   if (V2.isUndef()) {
15476     // Check for being able to broadcast a single element.
15477     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
15478                                                     Mask, Subtarget, DAG))
15479       return Broadcast;
15480 
15481     // Straight shuffle of a single input vector. For everything from SSE2
15482     // onward this has a single fast instruction with no scary immediates.
15483     // We have to map the mask as it is actually a v4i32 shuffle instruction.
15484     V1 = DAG.getBitcast(MVT::v4i32, V1);
15485     int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
15486                           Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
15487                           Mask[1] < 0 ? -1 : (Mask[1] * 2),
15488                           Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
15489     return DAG.getBitcast(
15490         MVT::v2i64,
15491         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
15492                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
15493   }
15494   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
15495   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
15496   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
15497   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
15498 
15499   if (Subtarget.hasAVX2())
15500     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
15501       return Extract;
15502 
15503   // Try to use shift instructions.
15504   if (SDValue Shift =
15505           lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget,
15506                               DAG, /*BitwiseOnly*/ false))
15507     return Shift;
15508 
15509   // When loading a scalar and then shuffling it into a vector we can often do
15510   // the insertion cheaply.
15511   if (SDValue Insertion = lowerShuffleAsElementInsertion(
15512           DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
15513     return Insertion;
15514   // Try inverting the insertion since for v2 masks it is easy to do and we
15515   // can't reliably sort the mask one way or the other.
15516   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
15517   if (SDValue Insertion = lowerShuffleAsElementInsertion(
15518           DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
15519     return Insertion;
15520 
15521   // We have different paths for blend lowering, but they all must use the
15522   // *exact* same predicate.
15523   bool IsBlendSupported = Subtarget.hasSSE41();
15524   if (IsBlendSupported)
15525     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
15526                                             Zeroable, Subtarget, DAG))
15527       return Blend;
15528 
15529   // Use dedicated unpack instructions for masks that match their pattern.
15530   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
15531     return V;
15532 
15533   // Try to use byte rotation instructions.
15534   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
15535   if (Subtarget.hasSSSE3()) {
15536     if (Subtarget.hasVLX())
15537       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
15538                                                 Subtarget, DAG))
15539         return Rotate;
15540 
15541     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
15542                                                   Subtarget, DAG))
15543       return Rotate;
15544   }
15545 
15546   // If we have direct support for blends, we should lower by decomposing into
15547   // a permute. That will be faster than the domain cross.
15548   if (IsBlendSupported)
15549     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
15550                                                 Subtarget, DAG);
15551 
15552   // We implement this with SHUFPD which is pretty lame because it will likely
15553   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
15554   // However, all the alternatives are still more cycles and newer chips don't
15555   // have this problem. It would be really nice if x86 had better shuffles here.
15556   V1 = DAG.getBitcast(MVT::v2f64, V1);
15557   V2 = DAG.getBitcast(MVT::v2f64, V2);
15558   return DAG.getBitcast(MVT::v2i64,
15559                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
15560 }
15561 
15562 /// Lower a vector shuffle using the SHUFPS instruction.
15563 ///
15564 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
15565 /// It makes no assumptions about whether this is the *best* lowering, it simply
15566 /// uses it.
15567 static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
15568                                       ArrayRef<int> Mask, SDValue V1,
15569                                       SDValue V2, SelectionDAG &DAG) {
15570   SDValue LowV = V1, HighV = V2;
15571   SmallVector<int, 4> NewMask(Mask);
15572   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
15573 
15574   if (NumV2Elements == 1) {
15575     int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
15576 
15577     // Compute the index adjacent to V2Index and in the same half by toggling
15578     // the low bit.
15579     int V2AdjIndex = V2Index ^ 1;
15580 
15581     if (Mask[V2AdjIndex] < 0) {
15582       // Handles all the cases where we have a single V2 element and an undef.
15583       // This will only ever happen in the high lanes because we commute the
15584       // vector otherwise.
15585       if (V2Index < 2)
15586         std::swap(LowV, HighV);
15587       NewMask[V2Index] -= 4;
15588     } else {
15589       // Handle the case where the V2 element ends up adjacent to a V1 element.
15590       // To make this work, blend them together as the first step.
15591       int V1Index = V2AdjIndex;
15592       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
15593       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
15594                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
15595 
15596       // Now proceed to reconstruct the final blend as we have the necessary
15597       // high or low half formed.
15598       if (V2Index < 2) {
15599         LowV = V2;
15600         HighV = V1;
15601       } else {
15602         HighV = V2;
15603       }
15604       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
15605       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
15606     }
15607   } else if (NumV2Elements == 2) {
15608     if (Mask[0] < 4 && Mask[1] < 4) {
15609       // Handle the easy case where we have V1 in the low lanes and V2 in the
15610       // high lanes.
15611       NewMask[2] -= 4;
15612       NewMask[3] -= 4;
15613     } else if (Mask[2] < 4 && Mask[3] < 4) {
15614       // We also handle the reversed case because this utility may get called
15615       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
15616       // arrange things in the right direction.
15617       NewMask[0] -= 4;
15618       NewMask[1] -= 4;
15619       HighV = V1;
15620       LowV = V2;
15621     } else {
15622       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
15623       // trying to place elements directly, just blend them and set up the final
15624       // shuffle to place them.
15625 
15626       // The first two blend mask elements are for V1, the second two are for
15627       // V2.
15628       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
15629                           Mask[2] < 4 ? Mask[2] : Mask[3],
15630                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
15631                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
15632       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
15633                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
15634 
15635       // Now we do a normal shuffle of V1 by giving V1 as both operands to
15636       // a blend.
15637       LowV = HighV = V1;
15638       NewMask[0] = Mask[0] < 4 ? 0 : 2;
15639       NewMask[1] = Mask[0] < 4 ? 2 : 0;
15640       NewMask[2] = Mask[2] < 4 ? 1 : 3;
15641       NewMask[3] = Mask[2] < 4 ? 3 : 1;
15642     }
15643   } else if (NumV2Elements == 3) {
15644     // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
15645     // we can get here due to other paths (e.g repeated mask matching) that we
15646     // don't want to do another round of lowerVECTOR_SHUFFLE.
15647     ShuffleVectorSDNode::commuteMask(NewMask);
15648     return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
15649   }
15650   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
15651                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
15652 }
15653 
15654 /// Lower 4-lane 32-bit floating point shuffles.
15655 ///
15656 /// Uses instructions exclusively from the floating point unit to minimize
15657 /// domain crossing penalties, as these are sufficient to implement all v4f32
15658 /// shuffles.
15659 static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15660                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15661                                  const X86Subtarget &Subtarget,
15662                                  SelectionDAG &DAG) {
15663   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
15664   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
15665   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15666 
15667   if (Subtarget.hasSSE41())
15668     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
15669                                             Zeroable, Subtarget, DAG))
15670       return Blend;
15671 
15672   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
15673 
15674   if (NumV2Elements == 0) {
15675     // Check for being able to broadcast a single element.
15676     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
15677                                                     Mask, Subtarget, DAG))
15678       return Broadcast;
15679 
15680     // Use even/odd duplicate instructions for masks that match their pattern.
15681     if (Subtarget.hasSSE3()) {
15682       if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
15683         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
15684       if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
15685         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
15686     }
15687 
15688     if (Subtarget.hasAVX()) {
15689       // If we have AVX, we can use VPERMILPS which will allow folding a load
15690       // into the shuffle.
15691       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
15692                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15693     }
15694 
15695     // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
15696     // in SSE1 because otherwise they are widened to v2f64 and never get here.
15697     if (!Subtarget.hasSSE2()) {
15698       if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
15699         return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
15700       if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
15701         return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
15702     }
15703 
15704     // Otherwise, use a straight shuffle of a single input vector. We pass the
15705     // input vector to both operands to simulate this with a SHUFPS.
15706     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
15707                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15708   }
15709 
15710   if (Subtarget.hasSSE2())
15711     if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
15712             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG)) {
15713       ZExt = DAG.getBitcast(MVT::v4f32, ZExt);
15714       return ZExt;
15715     }
15716 
15717   if (Subtarget.hasAVX2())
15718     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
15719       return Extract;
15720 
15721   // There are special ways we can lower some single-element blends. However, we
15722   // have custom ways we can lower more complex single-element blends below that
15723   // we defer to if both this and BLENDPS fail to match, so restrict this to
15724   // when the V2 input is targeting element 0 of the mask -- that is the fast
15725   // case here.
15726   if (NumV2Elements == 1 && Mask[0] >= 4)
15727     if (SDValue V = lowerShuffleAsElementInsertion(
15728             DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
15729       return V;
15730 
15731   if (Subtarget.hasSSE41()) {
15732     // Use INSERTPS if we can complete the shuffle efficiently.
15733     if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
15734       return V;
15735 
15736     if (!isSingleSHUFPSMask(Mask))
15737       if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
15738                                                             V2, Mask, DAG))
15739         return BlendPerm;
15740   }
15741 
15742   // Use low/high mov instructions. These are only valid in SSE1 because
15743   // otherwise they are widened to v2f64 and never get here.
15744   if (!Subtarget.hasSSE2()) {
15745     if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
15746       return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
15747     if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
15748       return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
15749   }
15750 
15751   // Use dedicated unpack instructions for masks that match their pattern.
15752   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
15753     return V;
15754 
15755   // Otherwise fall back to a SHUFPS lowering strategy.
15756   return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
15757 }
15758 
15759 /// Lower 4-lane i32 vector shuffles.
15760 ///
15761 /// We try to handle these with integer-domain shuffles where we can, but for
15762 /// blends we use the floating point domain blend instructions.
15763 static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15764                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15765                                  const X86Subtarget &Subtarget,
15766                                  SelectionDAG &DAG) {
15767   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
15768   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
15769   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15770 
15771   // Whenever we can lower this as a zext, that instruction is strictly faster
15772   // than any alternative. It also allows us to fold memory operands into the
15773   // shuffle in many cases.
15774   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
15775                                                    Zeroable, Subtarget, DAG))
15776     return ZExt;
15777 
15778   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
15779 
15780   // Try to use shift instructions if fast.
15781   if (Subtarget.preferLowerShuffleAsShift()) {
15782     if (SDValue Shift =
15783             lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable,
15784                                 Subtarget, DAG, /*BitwiseOnly*/ true))
15785       return Shift;
15786     if (NumV2Elements == 0)
15787       if (SDValue Rotate =
15788               lowerShuffleAsBitRotate(DL, MVT::v4i32, V1, Mask, Subtarget, DAG))
15789         return Rotate;
15790   }
15791 
15792   if (NumV2Elements == 0) {
15793     // Try to use broadcast unless the mask only has one non-undef element.
15794     if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
15795       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
15796                                                       Mask, Subtarget, DAG))
15797         return Broadcast;
15798     }
15799 
15800     // Straight shuffle of a single input vector. For everything from SSE2
15801     // onward this has a single fast instruction with no scary immediates.
15802     // We coerce the shuffle pattern to be compatible with UNPCK instructions
15803     // but we aren't actually going to use the UNPCK instruction because doing
15804     // so prevents folding a load into this instruction or making a copy.
15805     const int UnpackLoMask[] = {0, 0, 1, 1};
15806     const int UnpackHiMask[] = {2, 2, 3, 3};
15807     if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
15808       Mask = UnpackLoMask;
15809     else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
15810       Mask = UnpackHiMask;
15811 
15812     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
15813                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15814   }
15815 
15816   if (Subtarget.hasAVX2())
15817     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
15818       return Extract;
15819 
15820   // Try to use shift instructions.
15821   if (SDValue Shift =
15822           lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget,
15823                               DAG, /*BitwiseOnly*/ false))
15824     return Shift;
15825 
15826   // There are special ways we can lower some single-element blends.
15827   if (NumV2Elements == 1)
15828     if (SDValue V = lowerShuffleAsElementInsertion(
15829             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
15830       return V;
15831 
15832   // We have different paths for blend lowering, but they all must use the
15833   // *exact* same predicate.
15834   bool IsBlendSupported = Subtarget.hasSSE41();
15835   if (IsBlendSupported)
15836     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
15837                                             Zeroable, Subtarget, DAG))
15838       return Blend;
15839 
15840   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
15841                                              Zeroable, Subtarget, DAG))
15842     return Masked;
15843 
15844   // Use dedicated unpack instructions for masks that match their pattern.
15845   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
15846     return V;
15847 
15848   // Try to use byte rotation instructions.
15849   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
15850   if (Subtarget.hasSSSE3()) {
15851     if (Subtarget.hasVLX())
15852       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
15853                                                 Subtarget, DAG))
15854         return Rotate;
15855 
15856     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
15857                                                   Subtarget, DAG))
15858       return Rotate;
15859   }
15860 
15861   // Assume that a single SHUFPS is faster than an alternative sequence of
15862   // multiple instructions (even if the CPU has a domain penalty).
15863   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
15864   if (!isSingleSHUFPSMask(Mask)) {
15865     // If we have direct support for blends, we should lower by decomposing into
15866     // a permute. That will be faster than the domain cross.
15867     if (IsBlendSupported)
15868       return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
15869                                                   Subtarget, DAG);
15870 
15871     // Try to lower by permuting the inputs into an unpack instruction.
15872     if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
15873                                                         Mask, Subtarget, DAG))
15874       return Unpack;
15875   }
15876 
15877   // We implement this with SHUFPS because it can blend from two vectors.
15878   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
15879   // up the inputs, bypassing domain shift penalties that we would incur if we
15880   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
15881   // relevant.
15882   SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
15883   SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
15884   SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
15885   return DAG.getBitcast(MVT::v4i32, ShufPS);
15886 }
15887 
15888 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
15889 /// shuffle lowering, and the most complex part.
15890 ///
15891 /// The lowering strategy is to try to form pairs of input lanes which are
15892 /// targeted at the same half of the final vector, and then use a dword shuffle
15893 /// to place them onto the right half, and finally unpack the paired lanes into
15894 /// their final position.
15895 ///
15896 /// The exact breakdown of how to form these dword pairs and align them on the
15897 /// correct sides is really tricky. See the comments within the function for
15898 /// more of the details.
15899 ///
15900 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
15901 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
15902 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
15903 /// vector, form the analogous 128-bit 8-element Mask.
15904 static SDValue lowerV8I16GeneralSingleInputShuffle(
15905     const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
15906     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15907   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
15908   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
15909 
15910   assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
15911   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
15912   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
15913 
15914   // Attempt to directly match PSHUFLW or PSHUFHW.
15915   if (isUndefOrInRange(LoMask, 0, 4) &&
15916       isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
15917     return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15918                        getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
15919   }
15920   if (isUndefOrInRange(HiMask, 4, 8) &&
15921       isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
15922     for (int i = 0; i != 4; ++i)
15923       HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
15924     return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15925                        getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
15926   }
15927 
15928   SmallVector<int, 4> LoInputs;
15929   copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
15930   array_pod_sort(LoInputs.begin(), LoInputs.end());
15931   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
15932   SmallVector<int, 4> HiInputs;
15933   copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
15934   array_pod_sort(HiInputs.begin(), HiInputs.end());
15935   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
15936   int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
15937   int NumHToL = LoInputs.size() - NumLToL;
15938   int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
15939   int NumHToH = HiInputs.size() - NumLToH;
15940   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
15941   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
15942   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
15943   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
15944 
15945   // If we are shuffling values from one half - check how many different DWORD
15946   // pairs we need to create. If only 1 or 2 then we can perform this as a
15947   // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
15948   auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
15949                                ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
15950     V = DAG.getNode(ShufWOp, DL, VT, V,
15951                     getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
15952     V = DAG.getBitcast(PSHUFDVT, V);
15953     V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
15954                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
15955     return DAG.getBitcast(VT, V);
15956   };
15957 
15958   if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
15959     int PSHUFDMask[4] = { -1, -1, -1, -1 };
15960     SmallVector<std::pair<int, int>, 4> DWordPairs;
15961     int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
15962 
15963     // Collect the different DWORD pairs.
15964     for (int DWord = 0; DWord != 4; ++DWord) {
15965       int M0 = Mask[2 * DWord + 0];
15966       int M1 = Mask[2 * DWord + 1];
15967       M0 = (M0 >= 0 ? M0 % 4 : M0);
15968       M1 = (M1 >= 0 ? M1 % 4 : M1);
15969       if (M0 < 0 && M1 < 0)
15970         continue;
15971 
15972       bool Match = false;
15973       for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
15974         auto &DWordPair = DWordPairs[j];
15975         if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
15976             (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
15977           DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
15978           DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
15979           PSHUFDMask[DWord] = DOffset + j;
15980           Match = true;
15981           break;
15982         }
15983       }
15984       if (!Match) {
15985         PSHUFDMask[DWord] = DOffset + DWordPairs.size();
15986         DWordPairs.push_back(std::make_pair(M0, M1));
15987       }
15988     }
15989 
15990     if (DWordPairs.size() <= 2) {
15991       DWordPairs.resize(2, std::make_pair(-1, -1));
15992       int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
15993                               DWordPairs[1].first, DWordPairs[1].second};
15994       if ((NumHToL + NumHToH) == 0)
15995         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
15996       if ((NumLToL + NumLToH) == 0)
15997         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
15998     }
15999   }
16000 
16001   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
16002   // such inputs we can swap two of the dwords across the half mark and end up
16003   // with <=2 inputs to each half in each half. Once there, we can fall through
16004   // to the generic code below. For example:
16005   //
16006   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
16007   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
16008   //
16009   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
16010   // and an existing 2-into-2 on the other half. In this case we may have to
16011   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
16012   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
16013   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
16014   // because any other situation (including a 3-into-1 or 1-into-3 in the other
16015   // half than the one we target for fixing) will be fixed when we re-enter this
16016   // path. We will also combine away any sequence of PSHUFD instructions that
16017   // result into a single instruction. Here is an example of the tricky case:
16018   //
16019   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
16020   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
16021   //
16022   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
16023   //
16024   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
16025   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
16026   //
16027   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
16028   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
16029   //
16030   // The result is fine to be handled by the generic logic.
16031   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
16032                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
16033                           int AOffset, int BOffset) {
16034     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
16035            "Must call this with A having 3 or 1 inputs from the A half.");
16036     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
16037            "Must call this with B having 1 or 3 inputs from the B half.");
16038     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
16039            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
16040 
16041     bool ThreeAInputs = AToAInputs.size() == 3;
16042 
16043     // Compute the index of dword with only one word among the three inputs in
16044     // a half by taking the sum of the half with three inputs and subtracting
16045     // the sum of the actual three inputs. The difference is the remaining
16046     // slot.
16047     int ADWord = 0, BDWord = 0;
16048     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
16049     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
16050     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
16051     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
16052     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
16053     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
16054     int TripleNonInputIdx =
16055         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
16056     TripleDWord = TripleNonInputIdx / 2;
16057 
16058     // We use xor with one to compute the adjacent DWord to whichever one the
16059     // OneInput is in.
16060     OneInputDWord = (OneInput / 2) ^ 1;
16061 
16062     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
16063     // and BToA inputs. If there is also such a problem with the BToB and AToB
16064     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
16065     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
16066     // is essential that we don't *create* a 3<-1 as then we might oscillate.
16067     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
16068       // Compute how many inputs will be flipped by swapping these DWords. We
16069       // need
16070       // to balance this to ensure we don't form a 3-1 shuffle in the other
16071       // half.
16072       int NumFlippedAToBInputs = llvm::count(AToBInputs, 2 * ADWord) +
16073                                  llvm::count(AToBInputs, 2 * ADWord + 1);
16074       int NumFlippedBToBInputs = llvm::count(BToBInputs, 2 * BDWord) +
16075                                  llvm::count(BToBInputs, 2 * BDWord + 1);
16076       if ((NumFlippedAToBInputs == 1 &&
16077            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
16078           (NumFlippedBToBInputs == 1 &&
16079            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
16080         // We choose whether to fix the A half or B half based on whether that
16081         // half has zero flipped inputs. At zero, we may not be able to fix it
16082         // with that half. We also bias towards fixing the B half because that
16083         // will more commonly be the high half, and we have to bias one way.
16084         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
16085                                                        ArrayRef<int> Inputs) {
16086           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
16087           bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
16088           // Determine whether the free index is in the flipped dword or the
16089           // unflipped dword based on where the pinned index is. We use this bit
16090           // in an xor to conditionally select the adjacent dword.
16091           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
16092           bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
16093           if (IsFixIdxInput == IsFixFreeIdxInput)
16094             FixFreeIdx += 1;
16095           IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
16096           assert(IsFixIdxInput != IsFixFreeIdxInput &&
16097                  "We need to be changing the number of flipped inputs!");
16098           int PSHUFHalfMask[] = {0, 1, 2, 3};
16099           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
16100           V = DAG.getNode(
16101               FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
16102               MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
16103               getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
16104 
16105           for (int &M : Mask)
16106             if (M >= 0 && M == FixIdx)
16107               M = FixFreeIdx;
16108             else if (M >= 0 && M == FixFreeIdx)
16109               M = FixIdx;
16110         };
16111         if (NumFlippedBToBInputs != 0) {
16112           int BPinnedIdx =
16113               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
16114           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
16115         } else {
16116           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
16117           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
16118           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
16119         }
16120       }
16121     }
16122 
16123     int PSHUFDMask[] = {0, 1, 2, 3};
16124     PSHUFDMask[ADWord] = BDWord;
16125     PSHUFDMask[BDWord] = ADWord;
16126     V = DAG.getBitcast(
16127         VT,
16128         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
16129                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16130 
16131     // Adjust the mask to match the new locations of A and B.
16132     for (int &M : Mask)
16133       if (M >= 0 && M/2 == ADWord)
16134         M = 2 * BDWord + M % 2;
16135       else if (M >= 0 && M/2 == BDWord)
16136         M = 2 * ADWord + M % 2;
16137 
16138     // Recurse back into this routine to re-compute state now that this isn't
16139     // a 3 and 1 problem.
16140     return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
16141   };
16142   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
16143     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
16144   if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
16145     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
16146 
16147   // At this point there are at most two inputs to the low and high halves from
16148   // each half. That means the inputs can always be grouped into dwords and
16149   // those dwords can then be moved to the correct half with a dword shuffle.
16150   // We use at most one low and one high word shuffle to collect these paired
16151   // inputs into dwords, and finally a dword shuffle to place them.
16152   int PSHUFLMask[4] = {-1, -1, -1, -1};
16153   int PSHUFHMask[4] = {-1, -1, -1, -1};
16154   int PSHUFDMask[4] = {-1, -1, -1, -1};
16155 
16156   // First fix the masks for all the inputs that are staying in their
16157   // original halves. This will then dictate the targets of the cross-half
16158   // shuffles.
16159   auto fixInPlaceInputs =
16160       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
16161                     MutableArrayRef<int> SourceHalfMask,
16162                     MutableArrayRef<int> HalfMask, int HalfOffset) {
16163     if (InPlaceInputs.empty())
16164       return;
16165     if (InPlaceInputs.size() == 1) {
16166       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
16167           InPlaceInputs[0] - HalfOffset;
16168       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
16169       return;
16170     }
16171     if (IncomingInputs.empty()) {
16172       // Just fix all of the in place inputs.
16173       for (int Input : InPlaceInputs) {
16174         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
16175         PSHUFDMask[Input / 2] = Input / 2;
16176       }
16177       return;
16178     }
16179 
16180     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
16181     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
16182         InPlaceInputs[0] - HalfOffset;
16183     // Put the second input next to the first so that they are packed into
16184     // a dword. We find the adjacent index by toggling the low bit.
16185     int AdjIndex = InPlaceInputs[0] ^ 1;
16186     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
16187     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
16188     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
16189   };
16190   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
16191   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
16192 
16193   // Now gather the cross-half inputs and place them into a free dword of
16194   // their target half.
16195   // FIXME: This operation could almost certainly be simplified dramatically to
16196   // look more like the 3-1 fixing operation.
16197   auto moveInputsToRightHalf = [&PSHUFDMask](
16198       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
16199       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
16200       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
16201       int DestOffset) {
16202     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
16203       return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
16204     };
16205     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
16206                                                int Word) {
16207       int LowWord = Word & ~1;
16208       int HighWord = Word | 1;
16209       return isWordClobbered(SourceHalfMask, LowWord) ||
16210              isWordClobbered(SourceHalfMask, HighWord);
16211     };
16212 
16213     if (IncomingInputs.empty())
16214       return;
16215 
16216     if (ExistingInputs.empty()) {
16217       // Map any dwords with inputs from them into the right half.
16218       for (int Input : IncomingInputs) {
16219         // If the source half mask maps over the inputs, turn those into
16220         // swaps and use the swapped lane.
16221         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
16222           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
16223             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
16224                 Input - SourceOffset;
16225             // We have to swap the uses in our half mask in one sweep.
16226             for (int &M : HalfMask)
16227               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
16228                 M = Input;
16229               else if (M == Input)
16230                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
16231           } else {
16232             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
16233                        Input - SourceOffset &&
16234                    "Previous placement doesn't match!");
16235           }
16236           // Note that this correctly re-maps both when we do a swap and when
16237           // we observe the other side of the swap above. We rely on that to
16238           // avoid swapping the members of the input list directly.
16239           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
16240         }
16241 
16242         // Map the input's dword into the correct half.
16243         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
16244           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
16245         else
16246           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
16247                      Input / 2 &&
16248                  "Previous placement doesn't match!");
16249       }
16250 
16251       // And just directly shift any other-half mask elements to be same-half
16252       // as we will have mirrored the dword containing the element into the
16253       // same position within that half.
16254       for (int &M : HalfMask)
16255         if (M >= SourceOffset && M < SourceOffset + 4) {
16256           M = M - SourceOffset + DestOffset;
16257           assert(M >= 0 && "This should never wrap below zero!");
16258         }
16259       return;
16260     }
16261 
16262     // Ensure we have the input in a viable dword of its current half. This
16263     // is particularly tricky because the original position may be clobbered
16264     // by inputs being moved and *staying* in that half.
16265     if (IncomingInputs.size() == 1) {
16266       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
16267         int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
16268                          SourceOffset;
16269         SourceHalfMask[InputFixed - SourceOffset] =
16270             IncomingInputs[0] - SourceOffset;
16271         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
16272                      InputFixed);
16273         IncomingInputs[0] = InputFixed;
16274       }
16275     } else if (IncomingInputs.size() == 2) {
16276       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
16277           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
16278         // We have two non-adjacent or clobbered inputs we need to extract from
16279         // the source half. To do this, we need to map them into some adjacent
16280         // dword slot in the source mask.
16281         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
16282                               IncomingInputs[1] - SourceOffset};
16283 
16284         // If there is a free slot in the source half mask adjacent to one of
16285         // the inputs, place the other input in it. We use (Index XOR 1) to
16286         // compute an adjacent index.
16287         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
16288             SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
16289           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
16290           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
16291           InputsFixed[1] = InputsFixed[0] ^ 1;
16292         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
16293                    SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
16294           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
16295           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
16296           InputsFixed[0] = InputsFixed[1] ^ 1;
16297         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
16298                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
16299           // The two inputs are in the same DWord but it is clobbered and the
16300           // adjacent DWord isn't used at all. Move both inputs to the free
16301           // slot.
16302           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
16303           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
16304           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
16305           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
16306         } else {
16307           // The only way we hit this point is if there is no clobbering
16308           // (because there are no off-half inputs to this half) and there is no
16309           // free slot adjacent to one of the inputs. In this case, we have to
16310           // swap an input with a non-input.
16311           for (int i = 0; i < 4; ++i)
16312             assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
16313                    "We can't handle any clobbers here!");
16314           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
16315                  "Cannot have adjacent inputs here!");
16316 
16317           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
16318           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
16319 
16320           // We also have to update the final source mask in this case because
16321           // it may need to undo the above swap.
16322           for (int &M : FinalSourceHalfMask)
16323             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
16324               M = InputsFixed[1] + SourceOffset;
16325             else if (M == InputsFixed[1] + SourceOffset)
16326               M = (InputsFixed[0] ^ 1) + SourceOffset;
16327 
16328           InputsFixed[1] = InputsFixed[0] ^ 1;
16329         }
16330 
16331         // Point everything at the fixed inputs.
16332         for (int &M : HalfMask)
16333           if (M == IncomingInputs[0])
16334             M = InputsFixed[0] + SourceOffset;
16335           else if (M == IncomingInputs[1])
16336             M = InputsFixed[1] + SourceOffset;
16337 
16338         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
16339         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
16340       }
16341     } else {
16342       llvm_unreachable("Unhandled input size!");
16343     }
16344 
16345     // Now hoist the DWord down to the right half.
16346     int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
16347     assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
16348     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
16349     for (int &M : HalfMask)
16350       for (int Input : IncomingInputs)
16351         if (M == Input)
16352           M = FreeDWord * 2 + Input % 2;
16353   };
16354   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
16355                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
16356   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
16357                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
16358 
16359   // Now enact all the shuffles we've computed to move the inputs into their
16360   // target half.
16361   if (!isNoopShuffleMask(PSHUFLMask))
16362     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
16363                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
16364   if (!isNoopShuffleMask(PSHUFHMask))
16365     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
16366                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
16367   if (!isNoopShuffleMask(PSHUFDMask))
16368     V = DAG.getBitcast(
16369         VT,
16370         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
16371                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16372 
16373   // At this point, each half should contain all its inputs, and we can then
16374   // just shuffle them into their final position.
16375   assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
16376          "Failed to lift all the high half inputs to the low mask!");
16377   assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
16378          "Failed to lift all the low half inputs to the high mask!");
16379 
16380   // Do a half shuffle for the low mask.
16381   if (!isNoopShuffleMask(LoMask))
16382     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
16383                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
16384 
16385   // Do a half shuffle with the high mask after shifting its values down.
16386   for (int &M : HiMask)
16387     if (M >= 0)
16388       M -= 4;
16389   if (!isNoopShuffleMask(HiMask))
16390     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
16391                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
16392 
16393   return V;
16394 }
16395 
16396 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
16397 /// blend if only one input is used.
16398 static SDValue lowerShuffleAsBlendOfPSHUFBs(
16399     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16400     const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
16401   assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
16402          "Lane crossing shuffle masks not supported");
16403 
16404   int NumBytes = VT.getSizeInBits() / 8;
16405   int Size = Mask.size();
16406   int Scale = NumBytes / Size;
16407 
16408   SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
16409   SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
16410   V1InUse = false;
16411   V2InUse = false;
16412 
16413   for (int i = 0; i < NumBytes; ++i) {
16414     int M = Mask[i / Scale];
16415     if (M < 0)
16416       continue;
16417 
16418     const int ZeroMask = 0x80;
16419     int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
16420     int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
16421     if (Zeroable[i / Scale])
16422       V1Idx = V2Idx = ZeroMask;
16423 
16424     V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
16425     V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
16426     V1InUse |= (ZeroMask != V1Idx);
16427     V2InUse |= (ZeroMask != V2Idx);
16428   }
16429 
16430   MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
16431   if (V1InUse)
16432     V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
16433                      DAG.getBuildVector(ShufVT, DL, V1Mask));
16434   if (V2InUse)
16435     V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
16436                      DAG.getBuildVector(ShufVT, DL, V2Mask));
16437 
16438   // If we need shuffled inputs from both, blend the two.
16439   SDValue V;
16440   if (V1InUse && V2InUse)
16441     V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
16442   else
16443     V = V1InUse ? V1 : V2;
16444 
16445   // Cast the result back to the correct type.
16446   return DAG.getBitcast(VT, V);
16447 }
16448 
16449 /// Generic lowering of 8-lane i16 shuffles.
16450 ///
16451 /// This handles both single-input shuffles and combined shuffle/blends with
16452 /// two inputs. The single input shuffles are immediately delegated to
16453 /// a dedicated lowering routine.
16454 ///
16455 /// The blends are lowered in one of three fundamental ways. If there are few
16456 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
16457 /// of the input is significantly cheaper when lowered as an interleaving of
16458 /// the two inputs, try to interleave them. Otherwise, blend the low and high
16459 /// halves of the inputs separately (making them have relatively few inputs)
16460 /// and then concatenate them.
16461 static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16462                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16463                                  const X86Subtarget &Subtarget,
16464                                  SelectionDAG &DAG) {
16465   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
16466   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
16467   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16468 
16469   // Whenever we can lower this as a zext, that instruction is strictly faster
16470   // than any alternative.
16471   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
16472                                                    Zeroable, Subtarget, DAG))
16473     return ZExt;
16474 
16475   // Try to use lower using a truncation.
16476   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
16477                                         Subtarget, DAG))
16478     return V;
16479 
16480   int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
16481 
16482   if (NumV2Inputs == 0) {
16483     // Try to use shift instructions.
16484     if (SDValue Shift =
16485             lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, Zeroable,
16486                                 Subtarget, DAG, /*BitwiseOnly*/ false))
16487       return Shift;
16488 
16489     // Check for being able to broadcast a single element.
16490     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
16491                                                     Mask, Subtarget, DAG))
16492       return Broadcast;
16493 
16494     // Try to use bit rotation instructions.
16495     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
16496                                                  Subtarget, DAG))
16497       return Rotate;
16498 
16499     // Use dedicated unpack instructions for masks that match their pattern.
16500     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
16501       return V;
16502 
16503     // Use dedicated pack instructions for masks that match their pattern.
16504     if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
16505                                          Subtarget))
16506       return V;
16507 
16508     // Try to use byte rotation instructions.
16509     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
16510                                                   Subtarget, DAG))
16511       return Rotate;
16512 
16513     // Make a copy of the mask so it can be modified.
16514     SmallVector<int, 8> MutableMask(Mask);
16515     return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
16516                                                Subtarget, DAG);
16517   }
16518 
16519   assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
16520          "All single-input shuffles should be canonicalized to be V1-input "
16521          "shuffles.");
16522 
16523   // Try to use shift instructions.
16524   if (SDValue Shift =
16525           lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget,
16526                               DAG, /*BitwiseOnly*/ false))
16527     return Shift;
16528 
16529   // See if we can use SSE4A Extraction / Insertion.
16530   if (Subtarget.hasSSE4A())
16531     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
16532                                           Zeroable, DAG))
16533       return V;
16534 
16535   // There are special ways we can lower some single-element blends.
16536   if (NumV2Inputs == 1)
16537     if (SDValue V = lowerShuffleAsElementInsertion(
16538             DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16539       return V;
16540 
16541   // We have different paths for blend lowering, but they all must use the
16542   // *exact* same predicate.
16543   bool IsBlendSupported = Subtarget.hasSSE41();
16544   if (IsBlendSupported)
16545     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
16546                                             Zeroable, Subtarget, DAG))
16547       return Blend;
16548 
16549   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
16550                                              Zeroable, Subtarget, DAG))
16551     return Masked;
16552 
16553   // Use dedicated unpack instructions for masks that match their pattern.
16554   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
16555     return V;
16556 
16557   // Use dedicated pack instructions for masks that match their pattern.
16558   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
16559                                        Subtarget))
16560     return V;
16561 
16562   // Try to use lower using a truncation.
16563   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
16564                                        Subtarget, DAG))
16565     return V;
16566 
16567   // Try to use byte rotation instructions.
16568   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
16569                                                 Subtarget, DAG))
16570     return Rotate;
16571 
16572   if (SDValue BitBlend =
16573           lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
16574     return BitBlend;
16575 
16576   // Try to use byte shift instructions to mask.
16577   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
16578                                               Zeroable, Subtarget, DAG))
16579     return V;
16580 
16581   // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
16582   int NumEvenDrops = canLowerByDroppingElements(Mask, true, false);
16583   if ((NumEvenDrops == 1 || (NumEvenDrops == 2 && Subtarget.hasSSE41())) &&
16584       !Subtarget.hasVLX()) {
16585     // Check if this is part of a 256-bit vector truncation.
16586     unsigned PackOpc = 0;
16587     if (NumEvenDrops == 2 && Subtarget.hasAVX2() &&
16588         peekThroughBitcasts(V1).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16589         peekThroughBitcasts(V2).getOpcode() == ISD::EXTRACT_SUBVECTOR) {
16590       SDValue V1V2 = concatSubVectors(V1, V2, DAG, DL);
16591       V1V2 = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1V2,
16592                          getZeroVector(MVT::v16i16, Subtarget, DAG, DL),
16593                          DAG.getTargetConstant(0xEE, DL, MVT::i8));
16594       V1V2 = DAG.getBitcast(MVT::v8i32, V1V2);
16595       V1 = extract128BitVector(V1V2, 0, DAG, DL);
16596       V2 = extract128BitVector(V1V2, 4, DAG, DL);
16597       PackOpc = X86ISD::PACKUS;
16598     } else if (Subtarget.hasSSE41()) {
16599       SmallVector<SDValue, 4> DWordClearOps(4,
16600                                             DAG.getConstant(0, DL, MVT::i32));
16601       for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
16602         DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
16603       SDValue DWordClearMask =
16604           DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
16605       V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
16606                        DWordClearMask);
16607       V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
16608                        DWordClearMask);
16609       PackOpc = X86ISD::PACKUS;
16610     } else if (!Subtarget.hasSSSE3()) {
16611       SDValue ShAmt = DAG.getTargetConstant(16, DL, MVT::i8);
16612       V1 = DAG.getBitcast(MVT::v4i32, V1);
16613       V2 = DAG.getBitcast(MVT::v4i32, V2);
16614       V1 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V1, ShAmt);
16615       V2 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V2, ShAmt);
16616       V1 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V1, ShAmt);
16617       V2 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V2, ShAmt);
16618       PackOpc = X86ISD::PACKSS;
16619     }
16620     if (PackOpc) {
16621       // Now pack things back together.
16622       SDValue Result = DAG.getNode(PackOpc, DL, MVT::v8i16, V1, V2);
16623       if (NumEvenDrops == 2) {
16624         Result = DAG.getBitcast(MVT::v4i32, Result);
16625         Result = DAG.getNode(PackOpc, DL, MVT::v8i16, Result, Result);
16626       }
16627       return Result;
16628     }
16629   }
16630 
16631   // When compacting odd (upper) elements, use PACKSS pre-SSE41.
16632   int NumOddDrops = canLowerByDroppingElements(Mask, false, false);
16633   if (NumOddDrops == 1) {
16634     bool HasSSE41 = Subtarget.hasSSE41();
16635     V1 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
16636                      DAG.getBitcast(MVT::v4i32, V1),
16637                      DAG.getTargetConstant(16, DL, MVT::i8));
16638     V2 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
16639                      DAG.getBitcast(MVT::v4i32, V2),
16640                      DAG.getTargetConstant(16, DL, MVT::i8));
16641     return DAG.getNode(HasSSE41 ? X86ISD::PACKUS : X86ISD::PACKSS, DL,
16642                        MVT::v8i16, V1, V2);
16643   }
16644 
16645   // Try to lower by permuting the inputs into an unpack instruction.
16646   if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
16647                                                       Mask, Subtarget, DAG))
16648     return Unpack;
16649 
16650   // If we can't directly blend but can use PSHUFB, that will be better as it
16651   // can both shuffle and set up the inefficient blend.
16652   if (!IsBlendSupported && Subtarget.hasSSSE3()) {
16653     bool V1InUse, V2InUse;
16654     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
16655                                         Zeroable, DAG, V1InUse, V2InUse);
16656   }
16657 
16658   // We can always bit-blend if we have to so the fallback strategy is to
16659   // decompose into single-input permutes and blends/unpacks.
16660   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2,
16661                                               Mask, Subtarget, DAG);
16662 }
16663 
16664 /// Lower 8-lane 16-bit floating point shuffles.
16665 static SDValue lowerV8F16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16666                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16667                                  const X86Subtarget &Subtarget,
16668                                  SelectionDAG &DAG) {
16669   assert(V1.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
16670   assert(V2.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
16671   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16672   int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
16673 
16674   if (Subtarget.hasFP16()) {
16675     if (NumV2Elements == 0) {
16676       // Check for being able to broadcast a single element.
16677       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f16, V1, V2,
16678                                                       Mask, Subtarget, DAG))
16679         return Broadcast;
16680     }
16681     if (NumV2Elements == 1 && Mask[0] >= 8)
16682       if (SDValue V = lowerShuffleAsElementInsertion(
16683               DL, MVT::v8f16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16684         return V;
16685   }
16686 
16687   V1 = DAG.getBitcast(MVT::v8i16, V1);
16688   V2 = DAG.getBitcast(MVT::v8i16, V2);
16689   return DAG.getBitcast(MVT::v8f16,
16690                         DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
16691 }
16692 
16693 // Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
16694 // sub-512-bit shuffles are padded to 512-bits for the shuffle and then
16695 // the active subvector is extracted.
16696 static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
16697                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
16698                                      const X86Subtarget &Subtarget,
16699                                      SelectionDAG &DAG) {
16700   MVT MaskVT = VT.changeTypeToInteger();
16701   SDValue MaskNode;
16702   MVT ShuffleVT = VT;
16703   if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
16704     V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
16705     V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
16706     ShuffleVT = V1.getSimpleValueType();
16707 
16708     // Adjust mask to correct indices for the second input.
16709     int NumElts = VT.getVectorNumElements();
16710     unsigned Scale = 512 / VT.getSizeInBits();
16711     SmallVector<int, 32> AdjustedMask(Mask);
16712     for (int &M : AdjustedMask)
16713       if (NumElts <= M)
16714         M += (Scale - 1) * NumElts;
16715     MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
16716     MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
16717   } else {
16718     MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
16719   }
16720 
16721   SDValue Result;
16722   if (V2.isUndef())
16723     Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
16724   else
16725     Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
16726 
16727   if (VT != ShuffleVT)
16728     Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
16729 
16730   return Result;
16731 }
16732 
16733 /// Generic lowering of v16i8 shuffles.
16734 ///
16735 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
16736 /// detect any complexity reducing interleaving. If that doesn't help, it uses
16737 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
16738 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
16739 /// back together.
16740 static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16741                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16742                                  const X86Subtarget &Subtarget,
16743                                  SelectionDAG &DAG) {
16744   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
16745   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
16746   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16747 
16748   // Try to use shift instructions.
16749   if (SDValue Shift =
16750           lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget,
16751                               DAG, /*BitwiseOnly*/ false))
16752     return Shift;
16753 
16754   // Try to use byte rotation instructions.
16755   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
16756                                                 Subtarget, DAG))
16757     return Rotate;
16758 
16759   // Use dedicated pack instructions for masks that match their pattern.
16760   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
16761                                        Subtarget))
16762     return V;
16763 
16764   // Try to use a zext lowering.
16765   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
16766                                                    Zeroable, Subtarget, DAG))
16767     return ZExt;
16768 
16769   // Try to use lower using a truncation.
16770   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
16771                                         Subtarget, DAG))
16772     return V;
16773 
16774   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
16775                                        Subtarget, DAG))
16776     return V;
16777 
16778   // See if we can use SSE4A Extraction / Insertion.
16779   if (Subtarget.hasSSE4A())
16780     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
16781                                           Zeroable, DAG))
16782       return V;
16783 
16784   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
16785 
16786   // For single-input shuffles, there are some nicer lowering tricks we can use.
16787   if (NumV2Elements == 0) {
16788     // Check for being able to broadcast a single element.
16789     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
16790                                                     Mask, Subtarget, DAG))
16791       return Broadcast;
16792 
16793     // Try to use bit rotation instructions.
16794     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
16795                                                  Subtarget, DAG))
16796       return Rotate;
16797 
16798     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
16799       return V;
16800 
16801     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
16802     // Notably, this handles splat and partial-splat shuffles more efficiently.
16803     // However, it only makes sense if the pre-duplication shuffle simplifies
16804     // things significantly. Currently, this means we need to be able to
16805     // express the pre-duplication shuffle as an i16 shuffle.
16806     //
16807     // FIXME: We should check for other patterns which can be widened into an
16808     // i16 shuffle as well.
16809     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
16810       for (int i = 0; i < 16; i += 2)
16811         if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
16812           return false;
16813 
16814       return true;
16815     };
16816     auto tryToWidenViaDuplication = [&]() -> SDValue {
16817       if (!canWidenViaDuplication(Mask))
16818         return SDValue();
16819       SmallVector<int, 4> LoInputs;
16820       copy_if(Mask, std::back_inserter(LoInputs),
16821               [](int M) { return M >= 0 && M < 8; });
16822       array_pod_sort(LoInputs.begin(), LoInputs.end());
16823       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
16824                      LoInputs.end());
16825       SmallVector<int, 4> HiInputs;
16826       copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
16827       array_pod_sort(HiInputs.begin(), HiInputs.end());
16828       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
16829                      HiInputs.end());
16830 
16831       bool TargetLo = LoInputs.size() >= HiInputs.size();
16832       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
16833       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
16834 
16835       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
16836       SmallDenseMap<int, int, 8> LaneMap;
16837       for (int I : InPlaceInputs) {
16838         PreDupI16Shuffle[I/2] = I/2;
16839         LaneMap[I] = I;
16840       }
16841       int j = TargetLo ? 0 : 4, je = j + 4;
16842       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
16843         // Check if j is already a shuffle of this input. This happens when
16844         // there are two adjacent bytes after we move the low one.
16845         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
16846           // If we haven't yet mapped the input, search for a slot into which
16847           // we can map it.
16848           while (j < je && PreDupI16Shuffle[j] >= 0)
16849             ++j;
16850 
16851           if (j == je)
16852             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
16853             return SDValue();
16854 
16855           // Map this input with the i16 shuffle.
16856           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
16857         }
16858 
16859         // Update the lane map based on the mapping we ended up with.
16860         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
16861       }
16862       V1 = DAG.getBitcast(
16863           MVT::v16i8,
16864           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
16865                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
16866 
16867       // Unpack the bytes to form the i16s that will be shuffled into place.
16868       bool EvenInUse = false, OddInUse = false;
16869       for (int i = 0; i < 16; i += 2) {
16870         EvenInUse |= (Mask[i + 0] >= 0);
16871         OddInUse |= (Mask[i + 1] >= 0);
16872         if (EvenInUse && OddInUse)
16873           break;
16874       }
16875       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
16876                        MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
16877                        OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
16878 
16879       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
16880       for (int i = 0; i < 16; ++i)
16881         if (Mask[i] >= 0) {
16882           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
16883           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
16884           if (PostDupI16Shuffle[i / 2] < 0)
16885             PostDupI16Shuffle[i / 2] = MappedMask;
16886           else
16887             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
16888                    "Conflicting entries in the original shuffle!");
16889         }
16890       return DAG.getBitcast(
16891           MVT::v16i8,
16892           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
16893                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
16894     };
16895     if (SDValue V = tryToWidenViaDuplication())
16896       return V;
16897   }
16898 
16899   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
16900                                              Zeroable, Subtarget, DAG))
16901     return Masked;
16902 
16903   // Use dedicated unpack instructions for masks that match their pattern.
16904   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
16905     return V;
16906 
16907   // Try to use byte shift instructions to mask.
16908   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
16909                                               Zeroable, Subtarget, DAG))
16910     return V;
16911 
16912   // Check for compaction patterns.
16913   bool IsSingleInput = V2.isUndef();
16914   int NumEvenDrops = canLowerByDroppingElements(Mask, true, IsSingleInput);
16915 
16916   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
16917   // with PSHUFB. It is important to do this before we attempt to generate any
16918   // blends but after all of the single-input lowerings. If the single input
16919   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
16920   // want to preserve that and we can DAG combine any longer sequences into
16921   // a PSHUFB in the end. But once we start blending from multiple inputs,
16922   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
16923   // and there are *very* few patterns that would actually be faster than the
16924   // PSHUFB approach because of its ability to zero lanes.
16925   //
16926   // If the mask is a binary compaction, we can more efficiently perform this
16927   // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
16928   //
16929   // FIXME: The only exceptions to the above are blends which are exact
16930   // interleavings with direct instructions supporting them. We currently don't
16931   // handle those well here.
16932   if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
16933     bool V1InUse = false;
16934     bool V2InUse = false;
16935 
16936     SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
16937         DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
16938 
16939     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
16940     // do so. This avoids using them to handle blends-with-zero which is
16941     // important as a single pshufb is significantly faster for that.
16942     if (V1InUse && V2InUse) {
16943       if (Subtarget.hasSSE41())
16944         if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
16945                                                 Zeroable, Subtarget, DAG))
16946           return Blend;
16947 
16948       // We can use an unpack to do the blending rather than an or in some
16949       // cases. Even though the or may be (very minorly) more efficient, we
16950       // preference this lowering because there are common cases where part of
16951       // the complexity of the shuffles goes away when we do the final blend as
16952       // an unpack.
16953       // FIXME: It might be worth trying to detect if the unpack-feeding
16954       // shuffles will both be pshufb, in which case we shouldn't bother with
16955       // this.
16956       if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
16957               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
16958         return Unpack;
16959 
16960       // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
16961       if (Subtarget.hasVBMI())
16962         return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
16963                                      DAG);
16964 
16965       // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
16966       if (Subtarget.hasXOP()) {
16967         SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
16968         return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
16969       }
16970 
16971       // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
16972       // PALIGNR will be cheaper than the second PSHUFB+OR.
16973       if (SDValue V = lowerShuffleAsByteRotateAndPermute(
16974               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
16975         return V;
16976     }
16977 
16978     return PSHUFB;
16979   }
16980 
16981   // There are special ways we can lower some single-element blends.
16982   if (NumV2Elements == 1)
16983     if (SDValue V = lowerShuffleAsElementInsertion(
16984             DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
16985       return V;
16986 
16987   if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
16988     return Blend;
16989 
16990   // Check whether a compaction lowering can be done. This handles shuffles
16991   // which take every Nth element for some even N. See the helper function for
16992   // details.
16993   //
16994   // We special case these as they can be particularly efficiently handled with
16995   // the PACKUSB instruction on x86 and they show up in common patterns of
16996   // rearranging bytes to truncate wide elements.
16997   if (NumEvenDrops) {
16998     // NumEvenDrops is the power of two stride of the elements. Another way of
16999     // thinking about it is that we need to drop the even elements this many
17000     // times to get the original input.
17001 
17002     // First we need to zero all the dropped bytes.
17003     assert(NumEvenDrops <= 3 &&
17004            "No support for dropping even elements more than 3 times.");
17005     SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
17006     for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
17007       WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
17008     SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
17009     V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
17010                      WordClearMask);
17011     if (!IsSingleInput)
17012       V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
17013                        WordClearMask);
17014 
17015     // Now pack things back together.
17016     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
17017                                  IsSingleInput ? V1 : V2);
17018     for (int i = 1; i < NumEvenDrops; ++i) {
17019       Result = DAG.getBitcast(MVT::v8i16, Result);
17020       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
17021     }
17022     return Result;
17023   }
17024 
17025   int NumOddDrops = canLowerByDroppingElements(Mask, false, IsSingleInput);
17026   if (NumOddDrops == 1) {
17027     V1 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
17028                      DAG.getBitcast(MVT::v8i16, V1),
17029                      DAG.getTargetConstant(8, DL, MVT::i8));
17030     if (!IsSingleInput)
17031       V2 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
17032                        DAG.getBitcast(MVT::v8i16, V2),
17033                        DAG.getTargetConstant(8, DL, MVT::i8));
17034     return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
17035                        IsSingleInput ? V1 : V2);
17036   }
17037 
17038   // Handle multi-input cases by blending/unpacking single-input shuffles.
17039   if (NumV2Elements > 0)
17040     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
17041                                                 Subtarget, DAG);
17042 
17043   // The fallback path for single-input shuffles widens this into two v8i16
17044   // vectors with unpacks, shuffles those, and then pulls them back together
17045   // with a pack.
17046   SDValue V = V1;
17047 
17048   std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
17049   std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
17050   for (int i = 0; i < 16; ++i)
17051     if (Mask[i] >= 0)
17052       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
17053 
17054   SDValue VLoHalf, VHiHalf;
17055   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
17056   // them out and avoid using UNPCK{L,H} to extract the elements of V as
17057   // i16s.
17058   if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
17059       none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
17060     // Use a mask to drop the high bytes.
17061     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
17062     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
17063                           DAG.getConstant(0x00FF, DL, MVT::v8i16));
17064 
17065     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
17066     VHiHalf = DAG.getUNDEF(MVT::v8i16);
17067 
17068     // Squash the masks to point directly into VLoHalf.
17069     for (int &M : LoBlendMask)
17070       if (M >= 0)
17071         M /= 2;
17072     for (int &M : HiBlendMask)
17073       if (M >= 0)
17074         M /= 2;
17075   } else {
17076     // Otherwise just unpack the low half of V into VLoHalf and the high half into
17077     // VHiHalf so that we can blend them as i16s.
17078     SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
17079 
17080     VLoHalf = DAG.getBitcast(
17081         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
17082     VHiHalf = DAG.getBitcast(
17083         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
17084   }
17085 
17086   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
17087   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
17088 
17089   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
17090 }
17091 
17092 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
17093 ///
17094 /// This routine breaks down the specific type of 128-bit shuffle and
17095 /// dispatches to the lowering routines accordingly.
17096 static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17097                                   MVT VT, SDValue V1, SDValue V2,
17098                                   const APInt &Zeroable,
17099                                   const X86Subtarget &Subtarget,
17100                                   SelectionDAG &DAG) {
17101   switch (VT.SimpleTy) {
17102   case MVT::v2i64:
17103     return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17104   case MVT::v2f64:
17105     return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17106   case MVT::v4i32:
17107     return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17108   case MVT::v4f32:
17109     return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17110   case MVT::v8i16:
17111     return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17112   case MVT::v8f16:
17113     return lowerV8F16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17114   case MVT::v16i8:
17115     return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17116 
17117   default:
17118     llvm_unreachable("Unimplemented!");
17119   }
17120 }
17121 
17122 /// Generic routine to split vector shuffle into half-sized shuffles.
17123 ///
17124 /// This routine just extracts two subvectors, shuffles them independently, and
17125 /// then concatenates them back together. This should work effectively with all
17126 /// AVX vector shuffle types.
17127 static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
17128                                     SDValue V2, ArrayRef<int> Mask,
17129                                     SelectionDAG &DAG, bool SimpleOnly) {
17130   assert(VT.getSizeInBits() >= 256 &&
17131          "Only for 256-bit or wider vector shuffles!");
17132   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
17133   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
17134 
17135   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
17136   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
17137 
17138   int NumElements = VT.getVectorNumElements();
17139   int SplitNumElements = NumElements / 2;
17140   MVT ScalarVT = VT.getVectorElementType();
17141   MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
17142 
17143   // Use splitVector/extractSubVector so that split build-vectors just build two
17144   // narrower build vectors. This helps shuffling with splats and zeros.
17145   auto SplitVector = [&](SDValue V) {
17146     SDValue LoV, HiV;
17147     std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
17148     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
17149                           DAG.getBitcast(SplitVT, HiV));
17150   };
17151 
17152   SDValue LoV1, HiV1, LoV2, HiV2;
17153   std::tie(LoV1, HiV1) = SplitVector(V1);
17154   std::tie(LoV2, HiV2) = SplitVector(V2);
17155 
17156   // Now create two 4-way blends of these half-width vectors.
17157   auto GetHalfBlendPiecesReq = [&](const ArrayRef<int> &HalfMask, bool &UseLoV1,
17158                                    bool &UseHiV1, bool &UseLoV2,
17159                                    bool &UseHiV2) {
17160     UseLoV1 = UseHiV1 = UseLoV2 = UseHiV2 = false;
17161     for (int i = 0; i < SplitNumElements; ++i) {
17162       int M = HalfMask[i];
17163       if (M >= NumElements) {
17164         if (M >= NumElements + SplitNumElements)
17165           UseHiV2 = true;
17166         else
17167           UseLoV2 = true;
17168       } else if (M >= 0) {
17169         if (M >= SplitNumElements)
17170           UseHiV1 = true;
17171         else
17172           UseLoV1 = true;
17173       }
17174     }
17175   };
17176 
17177   auto CheckHalfBlendUsable = [&](const ArrayRef<int> &HalfMask) -> bool {
17178     if (!SimpleOnly)
17179       return true;
17180 
17181     bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
17182     GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
17183 
17184     return !(UseHiV1 || UseHiV2);
17185   };
17186 
17187   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
17188     SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
17189     SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
17190     SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
17191     for (int i = 0; i < SplitNumElements; ++i) {
17192       int M = HalfMask[i];
17193       if (M >= NumElements) {
17194         V2BlendMask[i] = M - NumElements;
17195         BlendMask[i] = SplitNumElements + i;
17196       } else if (M >= 0) {
17197         V1BlendMask[i] = M;
17198         BlendMask[i] = i;
17199       }
17200     }
17201 
17202     bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
17203     GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
17204 
17205     // Because the lowering happens after all combining takes place, we need to
17206     // manually combine these blend masks as much as possible so that we create
17207     // a minimal number of high-level vector shuffle nodes.
17208     assert((!SimpleOnly || (!UseHiV1 && !UseHiV2)) && "Shuffle isn't simple");
17209 
17210     // First try just blending the halves of V1 or V2.
17211     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
17212       return DAG.getUNDEF(SplitVT);
17213     if (!UseLoV2 && !UseHiV2)
17214       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
17215     if (!UseLoV1 && !UseHiV1)
17216       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
17217 
17218     SDValue V1Blend, V2Blend;
17219     if (UseLoV1 && UseHiV1) {
17220       V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
17221     } else {
17222       // We only use half of V1 so map the usage down into the final blend mask.
17223       V1Blend = UseLoV1 ? LoV1 : HiV1;
17224       for (int i = 0; i < SplitNumElements; ++i)
17225         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
17226           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
17227     }
17228     if (UseLoV2 && UseHiV2) {
17229       V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
17230     } else {
17231       // We only use half of V2 so map the usage down into the final blend mask.
17232       V2Blend = UseLoV2 ? LoV2 : HiV2;
17233       for (int i = 0; i < SplitNumElements; ++i)
17234         if (BlendMask[i] >= SplitNumElements)
17235           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
17236     }
17237     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
17238   };
17239 
17240   if (!CheckHalfBlendUsable(LoMask) || !CheckHalfBlendUsable(HiMask))
17241     return SDValue();
17242 
17243   SDValue Lo = HalfBlend(LoMask);
17244   SDValue Hi = HalfBlend(HiMask);
17245   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
17246 }
17247 
17248 /// Either split a vector in halves or decompose the shuffles and the
17249 /// blend/unpack.
17250 ///
17251 /// This is provided as a good fallback for many lowerings of non-single-input
17252 /// shuffles with more than one 128-bit lane. In those cases, we want to select
17253 /// between splitting the shuffle into 128-bit components and stitching those
17254 /// back together vs. extracting the single-input shuffles and blending those
17255 /// results.
17256 static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
17257                                           SDValue V2, ArrayRef<int> Mask,
17258                                           const X86Subtarget &Subtarget,
17259                                           SelectionDAG &DAG) {
17260   assert(!V2.isUndef() && "This routine must not be used to lower single-input "
17261          "shuffles as it could then recurse on itself.");
17262   int Size = Mask.size();
17263 
17264   // If this can be modeled as a broadcast of two elements followed by a blend,
17265   // prefer that lowering. This is especially important because broadcasts can
17266   // often fold with memory operands.
17267   auto DoBothBroadcast = [&] {
17268     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
17269     for (int M : Mask)
17270       if (M >= Size) {
17271         if (V2BroadcastIdx < 0)
17272           V2BroadcastIdx = M - Size;
17273         else if (M - Size != V2BroadcastIdx)
17274           return false;
17275       } else if (M >= 0) {
17276         if (V1BroadcastIdx < 0)
17277           V1BroadcastIdx = M;
17278         else if (M != V1BroadcastIdx)
17279           return false;
17280       }
17281     return true;
17282   };
17283   if (DoBothBroadcast())
17284     return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
17285                                                 DAG);
17286 
17287   // If the inputs all stem from a single 128-bit lane of each input, then we
17288   // split them rather than blending because the split will decompose to
17289   // unusually few instructions.
17290   int LaneCount = VT.getSizeInBits() / 128;
17291   int LaneSize = Size / LaneCount;
17292   SmallBitVector LaneInputs[2];
17293   LaneInputs[0].resize(LaneCount, false);
17294   LaneInputs[1].resize(LaneCount, false);
17295   for (int i = 0; i < Size; ++i)
17296     if (Mask[i] >= 0)
17297       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
17298   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
17299     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
17300                                 /*SimpleOnly*/ false);
17301 
17302   // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
17303   // requires that the decomposed single-input shuffles don't end up here.
17304   return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
17305                                               DAG);
17306 }
17307 
17308 // Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
17309 // TODO: Extend to support v8f32 (+ 512-bit shuffles).
17310 static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
17311                                                  SDValue V1, SDValue V2,
17312                                                  ArrayRef<int> Mask,
17313                                                  SelectionDAG &DAG) {
17314   assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
17315 
17316   int LHSMask[4] = {-1, -1, -1, -1};
17317   int RHSMask[4] = {-1, -1, -1, -1};
17318   unsigned SHUFPMask = 0;
17319 
17320   // As SHUFPD uses a single LHS/RHS element per lane, we can always
17321   // perform the shuffle once the lanes have been shuffled in place.
17322   for (int i = 0; i != 4; ++i) {
17323     int M = Mask[i];
17324     if (M < 0)
17325       continue;
17326     int LaneBase = i & ~1;
17327     auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
17328     LaneMask[LaneBase + (M & 1)] = M;
17329     SHUFPMask |= (M & 1) << i;
17330   }
17331 
17332   SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
17333   SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
17334   return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
17335                      DAG.getTargetConstant(SHUFPMask, DL, MVT::i8));
17336 }
17337 
17338 /// Lower a vector shuffle crossing multiple 128-bit lanes as
17339 /// a lane permutation followed by a per-lane permutation.
17340 ///
17341 /// This is mainly for cases where we can have non-repeating permutes
17342 /// in each lane.
17343 ///
17344 /// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
17345 /// we should investigate merging them.
17346 static SDValue lowerShuffleAsLanePermuteAndPermute(
17347     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
17348     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
17349   int NumElts = VT.getVectorNumElements();
17350   int NumLanes = VT.getSizeInBits() / 128;
17351   int NumEltsPerLane = NumElts / NumLanes;
17352   bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
17353 
17354   /// Attempts to find a sublane permute with the given size
17355   /// that gets all elements into their target lanes.
17356   ///
17357   /// If successful, fills CrossLaneMask and InLaneMask and returns true.
17358   /// If unsuccessful, returns false and may overwrite InLaneMask.
17359   auto getSublanePermute = [&](int NumSublanes) -> SDValue {
17360     int NumSublanesPerLane = NumSublanes / NumLanes;
17361     int NumEltsPerSublane = NumElts / NumSublanes;
17362 
17363     SmallVector<int, 16> CrossLaneMask;
17364     SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
17365     // CrossLaneMask but one entry == one sublane.
17366     SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
17367 
17368     for (int i = 0; i != NumElts; ++i) {
17369       int M = Mask[i];
17370       if (M < 0)
17371         continue;
17372 
17373       int SrcSublane = M / NumEltsPerSublane;
17374       int DstLane = i / NumEltsPerLane;
17375 
17376       // We only need to get the elements into the right lane, not sublane.
17377       // So search all sublanes that make up the destination lane.
17378       bool Found = false;
17379       int DstSubStart = DstLane * NumSublanesPerLane;
17380       int DstSubEnd = DstSubStart + NumSublanesPerLane;
17381       for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
17382         if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
17383           continue;
17384 
17385         Found = true;
17386         CrossLaneMaskLarge[DstSublane] = SrcSublane;
17387         int DstSublaneOffset = DstSublane * NumEltsPerSublane;
17388         InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
17389         break;
17390       }
17391       if (!Found)
17392         return SDValue();
17393     }
17394 
17395     // Fill CrossLaneMask using CrossLaneMaskLarge.
17396     narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
17397 
17398     if (!CanUseSublanes) {
17399       // If we're only shuffling a single lowest lane and the rest are identity
17400       // then don't bother.
17401       // TODO - isShuffleMaskInputInPlace could be extended to something like
17402       // this.
17403       int NumIdentityLanes = 0;
17404       bool OnlyShuffleLowestLane = true;
17405       for (int i = 0; i != NumLanes; ++i) {
17406         int LaneOffset = i * NumEltsPerLane;
17407         if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
17408                                        i * NumEltsPerLane))
17409           NumIdentityLanes++;
17410         else if (CrossLaneMask[LaneOffset] != 0)
17411           OnlyShuffleLowestLane = false;
17412       }
17413       if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
17414         return SDValue();
17415     }
17416 
17417     // Avoid returning the same shuffle operation. For example,
17418     // t7: v16i16 = vector_shuffle<8,9,10,11,4,5,6,7,0,1,2,3,12,13,14,15> t5,
17419     //                             undef:v16i16
17420     if (CrossLaneMask == Mask || InLaneMask == Mask)
17421       return SDValue();
17422 
17423     SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
17424     return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
17425                                 InLaneMask);
17426   };
17427 
17428   // First attempt a solution with full lanes.
17429   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes))
17430     return V;
17431 
17432   // The rest of the solutions use sublanes.
17433   if (!CanUseSublanes)
17434     return SDValue();
17435 
17436   // Then attempt a solution with 64-bit sublanes (vpermq).
17437   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes * 2))
17438     return V;
17439 
17440   // If that doesn't work and we have fast variable cross-lane shuffle,
17441   // attempt 32-bit sublanes (vpermd).
17442   if (!Subtarget.hasFastVariableCrossLaneShuffle())
17443     return SDValue();
17444 
17445   return getSublanePermute(/*NumSublanes=*/NumLanes * 4);
17446 }
17447 
17448 /// Helper to get compute inlane shuffle mask for a complete shuffle mask.
17449 static void computeInLaneShuffleMask(const ArrayRef<int> &Mask, int LaneSize,
17450                                      SmallVector<int> &InLaneMask) {
17451   int Size = Mask.size();
17452   InLaneMask.assign(Mask.begin(), Mask.end());
17453   for (int i = 0; i < Size; ++i) {
17454     int &M = InLaneMask[i];
17455     if (M < 0)
17456       continue;
17457     if (((M % Size) / LaneSize) != (i / LaneSize))
17458       M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
17459   }
17460 }
17461 
17462 /// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
17463 /// source with a lane permutation.
17464 ///
17465 /// This lowering strategy results in four instructions in the worst case for a
17466 /// single-input cross lane shuffle which is lower than any other fully general
17467 /// cross-lane shuffle strategy I'm aware of. Special cases for each particular
17468 /// shuffle pattern should be handled prior to trying this lowering.
17469 static SDValue lowerShuffleAsLanePermuteAndShuffle(
17470     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
17471     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
17472   // FIXME: This should probably be generalized for 512-bit vectors as well.
17473   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
17474   int Size = Mask.size();
17475   int LaneSize = Size / 2;
17476 
17477   // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
17478   // Only do this if the elements aren't all from the lower lane,
17479   // otherwise we're (probably) better off doing a split.
17480   if (VT == MVT::v4f64 &&
17481       !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
17482     return lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG);
17483 
17484   // If there are only inputs from one 128-bit lane, splitting will in fact be
17485   // less expensive. The flags track whether the given lane contains an element
17486   // that crosses to another lane.
17487   bool AllLanes;
17488   if (!Subtarget.hasAVX2()) {
17489     bool LaneCrossing[2] = {false, false};
17490     for (int i = 0; i < Size; ++i)
17491       if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
17492         LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
17493     AllLanes = LaneCrossing[0] && LaneCrossing[1];
17494   } else {
17495     bool LaneUsed[2] = {false, false};
17496     for (int i = 0; i < Size; ++i)
17497       if (Mask[i] >= 0)
17498         LaneUsed[(Mask[i] % Size) / LaneSize] = true;
17499     AllLanes = LaneUsed[0] && LaneUsed[1];
17500   }
17501 
17502   // TODO - we could support shuffling V2 in the Flipped input.
17503   assert(V2.isUndef() &&
17504          "This last part of this routine only works on single input shuffles");
17505 
17506   SmallVector<int> InLaneMask;
17507   computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
17508 
17509   assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
17510          "In-lane shuffle mask expected");
17511 
17512   // If we're not using both lanes in each lane and the inlane mask is not
17513   // repeating, then we're better off splitting.
17514   if (!AllLanes && !is128BitLaneRepeatedShuffleMask(VT, InLaneMask))
17515     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
17516                                 /*SimpleOnly*/ false);
17517 
17518   // Flip the lanes, and shuffle the results which should now be in-lane.
17519   MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
17520   SDValue Flipped = DAG.getBitcast(PVT, V1);
17521   Flipped =
17522       DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
17523   Flipped = DAG.getBitcast(VT, Flipped);
17524   return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
17525 }
17526 
17527 /// Handle lowering 2-lane 128-bit shuffles.
17528 static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
17529                                   SDValue V2, ArrayRef<int> Mask,
17530                                   const APInt &Zeroable,
17531                                   const X86Subtarget &Subtarget,
17532                                   SelectionDAG &DAG) {
17533   if (V2.isUndef()) {
17534     // Attempt to match VBROADCAST*128 subvector broadcast load.
17535     bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
17536     bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
17537     if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
17538         X86::mayFoldLoad(peekThroughOneUseBitcasts(V1), Subtarget)) {
17539       MVT MemVT = VT.getHalfNumVectorElementsVT();
17540       unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
17541       auto *Ld = cast<LoadSDNode>(peekThroughOneUseBitcasts(V1));
17542       if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
17543                                              VT, MemVT, Ld, Ofs, DAG))
17544         return BcstLd;
17545     }
17546 
17547     // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
17548     if (Subtarget.hasAVX2())
17549       return SDValue();
17550   }
17551 
17552   bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
17553 
17554   SmallVector<int, 4> WidenedMask;
17555   if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
17556     return SDValue();
17557 
17558   bool IsLowZero = (Zeroable & 0x3) == 0x3;
17559   bool IsHighZero = (Zeroable & 0xc) == 0xc;
17560 
17561   // Try to use an insert into a zero vector.
17562   if (WidenedMask[0] == 0 && IsHighZero) {
17563     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
17564     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
17565                               DAG.getIntPtrConstant(0, DL));
17566     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17567                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
17568                        DAG.getIntPtrConstant(0, DL));
17569   }
17570 
17571   // TODO: If minimizing size and one of the inputs is a zero vector and the
17572   // the zero vector has only one use, we could use a VPERM2X128 to save the
17573   // instruction bytes needed to explicitly generate the zero vector.
17574 
17575   // Blends are faster and handle all the non-lane-crossing cases.
17576   if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
17577                                           Subtarget, DAG))
17578     return Blend;
17579 
17580   // If either input operand is a zero vector, use VPERM2X128 because its mask
17581   // allows us to replace the zero input with an implicit zero.
17582   if (!IsLowZero && !IsHighZero) {
17583     // Check for patterns which can be matched with a single insert of a 128-bit
17584     // subvector.
17585     bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
17586     if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
17587 
17588       // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
17589       // this will likely become vinsertf128 which can't fold a 256-bit memop.
17590       if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
17591         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
17592         SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
17593                                      OnlyUsesV1 ? V1 : V2,
17594                                      DAG.getIntPtrConstant(0, DL));
17595         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
17596                            DAG.getIntPtrConstant(2, DL));
17597       }
17598     }
17599 
17600     // Try to use SHUF128 if possible.
17601     if (Subtarget.hasVLX()) {
17602       if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
17603         unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
17604                             ((WidenedMask[1] % 2) << 1);
17605         return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
17606                            DAG.getTargetConstant(PermMask, DL, MVT::i8));
17607       }
17608     }
17609   }
17610 
17611   // Otherwise form a 128-bit permutation. After accounting for undefs,
17612   // convert the 64-bit shuffle mask selection values into 128-bit
17613   // selection bits by dividing the indexes by 2 and shifting into positions
17614   // defined by a vperm2*128 instruction's immediate control byte.
17615 
17616   // The immediate permute control byte looks like this:
17617   //    [1:0] - select 128 bits from sources for low half of destination
17618   //    [2]   - ignore
17619   //    [3]   - zero low half of destination
17620   //    [5:4] - select 128 bits from sources for high half of destination
17621   //    [6]   - ignore
17622   //    [7]   - zero high half of destination
17623 
17624   assert((WidenedMask[0] >= 0 || IsLowZero) &&
17625          (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
17626 
17627   unsigned PermMask = 0;
17628   PermMask |= IsLowZero  ? 0x08 : (WidenedMask[0] << 0);
17629   PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
17630 
17631   // Check the immediate mask and replace unused sources with undef.
17632   if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
17633     V1 = DAG.getUNDEF(VT);
17634   if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
17635     V2 = DAG.getUNDEF(VT);
17636 
17637   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
17638                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
17639 }
17640 
17641 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
17642 /// shuffling each lane.
17643 ///
17644 /// This attempts to create a repeated lane shuffle where each lane uses one
17645 /// or two of the lanes of the inputs. The lanes of the input vectors are
17646 /// shuffled in one or two independent shuffles to get the lanes into the
17647 /// position needed by the final shuffle.
17648 static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
17649     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
17650     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
17651   assert(!V2.isUndef() && "This is only useful with multiple inputs.");
17652 
17653   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
17654     return SDValue();
17655 
17656   int NumElts = Mask.size();
17657   int NumLanes = VT.getSizeInBits() / 128;
17658   int NumLaneElts = 128 / VT.getScalarSizeInBits();
17659   SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
17660   SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
17661 
17662   // First pass will try to fill in the RepeatMask from lanes that need two
17663   // sources.
17664   for (int Lane = 0; Lane != NumLanes; ++Lane) {
17665     int Srcs[2] = {-1, -1};
17666     SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
17667     for (int i = 0; i != NumLaneElts; ++i) {
17668       int M = Mask[(Lane * NumLaneElts) + i];
17669       if (M < 0)
17670         continue;
17671       // Determine which of the possible input lanes (NumLanes from each source)
17672       // this element comes from. Assign that as one of the sources for this
17673       // lane. We can assign up to 2 sources for this lane. If we run out
17674       // sources we can't do anything.
17675       int LaneSrc = M / NumLaneElts;
17676       int Src;
17677       if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
17678         Src = 0;
17679       else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
17680         Src = 1;
17681       else
17682         return SDValue();
17683 
17684       Srcs[Src] = LaneSrc;
17685       InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
17686     }
17687 
17688     // If this lane has two sources, see if it fits with the repeat mask so far.
17689     if (Srcs[1] < 0)
17690       continue;
17691 
17692     LaneSrcs[Lane][0] = Srcs[0];
17693     LaneSrcs[Lane][1] = Srcs[1];
17694 
17695     auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
17696       assert(M1.size() == M2.size() && "Unexpected mask size");
17697       for (int i = 0, e = M1.size(); i != e; ++i)
17698         if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
17699           return false;
17700       return true;
17701     };
17702 
17703     auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
17704       assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
17705       for (int i = 0, e = MergedMask.size(); i != e; ++i) {
17706         int M = Mask[i];
17707         if (M < 0)
17708           continue;
17709         assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
17710                "Unexpected mask element");
17711         MergedMask[i] = M;
17712       }
17713     };
17714 
17715     if (MatchMasks(InLaneMask, RepeatMask)) {
17716       // Merge this lane mask into the final repeat mask.
17717       MergeMasks(InLaneMask, RepeatMask);
17718       continue;
17719     }
17720 
17721     // Didn't find a match. Swap the operands and try again.
17722     std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
17723     ShuffleVectorSDNode::commuteMask(InLaneMask);
17724 
17725     if (MatchMasks(InLaneMask, RepeatMask)) {
17726       // Merge this lane mask into the final repeat mask.
17727       MergeMasks(InLaneMask, RepeatMask);
17728       continue;
17729     }
17730 
17731     // Couldn't find a match with the operands in either order.
17732     return SDValue();
17733   }
17734 
17735   // Now handle any lanes with only one source.
17736   for (int Lane = 0; Lane != NumLanes; ++Lane) {
17737     // If this lane has already been processed, skip it.
17738     if (LaneSrcs[Lane][0] >= 0)
17739       continue;
17740 
17741     for (int i = 0; i != NumLaneElts; ++i) {
17742       int M = Mask[(Lane * NumLaneElts) + i];
17743       if (M < 0)
17744         continue;
17745 
17746       // If RepeatMask isn't defined yet we can define it ourself.
17747       if (RepeatMask[i] < 0)
17748         RepeatMask[i] = M % NumLaneElts;
17749 
17750       if (RepeatMask[i] < NumElts) {
17751         if (RepeatMask[i] != M % NumLaneElts)
17752           return SDValue();
17753         LaneSrcs[Lane][0] = M / NumLaneElts;
17754       } else {
17755         if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
17756           return SDValue();
17757         LaneSrcs[Lane][1] = M / NumLaneElts;
17758       }
17759     }
17760 
17761     if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
17762       return SDValue();
17763   }
17764 
17765   SmallVector<int, 16> NewMask(NumElts, -1);
17766   for (int Lane = 0; Lane != NumLanes; ++Lane) {
17767     int Src = LaneSrcs[Lane][0];
17768     for (int i = 0; i != NumLaneElts; ++i) {
17769       int M = -1;
17770       if (Src >= 0)
17771         M = Src * NumLaneElts + i;
17772       NewMask[Lane * NumLaneElts + i] = M;
17773     }
17774   }
17775   SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
17776   // Ensure we didn't get back the shuffle we started with.
17777   // FIXME: This is a hack to make up for some splat handling code in
17778   // getVectorShuffle.
17779   if (isa<ShuffleVectorSDNode>(NewV1) &&
17780       cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
17781     return SDValue();
17782 
17783   for (int Lane = 0; Lane != NumLanes; ++Lane) {
17784     int Src = LaneSrcs[Lane][1];
17785     for (int i = 0; i != NumLaneElts; ++i) {
17786       int M = -1;
17787       if (Src >= 0)
17788         M = Src * NumLaneElts + i;
17789       NewMask[Lane * NumLaneElts + i] = M;
17790     }
17791   }
17792   SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
17793   // Ensure we didn't get back the shuffle we started with.
17794   // FIXME: This is a hack to make up for some splat handling code in
17795   // getVectorShuffle.
17796   if (isa<ShuffleVectorSDNode>(NewV2) &&
17797       cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
17798     return SDValue();
17799 
17800   for (int i = 0; i != NumElts; ++i) {
17801     if (Mask[i] < 0) {
17802       NewMask[i] = -1;
17803       continue;
17804     }
17805     NewMask[i] = RepeatMask[i % NumLaneElts];
17806     if (NewMask[i] < 0)
17807       continue;
17808 
17809     NewMask[i] += (i / NumLaneElts) * NumLaneElts;
17810   }
17811   return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
17812 }
17813 
17814 /// If the input shuffle mask results in a vector that is undefined in all upper
17815 /// or lower half elements and that mask accesses only 2 halves of the
17816 /// shuffle's operands, return true. A mask of half the width with mask indexes
17817 /// adjusted to access the extracted halves of the original shuffle operands is
17818 /// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
17819 /// lower half of each input operand is accessed.
17820 static bool
17821 getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
17822                    int &HalfIdx1, int &HalfIdx2) {
17823   assert((Mask.size() == HalfMask.size() * 2) &&
17824          "Expected input mask to be twice as long as output");
17825 
17826   // Exactly one half of the result must be undef to allow narrowing.
17827   bool UndefLower = isUndefLowerHalf(Mask);
17828   bool UndefUpper = isUndefUpperHalf(Mask);
17829   if (UndefLower == UndefUpper)
17830     return false;
17831 
17832   unsigned HalfNumElts = HalfMask.size();
17833   unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
17834   HalfIdx1 = -1;
17835   HalfIdx2 = -1;
17836   for (unsigned i = 0; i != HalfNumElts; ++i) {
17837     int M = Mask[i + MaskIndexOffset];
17838     if (M < 0) {
17839       HalfMask[i] = M;
17840       continue;
17841     }
17842 
17843     // Determine which of the 4 half vectors this element is from.
17844     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
17845     int HalfIdx = M / HalfNumElts;
17846 
17847     // Determine the element index into its half vector source.
17848     int HalfElt = M % HalfNumElts;
17849 
17850     // We can shuffle with up to 2 half vectors, set the new 'half'
17851     // shuffle mask accordingly.
17852     if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
17853       HalfMask[i] = HalfElt;
17854       HalfIdx1 = HalfIdx;
17855       continue;
17856     }
17857     if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
17858       HalfMask[i] = HalfElt + HalfNumElts;
17859       HalfIdx2 = HalfIdx;
17860       continue;
17861     }
17862 
17863     // Too many half vectors referenced.
17864     return false;
17865   }
17866 
17867   return true;
17868 }
17869 
17870 /// Given the output values from getHalfShuffleMask(), create a half width
17871 /// shuffle of extracted vectors followed by an insert back to full width.
17872 static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
17873                                      ArrayRef<int> HalfMask, int HalfIdx1,
17874                                      int HalfIdx2, bool UndefLower,
17875                                      SelectionDAG &DAG, bool UseConcat = false) {
17876   assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
17877   assert(V1.getValueType().isSimple() && "Expecting only simple types");
17878 
17879   MVT VT = V1.getSimpleValueType();
17880   MVT HalfVT = VT.getHalfNumVectorElementsVT();
17881   unsigned HalfNumElts = HalfVT.getVectorNumElements();
17882 
17883   auto getHalfVector = [&](int HalfIdx) {
17884     if (HalfIdx < 0)
17885       return DAG.getUNDEF(HalfVT);
17886     SDValue V = (HalfIdx < 2 ? V1 : V2);
17887     HalfIdx = (HalfIdx % 2) * HalfNumElts;
17888     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
17889                        DAG.getIntPtrConstant(HalfIdx, DL));
17890   };
17891 
17892   // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
17893   SDValue Half1 = getHalfVector(HalfIdx1);
17894   SDValue Half2 = getHalfVector(HalfIdx2);
17895   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
17896   if (UseConcat) {
17897     SDValue Op0 = V;
17898     SDValue Op1 = DAG.getUNDEF(HalfVT);
17899     if (UndefLower)
17900       std::swap(Op0, Op1);
17901     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
17902   }
17903 
17904   unsigned Offset = UndefLower ? HalfNumElts : 0;
17905   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
17906                      DAG.getIntPtrConstant(Offset, DL));
17907 }
17908 
17909 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
17910 /// This allows for fast cases such as subvector extraction/insertion
17911 /// or shuffling smaller vector types which can lower more efficiently.
17912 static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
17913                                          SDValue V2, ArrayRef<int> Mask,
17914                                          const X86Subtarget &Subtarget,
17915                                          SelectionDAG &DAG) {
17916   assert((VT.is256BitVector() || VT.is512BitVector()) &&
17917          "Expected 256-bit or 512-bit vector");
17918 
17919   bool UndefLower = isUndefLowerHalf(Mask);
17920   if (!UndefLower && !isUndefUpperHalf(Mask))
17921     return SDValue();
17922 
17923   assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
17924          "Completely undef shuffle mask should have been simplified already");
17925 
17926   // Upper half is undef and lower half is whole upper subvector.
17927   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17928   MVT HalfVT = VT.getHalfNumVectorElementsVT();
17929   unsigned HalfNumElts = HalfVT.getVectorNumElements();
17930   if (!UndefLower &&
17931       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
17932     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
17933                              DAG.getIntPtrConstant(HalfNumElts, DL));
17934     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
17935                        DAG.getIntPtrConstant(0, DL));
17936   }
17937 
17938   // Lower half is undef and upper half is whole lower subvector.
17939   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17940   if (UndefLower &&
17941       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
17942     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
17943                              DAG.getIntPtrConstant(0, DL));
17944     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
17945                        DAG.getIntPtrConstant(HalfNumElts, DL));
17946   }
17947 
17948   int HalfIdx1, HalfIdx2;
17949   SmallVector<int, 8> HalfMask(HalfNumElts);
17950   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
17951     return SDValue();
17952 
17953   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
17954 
17955   // Only shuffle the halves of the inputs when useful.
17956   unsigned NumLowerHalves =
17957       (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
17958   unsigned NumUpperHalves =
17959       (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
17960   assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
17961 
17962   // Determine the larger pattern of undef/halves, then decide if it's worth
17963   // splitting the shuffle based on subtarget capabilities and types.
17964   unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
17965   if (!UndefLower) {
17966     // XXXXuuuu: no insert is needed.
17967     // Always extract lowers when setting lower - these are all free subreg ops.
17968     if (NumUpperHalves == 0)
17969       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
17970                                    UndefLower, DAG);
17971 
17972     if (NumUpperHalves == 1) {
17973       // AVX2 has efficient 32/64-bit element cross-lane shuffles.
17974       if (Subtarget.hasAVX2()) {
17975         // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
17976         if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
17977             !is128BitUnpackShuffleMask(HalfMask, DAG) &&
17978             (!isSingleSHUFPSMask(HalfMask) ||
17979              Subtarget.hasFastVariableCrossLaneShuffle()))
17980           return SDValue();
17981         // If this is a unary shuffle (assume that the 2nd operand is
17982         // canonicalized to undef), then we can use vpermpd. Otherwise, we
17983         // are better off extracting the upper half of 1 operand and using a
17984         // narrow shuffle.
17985         if (EltWidth == 64 && V2.isUndef())
17986           return SDValue();
17987       }
17988       // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
17989       if (Subtarget.hasAVX512() && VT.is512BitVector())
17990         return SDValue();
17991       // Extract + narrow shuffle is better than the wide alternative.
17992       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
17993                                    UndefLower, DAG);
17994     }
17995 
17996     // Don't extract both uppers, instead shuffle and then extract.
17997     assert(NumUpperHalves == 2 && "Half vector count went wrong");
17998     return SDValue();
17999   }
18000 
18001   // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
18002   if (NumUpperHalves == 0) {
18003     // AVX2 has efficient 64-bit element cross-lane shuffles.
18004     // TODO: Refine to account for unary shuffle, splat, and other masks?
18005     if (Subtarget.hasAVX2() && EltWidth == 64)
18006       return SDValue();
18007     // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
18008     if (Subtarget.hasAVX512() && VT.is512BitVector())
18009       return SDValue();
18010     // Narrow shuffle + insert is better than the wide alternative.
18011     return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
18012                                  UndefLower, DAG);
18013   }
18014 
18015   // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
18016   return SDValue();
18017 }
18018 
18019 /// Handle case where shuffle sources are coming from the same 128-bit lane and
18020 /// every lane can be represented as the same repeating mask - allowing us to
18021 /// shuffle the sources with the repeating shuffle and then permute the result
18022 /// to the destination lanes.
18023 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
18024     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
18025     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
18026   int NumElts = VT.getVectorNumElements();
18027   int NumLanes = VT.getSizeInBits() / 128;
18028   int NumLaneElts = NumElts / NumLanes;
18029 
18030   // On AVX2 we may be able to just shuffle the lowest elements and then
18031   // broadcast the result.
18032   if (Subtarget.hasAVX2()) {
18033     for (unsigned BroadcastSize : {16, 32, 64}) {
18034       if (BroadcastSize <= VT.getScalarSizeInBits())
18035         continue;
18036       int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
18037 
18038       // Attempt to match a repeating pattern every NumBroadcastElts,
18039       // accounting for UNDEFs but only references the lowest 128-bit
18040       // lane of the inputs.
18041       auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
18042         for (int i = 0; i != NumElts; i += NumBroadcastElts)
18043           for (int j = 0; j != NumBroadcastElts; ++j) {
18044             int M = Mask[i + j];
18045             if (M < 0)
18046               continue;
18047             int &R = RepeatMask[j];
18048             if (0 != ((M % NumElts) / NumLaneElts))
18049               return false;
18050             if (0 <= R && R != M)
18051               return false;
18052             R = M;
18053           }
18054         return true;
18055       };
18056 
18057       SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
18058       if (!FindRepeatingBroadcastMask(RepeatMask))
18059         continue;
18060 
18061       // Shuffle the (lowest) repeated elements in place for broadcast.
18062       SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
18063 
18064       // Shuffle the actual broadcast.
18065       SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
18066       for (int i = 0; i != NumElts; i += NumBroadcastElts)
18067         for (int j = 0; j != NumBroadcastElts; ++j)
18068           BroadcastMask[i + j] = j;
18069       return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
18070                                   BroadcastMask);
18071     }
18072   }
18073 
18074   // Bail if the shuffle mask doesn't cross 128-bit lanes.
18075   if (!is128BitLaneCrossingShuffleMask(VT, Mask))
18076     return SDValue();
18077 
18078   // Bail if we already have a repeated lane shuffle mask.
18079   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
18080     return SDValue();
18081 
18082   // Helper to look for repeated mask in each split sublane, and that those
18083   // sublanes can then be permuted into place.
18084   auto ShuffleSubLanes = [&](int SubLaneScale) {
18085     int NumSubLanes = NumLanes * SubLaneScale;
18086     int NumSubLaneElts = NumLaneElts / SubLaneScale;
18087 
18088     // Check that all the sources are coming from the same lane and see if we
18089     // can form a repeating shuffle mask (local to each sub-lane). At the same
18090     // time, determine the source sub-lane for each destination sub-lane.
18091     int TopSrcSubLane = -1;
18092     SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
18093     SmallVector<SmallVector<int, 8>> RepeatedSubLaneMasks(
18094         SubLaneScale,
18095         SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef));
18096 
18097     for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
18098       // Extract the sub-lane mask, check that it all comes from the same lane
18099       // and normalize the mask entries to come from the first lane.
18100       int SrcLane = -1;
18101       SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
18102       for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
18103         int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
18104         if (M < 0)
18105           continue;
18106         int Lane = (M % NumElts) / NumLaneElts;
18107         if ((0 <= SrcLane) && (SrcLane != Lane))
18108           return SDValue();
18109         SrcLane = Lane;
18110         int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
18111         SubLaneMask[Elt] = LocalM;
18112       }
18113 
18114       // Whole sub-lane is UNDEF.
18115       if (SrcLane < 0)
18116         continue;
18117 
18118       // Attempt to match against the candidate repeated sub-lane masks.
18119       for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
18120         auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
18121           for (int i = 0; i != NumSubLaneElts; ++i) {
18122             if (M1[i] < 0 || M2[i] < 0)
18123               continue;
18124             if (M1[i] != M2[i])
18125               return false;
18126           }
18127           return true;
18128         };
18129 
18130         auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
18131         if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
18132           continue;
18133 
18134         // Merge the sub-lane mask into the matching repeated sub-lane mask.
18135         for (int i = 0; i != NumSubLaneElts; ++i) {
18136           int M = SubLaneMask[i];
18137           if (M < 0)
18138             continue;
18139           assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
18140                  "Unexpected mask element");
18141           RepeatedSubLaneMask[i] = M;
18142         }
18143 
18144         // Track the top most source sub-lane - by setting the remaining to
18145         // UNDEF we can greatly simplify shuffle matching.
18146         int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
18147         TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
18148         Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
18149         break;
18150       }
18151 
18152       // Bail if we failed to find a matching repeated sub-lane mask.
18153       if (Dst2SrcSubLanes[DstSubLane] < 0)
18154         return SDValue();
18155     }
18156     assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
18157            "Unexpected source lane");
18158 
18159     // Create a repeating shuffle mask for the entire vector.
18160     SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
18161     for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
18162       int Lane = SubLane / SubLaneScale;
18163       auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
18164       for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
18165         int M = RepeatedSubLaneMask[Elt];
18166         if (M < 0)
18167           continue;
18168         int Idx = (SubLane * NumSubLaneElts) + Elt;
18169         RepeatedMask[Idx] = M + (Lane * NumLaneElts);
18170       }
18171     }
18172 
18173     // Shuffle each source sub-lane to its destination.
18174     SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
18175     for (int i = 0; i != NumElts; i += NumSubLaneElts) {
18176       int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
18177       if (SrcSubLane < 0)
18178         continue;
18179       for (int j = 0; j != NumSubLaneElts; ++j)
18180         SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
18181     }
18182 
18183     // Avoid returning the same shuffle operation.
18184     // v8i32 = vector_shuffle<0,1,4,5,2,3,6,7> t5, undef:v8i32
18185     if (RepeatedMask == Mask || SubLaneMask == Mask)
18186       return SDValue();
18187 
18188     SDValue RepeatedShuffle =
18189         DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
18190 
18191     return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
18192                                 SubLaneMask);
18193   };
18194 
18195   // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
18196   // (with PERMQ/PERMPD). On AVX2/AVX512BW targets, permuting 32-bit sub-lanes,
18197   // even with a variable shuffle, can be worth it for v32i8/v64i8 vectors.
18198   // Otherwise we can only permute whole 128-bit lanes.
18199   int MinSubLaneScale = 1, MaxSubLaneScale = 1;
18200   if (Subtarget.hasAVX2() && VT.is256BitVector()) {
18201     bool OnlyLowestElts = isUndefOrInRange(Mask, 0, NumLaneElts);
18202     MinSubLaneScale = 2;
18203     MaxSubLaneScale =
18204         (!OnlyLowestElts && V2.isUndef() && VT == MVT::v32i8) ? 4 : 2;
18205   }
18206   if (Subtarget.hasBWI() && VT == MVT::v64i8)
18207     MinSubLaneScale = MaxSubLaneScale = 4;
18208 
18209   for (int Scale = MinSubLaneScale; Scale <= MaxSubLaneScale; Scale *= 2)
18210     if (SDValue Shuffle = ShuffleSubLanes(Scale))
18211       return Shuffle;
18212 
18213   return SDValue();
18214 }
18215 
18216 static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
18217                                    bool &ForceV1Zero, bool &ForceV2Zero,
18218                                    unsigned &ShuffleImm, ArrayRef<int> Mask,
18219                                    const APInt &Zeroable) {
18220   int NumElts = VT.getVectorNumElements();
18221   assert(VT.getScalarSizeInBits() == 64 &&
18222          (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
18223          "Unexpected data type for VSHUFPD");
18224   assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
18225          "Illegal shuffle mask");
18226 
18227   bool ZeroLane[2] = { true, true };
18228   for (int i = 0; i < NumElts; ++i)
18229     ZeroLane[i & 1] &= Zeroable[i];
18230 
18231   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
18232   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
18233   ShuffleImm = 0;
18234   bool ShufpdMask = true;
18235   bool CommutableMask = true;
18236   for (int i = 0; i < NumElts; ++i) {
18237     if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
18238       continue;
18239     if (Mask[i] < 0)
18240       return false;
18241     int Val = (i & 6) + NumElts * (i & 1);
18242     int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
18243     if (Mask[i] < Val || Mask[i] > Val + 1)
18244       ShufpdMask = false;
18245     if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
18246       CommutableMask = false;
18247     ShuffleImm |= (Mask[i] % 2) << i;
18248   }
18249 
18250   if (!ShufpdMask && !CommutableMask)
18251     return false;
18252 
18253   if (!ShufpdMask && CommutableMask)
18254     std::swap(V1, V2);
18255 
18256   ForceV1Zero = ZeroLane[0];
18257   ForceV2Zero = ZeroLane[1];
18258   return true;
18259 }
18260 
18261 static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
18262                                       SDValue V2, ArrayRef<int> Mask,
18263                                       const APInt &Zeroable,
18264                                       const X86Subtarget &Subtarget,
18265                                       SelectionDAG &DAG) {
18266   assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
18267          "Unexpected data type for VSHUFPD");
18268 
18269   unsigned Immediate = 0;
18270   bool ForceV1Zero = false, ForceV2Zero = false;
18271   if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
18272                               Mask, Zeroable))
18273     return SDValue();
18274 
18275   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
18276   if (ForceV1Zero)
18277     V1 = getZeroVector(VT, Subtarget, DAG, DL);
18278   if (ForceV2Zero)
18279     V2 = getZeroVector(VT, Subtarget, DAG, DL);
18280 
18281   return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
18282                      DAG.getTargetConstant(Immediate, DL, MVT::i8));
18283 }
18284 
18285 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
18286 // by zeroable elements in the remaining 24 elements. Turn this into two
18287 // vmovqb instructions shuffled together.
18288 static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
18289                                              SDValue V1, SDValue V2,
18290                                              ArrayRef<int> Mask,
18291                                              const APInt &Zeroable,
18292                                              SelectionDAG &DAG) {
18293   assert(VT == MVT::v32i8 && "Unexpected type!");
18294 
18295   // The first 8 indices should be every 8th element.
18296   if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
18297     return SDValue();
18298 
18299   // Remaining elements need to be zeroable.
18300   if (Zeroable.countl_one() < (Mask.size() - 8))
18301     return SDValue();
18302 
18303   V1 = DAG.getBitcast(MVT::v4i64, V1);
18304   V2 = DAG.getBitcast(MVT::v4i64, V2);
18305 
18306   V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
18307   V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
18308 
18309   // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
18310   // the upper bits of the result using an unpckldq.
18311   SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
18312                                         { 0, 1, 2, 3, 16, 17, 18, 19,
18313                                           4, 5, 6, 7, 20, 21, 22, 23 });
18314   // Insert the unpckldq into a zero vector to widen to v32i8.
18315   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
18316                      DAG.getConstant(0, DL, MVT::v32i8), Unpack,
18317                      DAG.getIntPtrConstant(0, DL));
18318 }
18319 
18320 // a = shuffle v1, v2, mask1    ; interleaving lower lanes of v1 and v2
18321 // b = shuffle v1, v2, mask2    ; interleaving higher lanes of v1 and v2
18322 //     =>
18323 // ul = unpckl v1, v2
18324 // uh = unpckh v1, v2
18325 // a = vperm ul, uh
18326 // b = vperm ul, uh
18327 //
18328 // Pattern-match interleave(256b v1, 256b v2) -> 512b v3 and lower it into unpck
18329 // and permute. We cannot directly match v3 because it is split into two
18330 // 256-bit vectors in earlier isel stages. Therefore, this function matches a
18331 // pair of 256-bit shuffles and makes sure the masks are consecutive.
18332 //
18333 // Once unpck and permute nodes are created, the permute corresponding to this
18334 // shuffle is returned, while the other permute replaces the other half of the
18335 // shuffle in the selection dag.
18336 static SDValue lowerShufflePairAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
18337                                                  SDValue V1, SDValue V2,
18338                                                  ArrayRef<int> Mask,
18339                                                  SelectionDAG &DAG) {
18340   if (VT != MVT::v8f32 && VT != MVT::v8i32 && VT != MVT::v16i16 &&
18341       VT != MVT::v32i8)
18342     return SDValue();
18343   // <B0, B1, B0+1, B1+1, ..., >
18344   auto IsInterleavingPattern = [&](ArrayRef<int> Mask, unsigned Begin0,
18345                                    unsigned Begin1) {
18346     size_t Size = Mask.size();
18347     assert(Size % 2 == 0 && "Expected even mask size");
18348     for (unsigned I = 0; I < Size; I += 2) {
18349       if (Mask[I] != (int)(Begin0 + I / 2) ||
18350           Mask[I + 1] != (int)(Begin1 + I / 2))
18351         return false;
18352     }
18353     return true;
18354   };
18355   // Check which half is this shuffle node
18356   int NumElts = VT.getVectorNumElements();
18357   size_t FirstQtr = NumElts / 2;
18358   size_t ThirdQtr = NumElts + NumElts / 2;
18359   bool IsFirstHalf = IsInterleavingPattern(Mask, 0, NumElts);
18360   bool IsSecondHalf = IsInterleavingPattern(Mask, FirstQtr, ThirdQtr);
18361   if (!IsFirstHalf && !IsSecondHalf)
18362     return SDValue();
18363 
18364   // Find the intersection between shuffle users of V1 and V2.
18365   SmallVector<SDNode *, 2> Shuffles;
18366   for (SDNode *User : V1->uses())
18367     if (User->getOpcode() == ISD::VECTOR_SHUFFLE && User->getOperand(0) == V1 &&
18368         User->getOperand(1) == V2)
18369       Shuffles.push_back(User);
18370   // Limit user size to two for now.
18371   if (Shuffles.size() != 2)
18372     return SDValue();
18373   // Find out which half of the 512-bit shuffles is each smaller shuffle
18374   auto *SVN1 = cast<ShuffleVectorSDNode>(Shuffles[0]);
18375   auto *SVN2 = cast<ShuffleVectorSDNode>(Shuffles[1]);
18376   SDNode *FirstHalf;
18377   SDNode *SecondHalf;
18378   if (IsInterleavingPattern(SVN1->getMask(), 0, NumElts) &&
18379       IsInterleavingPattern(SVN2->getMask(), FirstQtr, ThirdQtr)) {
18380     FirstHalf = Shuffles[0];
18381     SecondHalf = Shuffles[1];
18382   } else if (IsInterleavingPattern(SVN1->getMask(), FirstQtr, ThirdQtr) &&
18383              IsInterleavingPattern(SVN2->getMask(), 0, NumElts)) {
18384     FirstHalf = Shuffles[1];
18385     SecondHalf = Shuffles[0];
18386   } else {
18387     return SDValue();
18388   }
18389   // Lower into unpck and perm. Return the perm of this shuffle and replace
18390   // the other.
18391   SDValue Unpckl = DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
18392   SDValue Unpckh = DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
18393   SDValue Perm1 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
18394                               DAG.getTargetConstant(0x20, DL, MVT::i8));
18395   SDValue Perm2 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
18396                               DAG.getTargetConstant(0x31, DL, MVT::i8));
18397   if (IsFirstHalf) {
18398     DAG.ReplaceAllUsesWith(SecondHalf, &Perm2);
18399     return Perm1;
18400   }
18401   DAG.ReplaceAllUsesWith(FirstHalf, &Perm1);
18402   return Perm2;
18403 }
18404 
18405 /// Handle lowering of 4-lane 64-bit floating point shuffles.
18406 ///
18407 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
18408 /// isn't available.
18409 static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18410                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18411                                  const X86Subtarget &Subtarget,
18412                                  SelectionDAG &DAG) {
18413   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
18414   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
18415   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
18416 
18417   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
18418                                      Subtarget, DAG))
18419     return V;
18420 
18421   if (V2.isUndef()) {
18422     // Check for being able to broadcast a single element.
18423     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
18424                                                     Mask, Subtarget, DAG))
18425       return Broadcast;
18426 
18427     // Use low duplicate instructions for masks that match their pattern.
18428     if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
18429       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
18430 
18431     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
18432       // Non-half-crossing single input shuffles can be lowered with an
18433       // interleaved permutation.
18434       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
18435                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
18436       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
18437                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
18438     }
18439 
18440     // With AVX2 we have direct support for this permutation.
18441     if (Subtarget.hasAVX2())
18442       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
18443                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
18444 
18445     // Try to create an in-lane repeating shuffle mask and then shuffle the
18446     // results into the target lanes.
18447     if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18448             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
18449       return V;
18450 
18451     // Try to permute the lanes and then use a per-lane permute.
18452     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
18453                                                         Mask, DAG, Subtarget))
18454       return V;
18455 
18456     // Otherwise, fall back.
18457     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
18458                                                DAG, Subtarget);
18459   }
18460 
18461   // Use dedicated unpack instructions for masks that match their pattern.
18462   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
18463     return V;
18464 
18465   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
18466                                           Zeroable, Subtarget, DAG))
18467     return Blend;
18468 
18469   // Check if the blend happens to exactly fit that of SHUFPD.
18470   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
18471                                           Zeroable, Subtarget, DAG))
18472     return Op;
18473 
18474   bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
18475   bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
18476 
18477   // If we have lane crossing shuffles AND they don't all come from the lower
18478   // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
18479   // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
18480   // canonicalize to a blend of splat which isn't necessary for this combine.
18481   if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
18482       !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
18483       (V1.getOpcode() != ISD::BUILD_VECTOR) &&
18484       (V2.getOpcode() != ISD::BUILD_VECTOR))
18485     return lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2, Mask, DAG);
18486 
18487   // If we have one input in place, then we can permute the other input and
18488   // blend the result.
18489   if (V1IsInPlace || V2IsInPlace)
18490     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
18491                                                 Subtarget, DAG);
18492 
18493   // Try to create an in-lane repeating shuffle mask and then shuffle the
18494   // results into the target lanes.
18495   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18496           DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
18497     return V;
18498 
18499   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18500   // shuffle. However, if we have AVX2 and either inputs are already in place,
18501   // we will be able to shuffle even across lanes the other input in a single
18502   // instruction so skip this pattern.
18503   if (!(Subtarget.hasAVX2() && (V1IsInPlace || V2IsInPlace)))
18504     if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
18505             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
18506       return V;
18507 
18508   // If we have VLX support, we can use VEXPAND.
18509   if (Subtarget.hasVLX())
18510     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
18511                                          DAG, Subtarget))
18512       return V;
18513 
18514   // If we have AVX2 then we always want to lower with a blend because an v4 we
18515   // can fully permute the elements.
18516   if (Subtarget.hasAVX2())
18517     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
18518                                                 Subtarget, DAG);
18519 
18520   // Otherwise fall back on generic lowering.
18521   return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
18522                                     Subtarget, DAG);
18523 }
18524 
18525 /// Handle lowering of 4-lane 64-bit integer shuffles.
18526 ///
18527 /// This routine is only called when we have AVX2 and thus a reasonable
18528 /// instruction set for v4i64 shuffling..
18529 static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18530                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18531                                  const X86Subtarget &Subtarget,
18532                                  SelectionDAG &DAG) {
18533   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
18534   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
18535   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
18536   assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
18537 
18538   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
18539                                      Subtarget, DAG))
18540     return V;
18541 
18542   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
18543                                           Zeroable, Subtarget, DAG))
18544     return Blend;
18545 
18546   // Check for being able to broadcast a single element.
18547   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
18548                                                   Subtarget, DAG))
18549     return Broadcast;
18550 
18551   // Try to use shift instructions if fast.
18552   if (Subtarget.preferLowerShuffleAsShift())
18553     if (SDValue Shift =
18554             lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
18555                                 Subtarget, DAG, /*BitwiseOnly*/ true))
18556       return Shift;
18557 
18558   if (V2.isUndef()) {
18559     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
18560     // can use lower latency instructions that will operate on both lanes.
18561     SmallVector<int, 2> RepeatedMask;
18562     if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
18563       SmallVector<int, 4> PSHUFDMask;
18564       narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
18565       return DAG.getBitcast(
18566           MVT::v4i64,
18567           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
18568                       DAG.getBitcast(MVT::v8i32, V1),
18569                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
18570     }
18571 
18572     // AVX2 provides a direct instruction for permuting a single input across
18573     // lanes.
18574     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
18575                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
18576   }
18577 
18578   // Try to use shift instructions.
18579   if (SDValue Shift =
18580           lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable, Subtarget,
18581                               DAG, /*BitwiseOnly*/ false))
18582     return Shift;
18583 
18584   // If we have VLX support, we can use VALIGN or VEXPAND.
18585   if (Subtarget.hasVLX()) {
18586     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
18587                                               Subtarget, DAG))
18588       return Rotate;
18589 
18590     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
18591                                          DAG, Subtarget))
18592       return V;
18593   }
18594 
18595   // Try to use PALIGNR.
18596   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
18597                                                 Subtarget, DAG))
18598     return Rotate;
18599 
18600   // Use dedicated unpack instructions for masks that match their pattern.
18601   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
18602     return V;
18603 
18604   bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
18605   bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
18606 
18607   // If we have one input in place, then we can permute the other input and
18608   // blend the result.
18609   if (V1IsInPlace || V2IsInPlace)
18610     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
18611                                                 Subtarget, DAG);
18612 
18613   // Try to create an in-lane repeating shuffle mask and then shuffle the
18614   // results into the target lanes.
18615   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18616           DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
18617     return V;
18618 
18619   // Try to lower to PERMQ(BLENDD(V1,V2)).
18620   if (SDValue V =
18621           lowerShuffleAsBlendAndPermute(DL, MVT::v4i64, V1, V2, Mask, DAG))
18622     return V;
18623 
18624   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18625   // shuffle. However, if we have AVX2 and either inputs are already in place,
18626   // we will be able to shuffle even across lanes the other input in a single
18627   // instruction so skip this pattern.
18628   if (!V1IsInPlace && !V2IsInPlace)
18629     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18630             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
18631       return Result;
18632 
18633   // Otherwise fall back on generic blend lowering.
18634   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
18635                                               Subtarget, DAG);
18636 }
18637 
18638 /// Handle lowering of 8-lane 32-bit floating point shuffles.
18639 ///
18640 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
18641 /// isn't available.
18642 static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18643                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18644                                  const X86Subtarget &Subtarget,
18645                                  SelectionDAG &DAG) {
18646   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
18647   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
18648   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
18649 
18650   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
18651                                           Zeroable, Subtarget, DAG))
18652     return Blend;
18653 
18654   // Check for being able to broadcast a single element.
18655   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
18656                                                   Subtarget, DAG))
18657     return Broadcast;
18658 
18659   if (!Subtarget.hasAVX2()) {
18660     SmallVector<int> InLaneMask;
18661     computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
18662 
18663     if (!is128BitLaneRepeatedShuffleMask(MVT::v8f32, InLaneMask))
18664       if (SDValue R = splitAndLowerShuffle(DL, MVT::v8f32, V1, V2, Mask, DAG,
18665                                            /*SimpleOnly*/ true))
18666         return R;
18667   }
18668   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
18669                                                    Zeroable, Subtarget, DAG))
18670     return DAG.getBitcast(MVT::v8f32, ZExt);
18671 
18672   // If the shuffle mask is repeated in each 128-bit lane, we have many more
18673   // options to efficiently lower the shuffle.
18674   SmallVector<int, 4> RepeatedMask;
18675   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
18676     assert(RepeatedMask.size() == 4 &&
18677            "Repeated masks must be half the mask width!");
18678 
18679     // Use even/odd duplicate instructions for masks that match their pattern.
18680     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
18681       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
18682     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
18683       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
18684 
18685     if (V2.isUndef())
18686       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
18687                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18688 
18689     // Use dedicated unpack instructions for masks that match their pattern.
18690     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
18691       return V;
18692 
18693     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
18694     // have already handled any direct blends.
18695     return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
18696   }
18697 
18698   // Try to create an in-lane repeating shuffle mask and then shuffle the
18699   // results into the target lanes.
18700   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18701           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
18702     return V;
18703 
18704   // If we have a single input shuffle with different shuffle patterns in the
18705   // two 128-bit lanes use the variable mask to VPERMILPS.
18706   if (V2.isUndef()) {
18707     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
18708       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
18709       return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
18710     }
18711     if (Subtarget.hasAVX2()) {
18712       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
18713       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
18714     }
18715     // Otherwise, fall back.
18716     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
18717                                                DAG, Subtarget);
18718   }
18719 
18720   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18721   // shuffle.
18722   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18723           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
18724     return Result;
18725 
18726   // If we have VLX support, we can use VEXPAND.
18727   if (Subtarget.hasVLX())
18728     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
18729                                          DAG, Subtarget))
18730       return V;
18731 
18732   // Try to match an interleave of two v8f32s and lower them as unpck and
18733   // permutes using ymms. This needs to go before we try to split the vectors.
18734   //
18735   // TODO: Expand this to AVX1. Currently v8i32 is casted to v8f32 and hits
18736   // this path inadvertently.
18737   if (Subtarget.hasAVX2() && !Subtarget.hasAVX512())
18738     if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8f32, V1, V2,
18739                                                       Mask, DAG))
18740       return V;
18741 
18742   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
18743   // since after split we get a more efficient code using vpunpcklwd and
18744   // vpunpckhwd instrs than vblend.
18745   if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32, DAG))
18746     return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Subtarget,
18747                                       DAG);
18748 
18749   // If we have AVX2 then we always want to lower with a blend because at v8 we
18750   // can fully permute the elements.
18751   if (Subtarget.hasAVX2())
18752     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
18753                                                 Subtarget, DAG);
18754 
18755   // Otherwise fall back on generic lowering.
18756   return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
18757                                     Subtarget, DAG);
18758 }
18759 
18760 /// Handle lowering of 8-lane 32-bit integer shuffles.
18761 ///
18762 /// This routine is only called when we have AVX2 and thus a reasonable
18763 /// instruction set for v8i32 shuffling..
18764 static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18765                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18766                                  const X86Subtarget &Subtarget,
18767                                  SelectionDAG &DAG) {
18768   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
18769   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
18770   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
18771   assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
18772 
18773   int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
18774 
18775   // Whenever we can lower this as a zext, that instruction is strictly faster
18776   // than any alternative. It also allows us to fold memory operands into the
18777   // shuffle in many cases.
18778   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
18779                                                    Zeroable, Subtarget, DAG))
18780     return ZExt;
18781 
18782   // Try to match an interleave of two v8i32s and lower them as unpck and
18783   // permutes using ymms. This needs to go before we try to split the vectors.
18784   if (!Subtarget.hasAVX512())
18785     if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8i32, V1, V2,
18786                                                       Mask, DAG))
18787       return V;
18788 
18789   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
18790   // since after split we get a more efficient code than vblend by using
18791   // vpunpcklwd and vpunpckhwd instrs.
18792   if (isUnpackWdShuffleMask(Mask, MVT::v8i32, DAG) && !V2.isUndef() &&
18793       !Subtarget.hasAVX512())
18794     return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Subtarget,
18795                                       DAG);
18796 
18797   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
18798                                           Zeroable, Subtarget, DAG))
18799     return Blend;
18800 
18801   // Check for being able to broadcast a single element.
18802   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
18803                                                   Subtarget, DAG))
18804     return Broadcast;
18805 
18806   // Try to use shift instructions if fast.
18807   if (Subtarget.preferLowerShuffleAsShift()) {
18808     if (SDValue Shift =
18809             lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
18810                                 Subtarget, DAG, /*BitwiseOnly*/ true))
18811       return Shift;
18812     if (NumV2Elements == 0)
18813       if (SDValue Rotate =
18814               lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
18815         return Rotate;
18816   }
18817 
18818   // If the shuffle mask is repeated in each 128-bit lane we can use more
18819   // efficient instructions that mirror the shuffles across the two 128-bit
18820   // lanes.
18821   SmallVector<int, 4> RepeatedMask;
18822   bool Is128BitLaneRepeatedShuffle =
18823       is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
18824   if (Is128BitLaneRepeatedShuffle) {
18825     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
18826     if (V2.isUndef())
18827       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
18828                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18829 
18830     // Use dedicated unpack instructions for masks that match their pattern.
18831     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
18832       return V;
18833   }
18834 
18835   // Try to use shift instructions.
18836   if (SDValue Shift =
18837           lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable, Subtarget,
18838                               DAG, /*BitwiseOnly*/ false))
18839     return Shift;
18840 
18841   if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements == 0)
18842     if (SDValue Rotate =
18843             lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
18844       return Rotate;
18845 
18846   // If we have VLX support, we can use VALIGN or EXPAND.
18847   if (Subtarget.hasVLX()) {
18848     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
18849                                               Subtarget, DAG))
18850       return Rotate;
18851 
18852     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
18853                                          DAG, Subtarget))
18854       return V;
18855   }
18856 
18857   // Try to use byte rotation instructions.
18858   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
18859                                                 Subtarget, DAG))
18860     return Rotate;
18861 
18862   // Try to create an in-lane repeating shuffle mask and then shuffle the
18863   // results into the target lanes.
18864   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18865           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
18866     return V;
18867 
18868   if (V2.isUndef()) {
18869     // Try to produce a fixed cross-128-bit lane permute followed by unpack
18870     // because that should be faster than the variable permute alternatives.
18871     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, Mask, V1, V2, DAG))
18872       return V;
18873 
18874     // If the shuffle patterns aren't repeated but it's a single input, directly
18875     // generate a cross-lane VPERMD instruction.
18876     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
18877     return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
18878   }
18879 
18880   // Assume that a single SHUFPS is faster than an alternative sequence of
18881   // multiple instructions (even if the CPU has a domain penalty).
18882   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
18883   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
18884     SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
18885     SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
18886     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
18887                                             CastV1, CastV2, DAG);
18888     return DAG.getBitcast(MVT::v8i32, ShufPS);
18889   }
18890 
18891   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18892   // shuffle.
18893   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18894           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
18895     return Result;
18896 
18897   // Otherwise fall back on generic blend lowering.
18898   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
18899                                               Subtarget, DAG);
18900 }
18901 
18902 /// Handle lowering of 16-lane 16-bit integer shuffles.
18903 ///
18904 /// This routine is only called when we have AVX2 and thus a reasonable
18905 /// instruction set for v16i16 shuffling..
18906 static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18907                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18908                                   const X86Subtarget &Subtarget,
18909                                   SelectionDAG &DAG) {
18910   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
18911   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
18912   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
18913   assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
18914 
18915   // Whenever we can lower this as a zext, that instruction is strictly faster
18916   // than any alternative. It also allows us to fold memory operands into the
18917   // shuffle in many cases.
18918   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18919           DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
18920     return ZExt;
18921 
18922   // Check for being able to broadcast a single element.
18923   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
18924                                                   Subtarget, DAG))
18925     return Broadcast;
18926 
18927   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
18928                                           Zeroable, Subtarget, DAG))
18929     return Blend;
18930 
18931   // Use dedicated unpack instructions for masks that match their pattern.
18932   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
18933     return V;
18934 
18935   // Use dedicated pack instructions for masks that match their pattern.
18936   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
18937                                        Subtarget))
18938     return V;
18939 
18940   // Try to use lower using a truncation.
18941   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
18942                                        Subtarget, DAG))
18943     return V;
18944 
18945   // Try to use shift instructions.
18946   if (SDValue Shift =
18947           lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
18948                               Subtarget, DAG, /*BitwiseOnly*/ false))
18949     return Shift;
18950 
18951   // Try to use byte rotation instructions.
18952   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
18953                                                 Subtarget, DAG))
18954     return Rotate;
18955 
18956   // Try to create an in-lane repeating shuffle mask and then shuffle the
18957   // results into the target lanes.
18958   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18959           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
18960     return V;
18961 
18962   if (V2.isUndef()) {
18963     // Try to use bit rotation instructions.
18964     if (SDValue Rotate =
18965             lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
18966       return Rotate;
18967 
18968     // Try to produce a fixed cross-128-bit lane permute followed by unpack
18969     // because that should be faster than the variable permute alternatives.
18970     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, Mask, V1, V2, DAG))
18971       return V;
18972 
18973     // There are no generalized cross-lane shuffle operations available on i16
18974     // element types.
18975     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
18976       if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
18977               DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
18978         return V;
18979 
18980       return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
18981                                                  DAG, Subtarget);
18982     }
18983 
18984     SmallVector<int, 8> RepeatedMask;
18985     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
18986       // As this is a single-input shuffle, the repeated mask should be
18987       // a strictly valid v8i16 mask that we can pass through to the v8i16
18988       // lowering to handle even the v16 case.
18989       return lowerV8I16GeneralSingleInputShuffle(
18990           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
18991     }
18992   }
18993 
18994   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
18995                                               Zeroable, Subtarget, DAG))
18996     return PSHUFB;
18997 
18998   // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
18999   if (Subtarget.hasBWI())
19000     return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
19001 
19002   // Try to simplify this by merging 128-bit lanes to enable a lane-based
19003   // shuffle.
19004   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
19005           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
19006     return Result;
19007 
19008   // Try to permute the lanes and then use a per-lane permute.
19009   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
19010           DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
19011     return V;
19012 
19013   // Try to match an interleave of two v16i16s and lower them as unpck and
19014   // permutes using ymms.
19015   if (!Subtarget.hasAVX512())
19016     if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v16i16, V1, V2,
19017                                                       Mask, DAG))
19018       return V;
19019 
19020   // Otherwise fall back on generic lowering.
19021   return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
19022                                     Subtarget, DAG);
19023 }
19024 
19025 /// Handle lowering of 32-lane 8-bit integer shuffles.
19026 ///
19027 /// This routine is only called when we have AVX2 and thus a reasonable
19028 /// instruction set for v32i8 shuffling..
19029 static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
19030                                  const APInt &Zeroable, SDValue V1, SDValue V2,
19031                                  const X86Subtarget &Subtarget,
19032                                  SelectionDAG &DAG) {
19033   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
19034   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
19035   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
19036   assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
19037 
19038   // Whenever we can lower this as a zext, that instruction is strictly faster
19039   // than any alternative. It also allows us to fold memory operands into the
19040   // shuffle in many cases.
19041   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
19042                                                    Zeroable, Subtarget, DAG))
19043     return ZExt;
19044 
19045   // Check for being able to broadcast a single element.
19046   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
19047                                                   Subtarget, DAG))
19048     return Broadcast;
19049 
19050   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
19051                                           Zeroable, Subtarget, DAG))
19052     return Blend;
19053 
19054   // Use dedicated unpack instructions for masks that match their pattern.
19055   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
19056     return V;
19057 
19058   // Use dedicated pack instructions for masks that match their pattern.
19059   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
19060                                        Subtarget))
19061     return V;
19062 
19063   // Try to use lower using a truncation.
19064   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
19065                                        Subtarget, DAG))
19066     return V;
19067 
19068   // Try to use shift instructions.
19069   if (SDValue Shift =
19070           lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, Zeroable, Subtarget,
19071                               DAG, /*BitwiseOnly*/ false))
19072     return Shift;
19073 
19074   // Try to use byte rotation instructions.
19075   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
19076                                                 Subtarget, DAG))
19077     return Rotate;
19078 
19079   // Try to use bit rotation instructions.
19080   if (V2.isUndef())
19081     if (SDValue Rotate =
19082             lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
19083       return Rotate;
19084 
19085   // Try to create an in-lane repeating shuffle mask and then shuffle the
19086   // results into the target lanes.
19087   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
19088           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
19089     return V;
19090 
19091   // There are no generalized cross-lane shuffle operations available on i8
19092   // element types.
19093   if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
19094     // Try to produce a fixed cross-128-bit lane permute followed by unpack
19095     // because that should be faster than the variable permute alternatives.
19096     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, Mask, V1, V2, DAG))
19097       return V;
19098 
19099     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
19100             DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
19101       return V;
19102 
19103     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
19104                                                DAG, Subtarget);
19105   }
19106 
19107   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
19108                                               Zeroable, Subtarget, DAG))
19109     return PSHUFB;
19110 
19111   // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
19112   if (Subtarget.hasVBMI())
19113     return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
19114 
19115   // Try to simplify this by merging 128-bit lanes to enable a lane-based
19116   // shuffle.
19117   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
19118           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
19119     return Result;
19120 
19121   // Try to permute the lanes and then use a per-lane permute.
19122   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
19123           DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
19124     return V;
19125 
19126   // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
19127   // by zeroable elements in the remaining 24 elements. Turn this into two
19128   // vmovqb instructions shuffled together.
19129   if (Subtarget.hasVLX())
19130     if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
19131                                                   Mask, Zeroable, DAG))
19132       return V;
19133 
19134   // Try to match an interleave of two v32i8s and lower them as unpck and
19135   // permutes using ymms.
19136   if (!Subtarget.hasAVX512())
19137     if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v32i8, V1, V2,
19138                                                       Mask, DAG))
19139       return V;
19140 
19141   // Otherwise fall back on generic lowering.
19142   return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
19143                                     Subtarget, DAG);
19144 }
19145 
19146 /// High-level routine to lower various 256-bit x86 vector shuffles.
19147 ///
19148 /// This routine either breaks down the specific type of a 256-bit x86 vector
19149 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
19150 /// together based on the available instructions.
19151 static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
19152                                   SDValue V1, SDValue V2, const APInt &Zeroable,
19153                                   const X86Subtarget &Subtarget,
19154                                   SelectionDAG &DAG) {
19155   // If we have a single input to the zero element, insert that into V1 if we
19156   // can do so cheaply.
19157   int NumElts = VT.getVectorNumElements();
19158   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
19159 
19160   if (NumV2Elements == 1 && Mask[0] >= NumElts)
19161     if (SDValue Insertion = lowerShuffleAsElementInsertion(
19162             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
19163       return Insertion;
19164 
19165   // Handle special cases where the lower or upper half is UNDEF.
19166   if (SDValue V =
19167           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
19168     return V;
19169 
19170   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
19171   // can check for those subtargets here and avoid much of the subtarget
19172   // querying in the per-vector-type lowering routines. With AVX1 we have
19173   // essentially *zero* ability to manipulate a 256-bit vector with integer
19174   // types. Since we'll use floating point types there eventually, just
19175   // immediately cast everything to a float and operate entirely in that domain.
19176   if (VT.isInteger() && !Subtarget.hasAVX2()) {
19177     int ElementBits = VT.getScalarSizeInBits();
19178     if (ElementBits < 32) {
19179       // No floating point type available, if we can't use the bit operations
19180       // for masking/blending then decompose into 128-bit vectors.
19181       if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
19182                                             Subtarget, DAG))
19183         return V;
19184       if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
19185         return V;
19186       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
19187     }
19188 
19189     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
19190                                 VT.getVectorNumElements());
19191     V1 = DAG.getBitcast(FpVT, V1);
19192     V2 = DAG.getBitcast(FpVT, V2);
19193     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
19194   }
19195 
19196   if (VT == MVT::v16f16 || VT == MVT::v16bf16) {
19197     V1 = DAG.getBitcast(MVT::v16i16, V1);
19198     V2 = DAG.getBitcast(MVT::v16i16, V2);
19199     return DAG.getBitcast(VT,
19200                           DAG.getVectorShuffle(MVT::v16i16, DL, V1, V2, Mask));
19201   }
19202 
19203   switch (VT.SimpleTy) {
19204   case MVT::v4f64:
19205     return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19206   case MVT::v4i64:
19207     return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19208   case MVT::v8f32:
19209     return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19210   case MVT::v8i32:
19211     return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19212   case MVT::v16i16:
19213     return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19214   case MVT::v32i8:
19215     return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19216 
19217   default:
19218     llvm_unreachable("Not a valid 256-bit x86 vector type!");
19219   }
19220 }
19221 
19222 /// Try to lower a vector shuffle as a 128-bit shuffles.
19223 static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
19224                                   const APInt &Zeroable, SDValue V1, SDValue V2,
19225                                   const X86Subtarget &Subtarget,
19226                                   SelectionDAG &DAG) {
19227   assert(VT.getScalarSizeInBits() == 64 &&
19228          "Unexpected element type size for 128bit shuffle.");
19229 
19230   // To handle 256 bit vector requires VLX and most probably
19231   // function lowerV2X128VectorShuffle() is better solution.
19232   assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
19233 
19234   // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
19235   SmallVector<int, 4> Widened128Mask;
19236   if (!canWidenShuffleElements(Mask, Widened128Mask))
19237     return SDValue();
19238   assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
19239 
19240   // Try to use an insert into a zero vector.
19241   if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
19242       (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
19243     unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
19244     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
19245     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
19246                               DAG.getIntPtrConstant(0, DL));
19247     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
19248                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
19249                        DAG.getIntPtrConstant(0, DL));
19250   }
19251 
19252   // Check for patterns which can be matched with a single insert of a 256-bit
19253   // subvector.
19254   bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
19255   if (OnlyUsesV1 ||
19256       isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
19257     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
19258     SDValue SubVec =
19259         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
19260                     DAG.getIntPtrConstant(0, DL));
19261     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
19262                        DAG.getIntPtrConstant(4, DL));
19263   }
19264 
19265   // See if this is an insertion of the lower 128-bits of V2 into V1.
19266   bool IsInsert = true;
19267   int V2Index = -1;
19268   for (int i = 0; i < 4; ++i) {
19269     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
19270     if (Widened128Mask[i] < 0)
19271       continue;
19272 
19273     // Make sure all V1 subvectors are in place.
19274     if (Widened128Mask[i] < 4) {
19275       if (Widened128Mask[i] != i) {
19276         IsInsert = false;
19277         break;
19278       }
19279     } else {
19280       // Make sure we only have a single V2 index and its the lowest 128-bits.
19281       if (V2Index >= 0 || Widened128Mask[i] != 4) {
19282         IsInsert = false;
19283         break;
19284       }
19285       V2Index = i;
19286     }
19287   }
19288   if (IsInsert && V2Index >= 0) {
19289     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
19290     SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
19291                                  DAG.getIntPtrConstant(0, DL));
19292     return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
19293   }
19294 
19295   // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
19296   // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
19297   // possible we at least ensure the lanes stay sequential to help later
19298   // combines.
19299   SmallVector<int, 2> Widened256Mask;
19300   if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
19301     Widened128Mask.clear();
19302     narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
19303   }
19304 
19305   // Try to lower to vshuf64x2/vshuf32x4.
19306   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
19307   unsigned PermMask = 0;
19308   // Insure elements came from the same Op.
19309   for (int i = 0; i < 4; ++i) {
19310     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
19311     if (Widened128Mask[i] < 0)
19312       continue;
19313 
19314     SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
19315     unsigned OpIndex = i / 2;
19316     if (Ops[OpIndex].isUndef())
19317       Ops[OpIndex] = Op;
19318     else if (Ops[OpIndex] != Op)
19319       return SDValue();
19320 
19321     // Convert the 128-bit shuffle mask selection values into 128-bit selection
19322     // bits defined by a vshuf64x2 instruction's immediate control byte.
19323     PermMask |= (Widened128Mask[i] % 4) << (i * 2);
19324   }
19325 
19326   return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
19327                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
19328 }
19329 
19330 /// Handle lowering of 8-lane 64-bit floating point shuffles.
19331 static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
19332                                  const APInt &Zeroable, SDValue V1, SDValue V2,
19333                                  const X86Subtarget &Subtarget,
19334                                  SelectionDAG &DAG) {
19335   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
19336   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
19337   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
19338 
19339   if (V2.isUndef()) {
19340     // Use low duplicate instructions for masks that match their pattern.
19341     if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
19342       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
19343 
19344     if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
19345       // Non-half-crossing single input shuffles can be lowered with an
19346       // interleaved permutation.
19347       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
19348                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
19349                               ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
19350                               ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
19351       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
19352                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
19353     }
19354 
19355     SmallVector<int, 4> RepeatedMask;
19356     if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
19357       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
19358                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
19359   }
19360 
19361   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
19362                                            V2, Subtarget, DAG))
19363     return Shuf128;
19364 
19365   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
19366     return Unpck;
19367 
19368   // Check if the blend happens to exactly fit that of SHUFPD.
19369   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
19370                                           Zeroable, Subtarget, DAG))
19371     return Op;
19372 
19373   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
19374                                        DAG, Subtarget))
19375     return V;
19376 
19377   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
19378                                           Zeroable, Subtarget, DAG))
19379     return Blend;
19380 
19381   return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
19382 }
19383 
19384 /// Handle lowering of 16-lane 32-bit floating point shuffles.
19385 static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
19386                                   const APInt &Zeroable, SDValue V1, SDValue V2,
19387                                   const X86Subtarget &Subtarget,
19388                                   SelectionDAG &DAG) {
19389   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
19390   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
19391   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
19392 
19393   // If the shuffle mask is repeated in each 128-bit lane, we have many more
19394   // options to efficiently lower the shuffle.
19395   SmallVector<int, 4> RepeatedMask;
19396   if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
19397     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
19398 
19399     // Use even/odd duplicate instructions for masks that match their pattern.
19400     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
19401       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
19402     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
19403       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
19404 
19405     if (V2.isUndef())
19406       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
19407                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
19408 
19409     // Use dedicated unpack instructions for masks that match their pattern.
19410     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
19411       return V;
19412 
19413     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
19414                                             Zeroable, Subtarget, DAG))
19415       return Blend;
19416 
19417     // Otherwise, fall back to a SHUFPS sequence.
19418     return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
19419   }
19420 
19421   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
19422                                           Zeroable, Subtarget, DAG))
19423     return Blend;
19424 
19425   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
19426           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
19427     return DAG.getBitcast(MVT::v16f32, ZExt);
19428 
19429   // Try to create an in-lane repeating shuffle mask and then shuffle the
19430   // results into the target lanes.
19431   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
19432           DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
19433     return V;
19434 
19435   // If we have a single input shuffle with different shuffle patterns in the
19436   // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
19437   if (V2.isUndef() &&
19438       !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
19439     SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
19440     return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
19441   }
19442 
19443   // If we have AVX512F support, we can use VEXPAND.
19444   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
19445                                              V1, V2, DAG, Subtarget))
19446     return V;
19447 
19448   return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
19449 }
19450 
19451 /// Handle lowering of 8-lane 64-bit integer shuffles.
19452 static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
19453                                  const APInt &Zeroable, SDValue V1, SDValue V2,
19454                                  const X86Subtarget &Subtarget,
19455                                  SelectionDAG &DAG) {
19456   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
19457   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
19458   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
19459 
19460   // Try to use shift instructions if fast.
19461   if (Subtarget.preferLowerShuffleAsShift())
19462     if (SDValue Shift =
19463             lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
19464                                 Subtarget, DAG, /*BitwiseOnly*/ true))
19465       return Shift;
19466 
19467   if (V2.isUndef()) {
19468     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
19469     // can use lower latency instructions that will operate on all four
19470     // 128-bit lanes.
19471     SmallVector<int, 2> Repeated128Mask;
19472     if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
19473       SmallVector<int, 4> PSHUFDMask;
19474       narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
19475       return DAG.getBitcast(
19476           MVT::v8i64,
19477           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
19478                       DAG.getBitcast(MVT::v16i32, V1),
19479                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
19480     }
19481 
19482     SmallVector<int, 4> Repeated256Mask;
19483     if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
19484       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
19485                          getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
19486   }
19487 
19488   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
19489                                            V2, Subtarget, DAG))
19490     return Shuf128;
19491 
19492   // Try to use shift instructions.
19493   if (SDValue Shift =
19494           lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable, Subtarget,
19495                               DAG, /*BitwiseOnly*/ false))
19496     return Shift;
19497 
19498   // Try to use VALIGN.
19499   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
19500                                             Subtarget, DAG))
19501     return Rotate;
19502 
19503   // Try to use PALIGNR.
19504   if (Subtarget.hasBWI())
19505     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
19506                                                   Subtarget, DAG))
19507       return Rotate;
19508 
19509   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
19510     return Unpck;
19511 
19512   // If we have AVX512F support, we can use VEXPAND.
19513   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
19514                                        DAG, Subtarget))
19515     return V;
19516 
19517   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
19518                                           Zeroable, Subtarget, DAG))
19519     return Blend;
19520 
19521   return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
19522 }
19523 
19524 /// Handle lowering of 16-lane 32-bit integer shuffles.
19525 static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
19526                                   const APInt &Zeroable, SDValue V1, SDValue V2,
19527                                   const X86Subtarget &Subtarget,
19528                                   SelectionDAG &DAG) {
19529   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
19530   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
19531   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
19532 
19533   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
19534 
19535   // Whenever we can lower this as a zext, that instruction is strictly faster
19536   // than any alternative. It also allows us to fold memory operands into the
19537   // shuffle in many cases.
19538   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
19539           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
19540     return ZExt;
19541 
19542   // Try to use shift instructions if fast.
19543   if (Subtarget.preferLowerShuffleAsShift()) {
19544     if (SDValue Shift =
19545             lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
19546                                 Subtarget, DAG, /*BitwiseOnly*/ true))
19547       return Shift;
19548     if (NumV2Elements == 0)
19549       if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask,
19550                                                    Subtarget, DAG))
19551         return Rotate;
19552   }
19553 
19554   // If the shuffle mask is repeated in each 128-bit lane we can use more
19555   // efficient instructions that mirror the shuffles across the four 128-bit
19556   // lanes.
19557   SmallVector<int, 4> RepeatedMask;
19558   bool Is128BitLaneRepeatedShuffle =
19559       is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
19560   if (Is128BitLaneRepeatedShuffle) {
19561     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
19562     if (V2.isUndef())
19563       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
19564                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
19565 
19566     // Use dedicated unpack instructions for masks that match their pattern.
19567     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
19568       return V;
19569   }
19570 
19571   // Try to use shift instructions.
19572   if (SDValue Shift =
19573           lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
19574                               Subtarget, DAG, /*BitwiseOnly*/ false))
19575     return Shift;
19576 
19577   if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements != 0)
19578     if (SDValue Rotate =
19579             lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask, Subtarget, DAG))
19580       return Rotate;
19581 
19582   // Try to use VALIGN.
19583   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
19584                                             Subtarget, DAG))
19585     return Rotate;
19586 
19587   // Try to use byte rotation instructions.
19588   if (Subtarget.hasBWI())
19589     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
19590                                                   Subtarget, DAG))
19591       return Rotate;
19592 
19593   // Assume that a single SHUFPS is faster than using a permv shuffle.
19594   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
19595   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
19596     SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
19597     SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
19598     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
19599                                             CastV1, CastV2, DAG);
19600     return DAG.getBitcast(MVT::v16i32, ShufPS);
19601   }
19602 
19603   // Try to create an in-lane repeating shuffle mask and then shuffle the
19604   // results into the target lanes.
19605   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
19606           DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
19607     return V;
19608 
19609   // If we have AVX512F support, we can use VEXPAND.
19610   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
19611                                        DAG, Subtarget))
19612     return V;
19613 
19614   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
19615                                           Zeroable, Subtarget, DAG))
19616     return Blend;
19617 
19618   return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
19619 }
19620 
19621 /// Handle lowering of 32-lane 16-bit integer shuffles.
19622 static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
19623                                   const APInt &Zeroable, SDValue V1, SDValue V2,
19624                                   const X86Subtarget &Subtarget,
19625                                   SelectionDAG &DAG) {
19626   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
19627   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
19628   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
19629   assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
19630 
19631   // Whenever we can lower this as a zext, that instruction is strictly faster
19632   // than any alternative. It also allows us to fold memory operands into the
19633   // shuffle in many cases.
19634   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
19635           DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
19636     return ZExt;
19637 
19638   // Use dedicated unpack instructions for masks that match their pattern.
19639   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
19640     return V;
19641 
19642   // Use dedicated pack instructions for masks that match their pattern.
19643   if (SDValue V =
19644           lowerShuffleWithPACK(DL, MVT::v32i16, Mask, V1, V2, DAG, Subtarget))
19645     return V;
19646 
19647   // Try to use shift instructions.
19648   if (SDValue Shift =
19649           lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask, Zeroable,
19650                               Subtarget, DAG, /*BitwiseOnly*/ false))
19651     return Shift;
19652 
19653   // Try to use byte rotation instructions.
19654   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
19655                                                 Subtarget, DAG))
19656     return Rotate;
19657 
19658   if (V2.isUndef()) {
19659     // Try to use bit rotation instructions.
19660     if (SDValue Rotate =
19661             lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
19662       return Rotate;
19663 
19664     SmallVector<int, 8> RepeatedMask;
19665     if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
19666       // As this is a single-input shuffle, the repeated mask should be
19667       // a strictly valid v8i16 mask that we can pass through to the v8i16
19668       // lowering to handle even the v32 case.
19669       return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
19670                                                  RepeatedMask, Subtarget, DAG);
19671     }
19672   }
19673 
19674   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
19675                                           Zeroable, Subtarget, DAG))
19676     return Blend;
19677 
19678   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
19679                                               Zeroable, Subtarget, DAG))
19680     return PSHUFB;
19681 
19682   return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
19683 }
19684 
19685 /// Handle lowering of 64-lane 8-bit integer shuffles.
19686 static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
19687                                  const APInt &Zeroable, SDValue V1, SDValue V2,
19688                                  const X86Subtarget &Subtarget,
19689                                  SelectionDAG &DAG) {
19690   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
19691   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
19692   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
19693   assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
19694 
19695   // Whenever we can lower this as a zext, that instruction is strictly faster
19696   // than any alternative. It also allows us to fold memory operands into the
19697   // shuffle in many cases.
19698   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
19699           DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
19700     return ZExt;
19701 
19702   // Use dedicated unpack instructions for masks that match their pattern.
19703   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
19704     return V;
19705 
19706   // Use dedicated pack instructions for masks that match their pattern.
19707   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
19708                                        Subtarget))
19709     return V;
19710 
19711   // Try to use shift instructions.
19712   if (SDValue Shift =
19713           lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget,
19714                               DAG, /*BitwiseOnly*/ false))
19715     return Shift;
19716 
19717   // Try to use byte rotation instructions.
19718   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
19719                                                 Subtarget, DAG))
19720     return Rotate;
19721 
19722   // Try to use bit rotation instructions.
19723   if (V2.isUndef())
19724     if (SDValue Rotate =
19725             lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
19726       return Rotate;
19727 
19728   // Lower as AND if possible.
19729   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask,
19730                                              Zeroable, Subtarget, DAG))
19731     return Masked;
19732 
19733   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
19734                                               Zeroable, Subtarget, DAG))
19735     return PSHUFB;
19736 
19737   // Try to create an in-lane repeating shuffle mask and then shuffle the
19738   // results into the target lanes.
19739   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
19740           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
19741     return V;
19742 
19743   if (SDValue Result = lowerShuffleAsLanePermuteAndPermute(
19744           DL, MVT::v64i8, V1, V2, Mask, DAG, Subtarget))
19745     return Result;
19746 
19747   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
19748                                           Zeroable, Subtarget, DAG))
19749     return Blend;
19750 
19751   if (!is128BitLaneCrossingShuffleMask(MVT::v64i8, Mask)) {
19752     // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
19753     // PALIGNR will be cheaper than the second PSHUFB+OR.
19754     if (SDValue V = lowerShuffleAsByteRotateAndPermute(DL, MVT::v64i8, V1, V2,
19755                                                        Mask, Subtarget, DAG))
19756       return V;
19757 
19758     // If we can't directly blend but can use PSHUFB, that will be better as it
19759     // can both shuffle and set up the inefficient blend.
19760     bool V1InUse, V2InUse;
19761     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v64i8, V1, V2, Mask, Zeroable,
19762                                         DAG, V1InUse, V2InUse);
19763   }
19764 
19765   // Try to simplify this by merging 128-bit lanes to enable a lane-based
19766   // shuffle.
19767   if (!V2.isUndef())
19768     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
19769             DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
19770       return Result;
19771 
19772   // VBMI can use VPERMV/VPERMV3 byte shuffles.
19773   if (Subtarget.hasVBMI())
19774     return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
19775 
19776   return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
19777 }
19778 
19779 /// High-level routine to lower various 512-bit x86 vector shuffles.
19780 ///
19781 /// This routine either breaks down the specific type of a 512-bit x86 vector
19782 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
19783 /// together based on the available instructions.
19784 static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
19785                                   MVT VT, SDValue V1, SDValue V2,
19786                                   const APInt &Zeroable,
19787                                   const X86Subtarget &Subtarget,
19788                                   SelectionDAG &DAG) {
19789   assert(Subtarget.hasAVX512() &&
19790          "Cannot lower 512-bit vectors w/ basic ISA!");
19791 
19792   // If we have a single input to the zero element, insert that into V1 if we
19793   // can do so cheaply.
19794   int NumElts = Mask.size();
19795   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
19796 
19797   if (NumV2Elements == 1 && Mask[0] >= NumElts)
19798     if (SDValue Insertion = lowerShuffleAsElementInsertion(
19799             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
19800       return Insertion;
19801 
19802   // Handle special cases where the lower or upper half is UNDEF.
19803   if (SDValue V =
19804           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
19805     return V;
19806 
19807   // Check for being able to broadcast a single element.
19808   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
19809                                                   Subtarget, DAG))
19810     return Broadcast;
19811 
19812   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
19813     // Try using bit ops for masking and blending before falling back to
19814     // splitting.
19815     if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
19816                                           Subtarget, DAG))
19817       return V;
19818     if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
19819       return V;
19820 
19821     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
19822   }
19823 
19824   if (VT == MVT::v32f16) {
19825     if (!Subtarget.hasBWI())
19826       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
19827                                   /*SimpleOnly*/ false);
19828 
19829     V1 = DAG.getBitcast(MVT::v32i16, V1);
19830     V2 = DAG.getBitcast(MVT::v32i16, V2);
19831     return DAG.getBitcast(MVT::v32f16,
19832                           DAG.getVectorShuffle(MVT::v32i16, DL, V1, V2, Mask));
19833   }
19834 
19835   // Dispatch to each element type for lowering. If we don't have support for
19836   // specific element type shuffles at 512 bits, immediately split them and
19837   // lower them. Each lowering routine of a given type is allowed to assume that
19838   // the requisite ISA extensions for that element type are available.
19839   switch (VT.SimpleTy) {
19840   case MVT::v8f64:
19841     return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19842   case MVT::v16f32:
19843     return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19844   case MVT::v8i64:
19845     return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19846   case MVT::v16i32:
19847     return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19848   case MVT::v32i16:
19849     return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19850   case MVT::v64i8:
19851     return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
19852 
19853   default:
19854     llvm_unreachable("Not a valid 512-bit x86 vector type!");
19855   }
19856 }
19857 
19858 static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
19859                                          MVT VT, SDValue V1, SDValue V2,
19860                                          const X86Subtarget &Subtarget,
19861                                          SelectionDAG &DAG) {
19862   // Shuffle should be unary.
19863   if (!V2.isUndef())
19864     return SDValue();
19865 
19866   int ShiftAmt = -1;
19867   int NumElts = Mask.size();
19868   for (int i = 0; i != NumElts; ++i) {
19869     int M = Mask[i];
19870     assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
19871            "Unexpected mask index.");
19872     if (M < 0)
19873       continue;
19874 
19875     // The first non-undef element determines our shift amount.
19876     if (ShiftAmt < 0) {
19877       ShiftAmt = M - i;
19878       // Need to be shifting right.
19879       if (ShiftAmt <= 0)
19880         return SDValue();
19881     }
19882     // All non-undef elements must shift by the same amount.
19883     if (ShiftAmt != M - i)
19884       return SDValue();
19885   }
19886   assert(ShiftAmt >= 0 && "All undef?");
19887 
19888   // Great we found a shift right.
19889   MVT WideVT = VT;
19890   if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
19891     WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19892   SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
19893                             DAG.getUNDEF(WideVT), V1,
19894                             DAG.getIntPtrConstant(0, DL));
19895   Res = DAG.getNode(X86ISD::KSHIFTR, DL, WideVT, Res,
19896                     DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
19897   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19898                      DAG.getIntPtrConstant(0, DL));
19899 }
19900 
19901 // Determine if this shuffle can be implemented with a KSHIFT instruction.
19902 // Returns the shift amount if possible or -1 if not. This is a simplified
19903 // version of matchShuffleAsShift.
19904 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
19905                                     int MaskOffset, const APInt &Zeroable) {
19906   int Size = Mask.size();
19907 
19908   auto CheckZeros = [&](int Shift, bool Left) {
19909     for (int j = 0; j < Shift; ++j)
19910       if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
19911         return false;
19912 
19913     return true;
19914   };
19915 
19916   auto MatchShift = [&](int Shift, bool Left) {
19917     unsigned Pos = Left ? Shift : 0;
19918     unsigned Low = Left ? 0 : Shift;
19919     unsigned Len = Size - Shift;
19920     return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
19921   };
19922 
19923   for (int Shift = 1; Shift != Size; ++Shift)
19924     for (bool Left : {true, false})
19925       if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
19926         Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
19927         return Shift;
19928       }
19929 
19930   return -1;
19931 }
19932 
19933 
19934 // Lower vXi1 vector shuffles.
19935 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
19936 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
19937 // vector, shuffle and then truncate it back.
19938 static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
19939                                 MVT VT, SDValue V1, SDValue V2,
19940                                 const APInt &Zeroable,
19941                                 const X86Subtarget &Subtarget,
19942                                 SelectionDAG &DAG) {
19943   assert(Subtarget.hasAVX512() &&
19944          "Cannot lower 512-bit vectors w/o basic ISA!");
19945 
19946   int NumElts = Mask.size();
19947 
19948   // Try to recognize shuffles that are just padding a subvector with zeros.
19949   int SubvecElts = 0;
19950   int Src = -1;
19951   for (int i = 0; i != NumElts; ++i) {
19952     if (Mask[i] >= 0) {
19953       // Grab the source from the first valid mask. All subsequent elements need
19954       // to use this same source.
19955       if (Src < 0)
19956         Src = Mask[i] / NumElts;
19957       if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
19958         break;
19959     }
19960 
19961     ++SubvecElts;
19962   }
19963   assert(SubvecElts != NumElts && "Identity shuffle?");
19964 
19965   // Clip to a power 2.
19966   SubvecElts = llvm::bit_floor<uint32_t>(SubvecElts);
19967 
19968   // Make sure the number of zeroable bits in the top at least covers the bits
19969   // not covered by the subvector.
19970   if ((int)Zeroable.countl_one() >= (NumElts - SubvecElts)) {
19971     assert(Src >= 0 && "Expected a source!");
19972     MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
19973     SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
19974                                   Src == 0 ? V1 : V2,
19975                                   DAG.getIntPtrConstant(0, DL));
19976     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
19977                        DAG.getConstant(0, DL, VT),
19978                        Extract, DAG.getIntPtrConstant(0, DL));
19979   }
19980 
19981   // Try a simple shift right with undef elements. Later we'll try with zeros.
19982   if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
19983                                                 DAG))
19984     return Shift;
19985 
19986   // Try to match KSHIFTs.
19987   unsigned Offset = 0;
19988   for (SDValue V : { V1, V2 }) {
19989     unsigned Opcode;
19990     int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
19991     if (ShiftAmt >= 0) {
19992       MVT WideVT = VT;
19993       if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
19994         WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19995       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
19996                                 DAG.getUNDEF(WideVT), V,
19997                                 DAG.getIntPtrConstant(0, DL));
19998       // Widened right shifts need two shifts to ensure we shift in zeroes.
19999       if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
20000         int WideElts = WideVT.getVectorNumElements();
20001         // Shift left to put the original vector in the MSBs of the new size.
20002         Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
20003                           DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
20004         // Increase the shift amount to account for the left shift.
20005         ShiftAmt += WideElts - NumElts;
20006       }
20007 
20008       Res = DAG.getNode(Opcode, DL, WideVT, Res,
20009                         DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
20010       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20011                          DAG.getIntPtrConstant(0, DL));
20012     }
20013     Offset += NumElts; // Increment for next iteration.
20014   }
20015 
20016   // If we're broadcasting a SETCC result, try to broadcast the ops instead.
20017   // TODO: What other unary shuffles would benefit from this?
20018   if (isBroadcastShuffleMask(Mask) && V1.getOpcode() == ISD::SETCC &&
20019       V1->hasOneUse()) {
20020     SDValue Op0 = V1.getOperand(0);
20021     SDValue Op1 = V1.getOperand(1);
20022     ISD::CondCode CC = cast<CondCodeSDNode>(V1.getOperand(2))->get();
20023     EVT OpVT = Op0.getValueType();
20024     return DAG.getSetCC(
20025         DL, VT, DAG.getVectorShuffle(OpVT, DL, Op0, DAG.getUNDEF(OpVT), Mask),
20026         DAG.getVectorShuffle(OpVT, DL, Op1, DAG.getUNDEF(OpVT), Mask), CC);
20027   }
20028 
20029   MVT ExtVT;
20030   switch (VT.SimpleTy) {
20031   default:
20032     llvm_unreachable("Expected a vector of i1 elements");
20033   case MVT::v2i1:
20034     ExtVT = MVT::v2i64;
20035     break;
20036   case MVT::v4i1:
20037     ExtVT = MVT::v4i32;
20038     break;
20039   case MVT::v8i1:
20040     // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
20041     // shuffle.
20042     ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
20043     break;
20044   case MVT::v16i1:
20045     // Take 512-bit type, unless we are avoiding 512-bit types and have the
20046     // 256-bit operation available.
20047     ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
20048     break;
20049   case MVT::v32i1:
20050     // Take 512-bit type, unless we are avoiding 512-bit types and have the
20051     // 256-bit operation available.
20052     assert(Subtarget.hasBWI() && "Expected AVX512BW support");
20053     ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
20054     break;
20055   case MVT::v64i1:
20056     // Fall back to scalarization. FIXME: We can do better if the shuffle
20057     // can be partitioned cleanly.
20058     if (!Subtarget.useBWIRegs())
20059       return SDValue();
20060     ExtVT = MVT::v64i8;
20061     break;
20062   }
20063 
20064   V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
20065   V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
20066 
20067   SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
20068   // i1 was sign extended we can use X86ISD::CVT2MASK.
20069   int NumElems = VT.getVectorNumElements();
20070   if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
20071       (Subtarget.hasDQI() && (NumElems < 32)))
20072     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
20073                        Shuffle, ISD::SETGT);
20074 
20075   return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
20076 }
20077 
20078 /// Helper function that returns true if the shuffle mask should be
20079 /// commuted to improve canonicalization.
20080 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
20081   int NumElements = Mask.size();
20082 
20083   int NumV1Elements = 0, NumV2Elements = 0;
20084   for (int M : Mask)
20085     if (M < 0)
20086       continue;
20087     else if (M < NumElements)
20088       ++NumV1Elements;
20089     else
20090       ++NumV2Elements;
20091 
20092   // Commute the shuffle as needed such that more elements come from V1 than
20093   // V2. This allows us to match the shuffle pattern strictly on how many
20094   // elements come from V1 without handling the symmetric cases.
20095   if (NumV2Elements > NumV1Elements)
20096     return true;
20097 
20098   assert(NumV1Elements > 0 && "No V1 indices");
20099 
20100   if (NumV2Elements == 0)
20101     return false;
20102 
20103   // When the number of V1 and V2 elements are the same, try to minimize the
20104   // number of uses of V2 in the low half of the vector. When that is tied,
20105   // ensure that the sum of indices for V1 is equal to or lower than the sum
20106   // indices for V2. When those are equal, try to ensure that the number of odd
20107   // indices for V1 is lower than the number of odd indices for V2.
20108   if (NumV1Elements == NumV2Elements) {
20109     int LowV1Elements = 0, LowV2Elements = 0;
20110     for (int M : Mask.slice(0, NumElements / 2))
20111       if (M >= NumElements)
20112         ++LowV2Elements;
20113       else if (M >= 0)
20114         ++LowV1Elements;
20115     if (LowV2Elements > LowV1Elements)
20116       return true;
20117     if (LowV2Elements == LowV1Elements) {
20118       int SumV1Indices = 0, SumV2Indices = 0;
20119       for (int i = 0, Size = Mask.size(); i < Size; ++i)
20120         if (Mask[i] >= NumElements)
20121           SumV2Indices += i;
20122         else if (Mask[i] >= 0)
20123           SumV1Indices += i;
20124       if (SumV2Indices < SumV1Indices)
20125         return true;
20126       if (SumV2Indices == SumV1Indices) {
20127         int NumV1OddIndices = 0, NumV2OddIndices = 0;
20128         for (int i = 0, Size = Mask.size(); i < Size; ++i)
20129           if (Mask[i] >= NumElements)
20130             NumV2OddIndices += i % 2;
20131           else if (Mask[i] >= 0)
20132             NumV1OddIndices += i % 2;
20133         if (NumV2OddIndices < NumV1OddIndices)
20134           return true;
20135       }
20136     }
20137   }
20138 
20139   return false;
20140 }
20141 
20142 static bool canCombineAsMaskOperation(SDValue V,
20143                                       const X86Subtarget &Subtarget) {
20144   if (!Subtarget.hasAVX512())
20145     return false;
20146 
20147   if (!V.getValueType().isSimple())
20148     return false;
20149 
20150   MVT VT = V.getSimpleValueType().getScalarType();
20151   if ((VT == MVT::i16 || VT == MVT::i8) && !Subtarget.hasBWI())
20152     return false;
20153 
20154   // If vec width < 512, widen i8/i16 even with BWI as blendd/blendps/blendpd
20155   // are preferable to blendw/blendvb/masked-mov.
20156   if ((VT == MVT::i16 || VT == MVT::i8) &&
20157       V.getSimpleValueType().getSizeInBits() < 512)
20158     return false;
20159 
20160   auto HasMaskOperation = [&](SDValue V) {
20161     // TODO: Currently we only check limited opcode. We probably extend
20162     // it to all binary operation by checking TLI.isBinOp().
20163     switch (V->getOpcode()) {
20164     default:
20165       return false;
20166     case ISD::ADD:
20167     case ISD::SUB:
20168     case ISD::AND:
20169     case ISD::XOR:
20170     case ISD::OR:
20171     case ISD::SMAX:
20172     case ISD::SMIN:
20173     case ISD::UMAX:
20174     case ISD::UMIN:
20175     case ISD::ABS:
20176     case ISD::SHL:
20177     case ISD::SRL:
20178     case ISD::SRA:
20179     case ISD::MUL:
20180       break;
20181     }
20182     if (!V->hasOneUse())
20183       return false;
20184 
20185     return true;
20186   };
20187 
20188   if (HasMaskOperation(V))
20189     return true;
20190 
20191   return false;
20192 }
20193 
20194 // Forward declaration.
20195 static SDValue canonicalizeShuffleMaskWithHorizOp(
20196     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
20197     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
20198     const X86Subtarget &Subtarget);
20199 
20200     /// Top-level lowering for x86 vector shuffles.
20201 ///
20202 /// This handles decomposition, canonicalization, and lowering of all x86
20203 /// vector shuffles. Most of the specific lowering strategies are encapsulated
20204 /// above in helper routines. The canonicalization attempts to widen shuffles
20205 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
20206 /// s.t. only one of the two inputs needs to be tested, etc.
20207 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
20208                                    SelectionDAG &DAG) {
20209   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
20210   ArrayRef<int> OrigMask = SVOp->getMask();
20211   SDValue V1 = Op.getOperand(0);
20212   SDValue V2 = Op.getOperand(1);
20213   MVT VT = Op.getSimpleValueType();
20214   int NumElements = VT.getVectorNumElements();
20215   SDLoc DL(Op);
20216   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
20217 
20218   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
20219          "Can't lower MMX shuffles");
20220 
20221   bool V1IsUndef = V1.isUndef();
20222   bool V2IsUndef = V2.isUndef();
20223   if (V1IsUndef && V2IsUndef)
20224     return DAG.getUNDEF(VT);
20225 
20226   // When we create a shuffle node we put the UNDEF node to second operand,
20227   // but in some cases the first operand may be transformed to UNDEF.
20228   // In this case we should just commute the node.
20229   if (V1IsUndef)
20230     return DAG.getCommutedVectorShuffle(*SVOp);
20231 
20232   // Check for non-undef masks pointing at an undef vector and make the masks
20233   // undef as well. This makes it easier to match the shuffle based solely on
20234   // the mask.
20235   if (V2IsUndef &&
20236       any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
20237     SmallVector<int, 8> NewMask(OrigMask);
20238     for (int &M : NewMask)
20239       if (M >= NumElements)
20240         M = -1;
20241     return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
20242   }
20243 
20244   // Check for illegal shuffle mask element index values.
20245   int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
20246   (void)MaskUpperLimit;
20247   assert(llvm::all_of(OrigMask,
20248                       [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
20249          "Out of bounds shuffle index");
20250 
20251   // We actually see shuffles that are entirely re-arrangements of a set of
20252   // zero inputs. This mostly happens while decomposing complex shuffles into
20253   // simple ones. Directly lower these as a buildvector of zeros.
20254   APInt KnownUndef, KnownZero;
20255   computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
20256 
20257   APInt Zeroable = KnownUndef | KnownZero;
20258   if (Zeroable.isAllOnes())
20259     return getZeroVector(VT, Subtarget, DAG, DL);
20260 
20261   bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
20262 
20263   // Try to collapse shuffles into using a vector type with fewer elements but
20264   // wider element types. We cap this to not form integers or floating point
20265   // elements wider than 64 bits. It does not seem beneficial to form i128
20266   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
20267   SmallVector<int, 16> WidenedMask;
20268   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
20269       !canCombineAsMaskOperation(V1, Subtarget) &&
20270       !canCombineAsMaskOperation(V2, Subtarget) &&
20271       canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
20272     // Shuffle mask widening should not interfere with a broadcast opportunity
20273     // by obfuscating the operands with bitcasts.
20274     // TODO: Avoid lowering directly from this top-level function: make this
20275     // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
20276     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
20277                                                     Subtarget, DAG))
20278       return Broadcast;
20279 
20280     MVT NewEltVT = VT.isFloatingPoint()
20281                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
20282                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
20283     int NewNumElts = NumElements / 2;
20284     MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
20285     // Make sure that the new vector type is legal. For example, v2f64 isn't
20286     // legal on SSE1.
20287     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
20288       if (V2IsZero) {
20289         // Modify the new Mask to take all zeros from the all-zero vector.
20290         // Choose indices that are blend-friendly.
20291         bool UsedZeroVector = false;
20292         assert(is_contained(WidenedMask, SM_SentinelZero) &&
20293                "V2's non-undef elements are used?!");
20294         for (int i = 0; i != NewNumElts; ++i)
20295           if (WidenedMask[i] == SM_SentinelZero) {
20296             WidenedMask[i] = i + NewNumElts;
20297             UsedZeroVector = true;
20298           }
20299         // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
20300         // some elements to be undef.
20301         if (UsedZeroVector)
20302           V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
20303       }
20304       V1 = DAG.getBitcast(NewVT, V1);
20305       V2 = DAG.getBitcast(NewVT, V2);
20306       return DAG.getBitcast(
20307           VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
20308     }
20309   }
20310 
20311   SmallVector<SDValue> Ops = {V1, V2};
20312   SmallVector<int> Mask(OrigMask);
20313 
20314   // Canonicalize the shuffle with any horizontal ops inputs.
20315   // NOTE: This may update Ops and Mask.
20316   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
20317           Ops, Mask, VT.getSizeInBits(), DL, DAG, Subtarget))
20318     return DAG.getBitcast(VT, HOp);
20319 
20320   V1 = DAG.getBitcast(VT, Ops[0]);
20321   V2 = DAG.getBitcast(VT, Ops[1]);
20322   assert(NumElements == (int)Mask.size() &&
20323          "canonicalizeShuffleMaskWithHorizOp "
20324          "shouldn't alter the shuffle mask size");
20325 
20326   // Commute the shuffle if it will improve canonicalization.
20327   if (canonicalizeShuffleMaskWithCommute(Mask)) {
20328     ShuffleVectorSDNode::commuteMask(Mask);
20329     std::swap(V1, V2);
20330   }
20331 
20332   // For each vector width, delegate to a specialized lowering routine.
20333   if (VT.is128BitVector())
20334     return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
20335 
20336   if (VT.is256BitVector())
20337     return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
20338 
20339   if (VT.is512BitVector())
20340     return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
20341 
20342   if (Is1BitVector)
20343     return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
20344 
20345   llvm_unreachable("Unimplemented!");
20346 }
20347 
20348 /// Try to lower a VSELECT instruction to a vector shuffle.
20349 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
20350                                            const X86Subtarget &Subtarget,
20351                                            SelectionDAG &DAG) {
20352   SDValue Cond = Op.getOperand(0);
20353   SDValue LHS = Op.getOperand(1);
20354   SDValue RHS = Op.getOperand(2);
20355   MVT VT = Op.getSimpleValueType();
20356 
20357   // Only non-legal VSELECTs reach this lowering, convert those into generic
20358   // shuffles and re-use the shuffle lowering path for blends.
20359   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
20360     SmallVector<int, 32> Mask;
20361     if (createShuffleMaskFromVSELECT(Mask, Cond))
20362       return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
20363   }
20364 
20365   return SDValue();
20366 }
20367 
20368 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
20369   SDValue Cond = Op.getOperand(0);
20370   SDValue LHS = Op.getOperand(1);
20371   SDValue RHS = Op.getOperand(2);
20372 
20373   SDLoc dl(Op);
20374   MVT VT = Op.getSimpleValueType();
20375   if (isSoftF16(VT, Subtarget)) {
20376     MVT NVT = VT.changeVectorElementTypeToInteger();
20377     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, dl, NVT, Cond,
20378                                           DAG.getBitcast(NVT, LHS),
20379                                           DAG.getBitcast(NVT, RHS)));
20380   }
20381 
20382   // A vselect where all conditions and data are constants can be optimized into
20383   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20384   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
20385       ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20386       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20387     return SDValue();
20388 
20389   // Try to lower this to a blend-style vector shuffle. This can handle all
20390   // constant condition cases.
20391   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
20392     return BlendOp;
20393 
20394   // If this VSELECT has a vector if i1 as a mask, it will be directly matched
20395   // with patterns on the mask registers on AVX-512.
20396   MVT CondVT = Cond.getSimpleValueType();
20397   unsigned CondEltSize = Cond.getScalarValueSizeInBits();
20398   if (CondEltSize == 1)
20399     return Op;
20400 
20401   // Variable blends are only legal from SSE4.1 onward.
20402   if (!Subtarget.hasSSE41())
20403     return SDValue();
20404 
20405   unsigned EltSize = VT.getScalarSizeInBits();
20406   unsigned NumElts = VT.getVectorNumElements();
20407 
20408   // Expand v32i16/v64i8 without BWI.
20409   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
20410     return SDValue();
20411 
20412   // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
20413   // into an i1 condition so that we can use the mask-based 512-bit blend
20414   // instructions.
20415   if (VT.getSizeInBits() == 512) {
20416     // Build a mask by testing the condition against zero.
20417     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20418     SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
20419                                 DAG.getConstant(0, dl, CondVT),
20420                                 ISD::SETNE);
20421     // Now return a new VSELECT using the mask.
20422     return DAG.getSelect(dl, VT, Mask, LHS, RHS);
20423   }
20424 
20425   // SEXT/TRUNC cases where the mask doesn't match the destination size.
20426   if (CondEltSize != EltSize) {
20427     // If we don't have a sign splat, rely on the expansion.
20428     if (CondEltSize != DAG.ComputeNumSignBits(Cond))
20429       return SDValue();
20430 
20431     MVT NewCondSVT = MVT::getIntegerVT(EltSize);
20432     MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
20433     Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
20434     return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
20435   }
20436 
20437   // Only some types will be legal on some subtargets. If we can emit a legal
20438   // VSELECT-matching blend, return Op, and but if we need to expand, return
20439   // a null value.
20440   switch (VT.SimpleTy) {
20441   default:
20442     // Most of the vector types have blends past SSE4.1.
20443     return Op;
20444 
20445   case MVT::v32i8:
20446     // The byte blends for AVX vectors were introduced only in AVX2.
20447     if (Subtarget.hasAVX2())
20448       return Op;
20449 
20450     return SDValue();
20451 
20452   case MVT::v8i16:
20453   case MVT::v16i16: {
20454     // Bitcast everything to the vXi8 type and use a vXi8 vselect.
20455     MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
20456     Cond = DAG.getBitcast(CastVT, Cond);
20457     LHS = DAG.getBitcast(CastVT, LHS);
20458     RHS = DAG.getBitcast(CastVT, RHS);
20459     SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
20460     return DAG.getBitcast(VT, Select);
20461   }
20462   }
20463 }
20464 
20465 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
20466   MVT VT = Op.getSimpleValueType();
20467   SDValue Vec = Op.getOperand(0);
20468   SDValue Idx = Op.getOperand(1);
20469   assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
20470   SDLoc dl(Op);
20471 
20472   if (!Vec.getSimpleValueType().is128BitVector())
20473     return SDValue();
20474 
20475   if (VT.getSizeInBits() == 8) {
20476     // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
20477     // we're going to zero extend the register or fold the store.
20478     if (llvm::isNullConstant(Idx) && !X86::mayFoldIntoZeroExtend(Op) &&
20479         !X86::mayFoldIntoStore(Op))
20480       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
20481                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
20482                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
20483 
20484     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20485     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
20486                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
20487     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
20488   }
20489 
20490   if (VT == MVT::f32) {
20491     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
20492     // the result back to FR32 register. It's only worth matching if the
20493     // result has a single use which is a store or a bitcast to i32.  And in
20494     // the case of a store, it's not worth it if the index is a constant 0,
20495     // because a MOVSSmr can be used instead, which is smaller and faster.
20496     if (!Op.hasOneUse())
20497       return SDValue();
20498     SDNode *User = *Op.getNode()->use_begin();
20499     if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
20500         (User->getOpcode() != ISD::BITCAST ||
20501          User->getValueType(0) != MVT::i32))
20502       return SDValue();
20503     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
20504                                   DAG.getBitcast(MVT::v4i32, Vec), Idx);
20505     return DAG.getBitcast(MVT::f32, Extract);
20506   }
20507 
20508   if (VT == MVT::i32 || VT == MVT::i64)
20509       return Op;
20510 
20511   return SDValue();
20512 }
20513 
20514 /// Extract one bit from mask vector, like v16i1 or v8i1.
20515 /// AVX-512 feature.
20516 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
20517                                         const X86Subtarget &Subtarget) {
20518   SDValue Vec = Op.getOperand(0);
20519   SDLoc dl(Vec);
20520   MVT VecVT = Vec.getSimpleValueType();
20521   SDValue Idx = Op.getOperand(1);
20522   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
20523   MVT EltVT = Op.getSimpleValueType();
20524 
20525   assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
20526          "Unexpected vector type in ExtractBitFromMaskVector");
20527 
20528   // variable index can't be handled in mask registers,
20529   // extend vector to VR512/128
20530   if (!IdxC) {
20531     unsigned NumElts = VecVT.getVectorNumElements();
20532     // Extending v8i1/v16i1 to 512-bit get better performance on KNL
20533     // than extending to 128/256bit.
20534     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
20535     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
20536     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
20537     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
20538     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
20539   }
20540 
20541   unsigned IdxVal = IdxC->getZExtValue();
20542   if (IdxVal == 0) // the operation is legal
20543     return Op;
20544 
20545   // Extend to natively supported kshift.
20546   unsigned NumElems = VecVT.getVectorNumElements();
20547   MVT WideVecVT = VecVT;
20548   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
20549     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
20550     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
20551                       DAG.getUNDEF(WideVecVT), Vec,
20552                       DAG.getIntPtrConstant(0, dl));
20553   }
20554 
20555   // Use kshiftr instruction to move to the lower element.
20556   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
20557                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
20558 
20559   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
20560                      DAG.getIntPtrConstant(0, dl));
20561 }
20562 
20563 SDValue
20564 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
20565                                            SelectionDAG &DAG) const {
20566   SDLoc dl(Op);
20567   SDValue Vec = Op.getOperand(0);
20568   MVT VecVT = Vec.getSimpleValueType();
20569   SDValue Idx = Op.getOperand(1);
20570   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
20571 
20572   if (VecVT.getVectorElementType() == MVT::i1)
20573     return ExtractBitFromMaskVector(Op, DAG, Subtarget);
20574 
20575   if (!IdxC) {
20576     // Its more profitable to go through memory (1 cycles throughput)
20577     // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
20578     // IACA tool was used to get performance estimation
20579     // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
20580     //
20581     // example : extractelement <16 x i8> %a, i32 %i
20582     //
20583     // Block Throughput: 3.00 Cycles
20584     // Throughput Bottleneck: Port5
20585     //
20586     // | Num Of |   Ports pressure in cycles  |    |
20587     // |  Uops  |  0  - DV  |  5  |  6  |  7  |    |
20588     // ---------------------------------------------
20589     // |   1    |           | 1.0 |     |     | CP | vmovd xmm1, edi
20590     // |   1    |           | 1.0 |     |     | CP | vpshufb xmm0, xmm0, xmm1
20591     // |   2    | 1.0       | 1.0 |     |     | CP | vpextrb eax, xmm0, 0x0
20592     // Total Num Of Uops: 4
20593     //
20594     //
20595     // Block Throughput: 1.00 Cycles
20596     // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
20597     //
20598     // |    |  Ports pressure in cycles   |  |
20599     // |Uops| 1 | 2 - D  |3 -  D  | 4 | 5 |  |
20600     // ---------------------------------------------------------
20601     // |2^  |   | 0.5    | 0.5    |1.0|   |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
20602     // |1   |0.5|        |        |   |0.5|  | lea rax, ptr [rsp-0x18]
20603     // |1   |   |0.5, 0.5|0.5, 0.5|   |   |CP| mov al, byte ptr [rdi+rax*1]
20604     // Total Num Of Uops: 4
20605 
20606     return SDValue();
20607   }
20608 
20609   unsigned IdxVal = IdxC->getZExtValue();
20610 
20611   // If this is a 256-bit vector result, first extract the 128-bit vector and
20612   // then extract the element from the 128-bit vector.
20613   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
20614     // Get the 128-bit vector.
20615     Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
20616     MVT EltVT = VecVT.getVectorElementType();
20617 
20618     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
20619     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
20620 
20621     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
20622     // this can be done with a mask.
20623     IdxVal &= ElemsPerChunk - 1;
20624     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
20625                        DAG.getIntPtrConstant(IdxVal, dl));
20626   }
20627 
20628   assert(VecVT.is128BitVector() && "Unexpected vector length");
20629 
20630   MVT VT = Op.getSimpleValueType();
20631 
20632   if (VT == MVT::i16) {
20633     // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
20634     // we're going to zero extend the register or fold the store (SSE41 only).
20635     if (IdxVal == 0 && !X86::mayFoldIntoZeroExtend(Op) &&
20636         !(Subtarget.hasSSE41() && X86::mayFoldIntoStore(Op))) {
20637       if (Subtarget.hasFP16())
20638         return Op;
20639 
20640       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
20641                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
20642                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
20643     }
20644 
20645     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
20646                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
20647     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
20648   }
20649 
20650   if (Subtarget.hasSSE41())
20651     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
20652       return Res;
20653 
20654   // TODO: We only extract a single element from v16i8, we can probably afford
20655   // to be more aggressive here before using the default approach of spilling to
20656   // stack.
20657   if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
20658     // Extract either the lowest i32 or any i16, and extract the sub-byte.
20659     int DWordIdx = IdxVal / 4;
20660     if (DWordIdx == 0) {
20661       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
20662                                 DAG.getBitcast(MVT::v4i32, Vec),
20663                                 DAG.getIntPtrConstant(DWordIdx, dl));
20664       int ShiftVal = (IdxVal % 4) * 8;
20665       if (ShiftVal != 0)
20666         Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
20667                           DAG.getConstant(ShiftVal, dl, MVT::i8));
20668       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20669     }
20670 
20671     int WordIdx = IdxVal / 2;
20672     SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
20673                               DAG.getBitcast(MVT::v8i16, Vec),
20674                               DAG.getIntPtrConstant(WordIdx, dl));
20675     int ShiftVal = (IdxVal % 2) * 8;
20676     if (ShiftVal != 0)
20677       Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
20678                         DAG.getConstant(ShiftVal, dl, MVT::i8));
20679     return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20680   }
20681 
20682   if (VT == MVT::f16 || VT.getSizeInBits() == 32) {
20683     if (IdxVal == 0)
20684       return Op;
20685 
20686     // Shuffle the element to the lowest element, then movss or movsh.
20687     SmallVector<int, 8> Mask(VecVT.getVectorNumElements(), -1);
20688     Mask[0] = static_cast<int>(IdxVal);
20689     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
20690     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
20691                        DAG.getIntPtrConstant(0, dl));
20692   }
20693 
20694   if (VT.getSizeInBits() == 64) {
20695     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
20696     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
20697     //        to match extract_elt for f64.
20698     if (IdxVal == 0)
20699       return Op;
20700 
20701     // UNPCKHPD the element to the lowest double word, then movsd.
20702     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
20703     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
20704     int Mask[2] = { 1, -1 };
20705     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
20706     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
20707                        DAG.getIntPtrConstant(0, dl));
20708   }
20709 
20710   return SDValue();
20711 }
20712 
20713 /// Insert one bit to mask vector, like v16i1 or v8i1.
20714 /// AVX-512 feature.
20715 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
20716                                      const X86Subtarget &Subtarget) {
20717   SDLoc dl(Op);
20718   SDValue Vec = Op.getOperand(0);
20719   SDValue Elt = Op.getOperand(1);
20720   SDValue Idx = Op.getOperand(2);
20721   MVT VecVT = Vec.getSimpleValueType();
20722 
20723   if (!isa<ConstantSDNode>(Idx)) {
20724     // Non constant index. Extend source and destination,
20725     // insert element and then truncate the result.
20726     unsigned NumElts = VecVT.getVectorNumElements();
20727     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
20728     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
20729     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
20730       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
20731       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
20732     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
20733   }
20734 
20735   // Copy into a k-register, extract to v1i1 and insert_subvector.
20736   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
20737   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
20738 }
20739 
20740 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
20741                                                   SelectionDAG &DAG) const {
20742   MVT VT = Op.getSimpleValueType();
20743   MVT EltVT = VT.getVectorElementType();
20744   unsigned NumElts = VT.getVectorNumElements();
20745   unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
20746 
20747   if (EltVT == MVT::i1)
20748     return InsertBitToMaskVector(Op, DAG, Subtarget);
20749 
20750   SDLoc dl(Op);
20751   SDValue N0 = Op.getOperand(0);
20752   SDValue N1 = Op.getOperand(1);
20753   SDValue N2 = Op.getOperand(2);
20754   auto *N2C = dyn_cast<ConstantSDNode>(N2);
20755 
20756   if (EltVT == MVT::bf16) {
20757     MVT IVT = VT.changeVectorElementTypeToInteger();
20758     SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVT,
20759                               DAG.getBitcast(IVT, N0),
20760                               DAG.getBitcast(MVT::i16, N1), N2);
20761     return DAG.getBitcast(VT, Res);
20762   }
20763 
20764   if (!N2C) {
20765     // Variable insertion indices, usually we're better off spilling to stack,
20766     // but AVX512 can use a variable compare+select by comparing against all
20767     // possible vector indices, and FP insertion has less gpr->simd traffic.
20768     if (!(Subtarget.hasBWI() ||
20769           (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
20770           (Subtarget.hasSSE41() && (EltVT == MVT::f32 || EltVT == MVT::f64))))
20771       return SDValue();
20772 
20773     MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
20774     MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
20775     if (!isTypeLegal(IdxSVT) || !isTypeLegal(IdxVT))
20776       return SDValue();
20777 
20778     SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
20779     SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
20780     SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
20781 
20782     SmallVector<SDValue, 16> RawIndices;
20783     for (unsigned I = 0; I != NumElts; ++I)
20784       RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
20785     SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
20786 
20787     // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
20788     return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
20789                            ISD::CondCode::SETEQ);
20790   }
20791 
20792   if (N2C->getAPIntValue().uge(NumElts))
20793     return SDValue();
20794   uint64_t IdxVal = N2C->getZExtValue();
20795 
20796   bool IsZeroElt = X86::isZeroNode(N1);
20797   bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
20798 
20799   if (IsZeroElt || IsAllOnesElt) {
20800     // Lower insertion of v16i8/v32i8/v64i16 -1 elts as an 'OR' blend.
20801     // We don't deal with i8 0 since it appears to be handled elsewhere.
20802     if (IsAllOnesElt &&
20803         ((VT == MVT::v16i8 && !Subtarget.hasSSE41()) ||
20804          ((VT == MVT::v32i8 || VT == MVT::v16i16) && !Subtarget.hasInt256()))) {
20805       SDValue ZeroCst = DAG.getConstant(0, dl, VT.getScalarType());
20806       SDValue OnesCst = DAG.getAllOnesConstant(dl, VT.getScalarType());
20807       SmallVector<SDValue, 8> CstVectorElts(NumElts, ZeroCst);
20808       CstVectorElts[IdxVal] = OnesCst;
20809       SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
20810       return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
20811     }
20812     // See if we can do this more efficiently with a blend shuffle with a
20813     // rematerializable vector.
20814     if (Subtarget.hasSSE41() &&
20815         (EltSizeInBits >= 16 || (IsZeroElt && !VT.is128BitVector()))) {
20816       SmallVector<int, 8> BlendMask;
20817       for (unsigned i = 0; i != NumElts; ++i)
20818         BlendMask.push_back(i == IdxVal ? i + NumElts : i);
20819       SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
20820                                     : getOnesVector(VT, DAG, dl);
20821       return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
20822     }
20823   }
20824 
20825   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
20826   // into that, and then insert the subvector back into the result.
20827   if (VT.is256BitVector() || VT.is512BitVector()) {
20828     // With a 256-bit vector, we can insert into the zero element efficiently
20829     // using a blend if we have AVX or AVX2 and the right data type.
20830     if (VT.is256BitVector() && IdxVal == 0) {
20831       // TODO: It is worthwhile to cast integer to floating point and back
20832       // and incur a domain crossing penalty if that's what we'll end up
20833       // doing anyway after extracting to a 128-bit vector.
20834       if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
20835           (Subtarget.hasAVX2() && (EltVT == MVT::i32 || EltVT == MVT::i64))) {
20836         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
20837         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
20838                            DAG.getTargetConstant(1, dl, MVT::i8));
20839       }
20840     }
20841 
20842     unsigned NumEltsIn128 = 128 / EltSizeInBits;
20843     assert(isPowerOf2_32(NumEltsIn128) &&
20844            "Vectors will always have power-of-two number of elements.");
20845 
20846     // If we are not inserting into the low 128-bit vector chunk,
20847     // then prefer the broadcast+blend sequence.
20848     // FIXME: relax the profitability check iff all N1 uses are insertions.
20849     if (IdxVal >= NumEltsIn128 &&
20850         ((Subtarget.hasAVX2() && EltSizeInBits != 8) ||
20851          (Subtarget.hasAVX() && (EltSizeInBits >= 32) &&
20852           X86::mayFoldLoad(N1, Subtarget)))) {
20853       SDValue N1SplatVec = DAG.getSplatBuildVector(VT, dl, N1);
20854       SmallVector<int, 8> BlendMask;
20855       for (unsigned i = 0; i != NumElts; ++i)
20856         BlendMask.push_back(i == IdxVal ? i + NumElts : i);
20857       return DAG.getVectorShuffle(VT, dl, N0, N1SplatVec, BlendMask);
20858     }
20859 
20860     // Get the desired 128-bit vector chunk.
20861     SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
20862 
20863     // Insert the element into the desired chunk.
20864     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
20865     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
20866 
20867     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
20868                     DAG.getIntPtrConstant(IdxIn128, dl));
20869 
20870     // Insert the changed part back into the bigger vector
20871     return insert128BitVector(N0, V, IdxVal, DAG, dl);
20872   }
20873   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
20874 
20875   // This will be just movw/movd/movq/movsh/movss/movsd.
20876   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
20877     if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
20878         EltVT == MVT::f16 || EltVT == MVT::i64) {
20879       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
20880       return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
20881     }
20882 
20883     // We can't directly insert an i8 or i16 into a vector, so zero extend
20884     // it to i32 first.
20885     if (EltVT == MVT::i16 || EltVT == MVT::i8) {
20886       N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
20887       MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
20888       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
20889       N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
20890       return DAG.getBitcast(VT, N1);
20891     }
20892   }
20893 
20894   // Transform it so it match pinsr{b,w} which expects a GR32 as its second
20895   // argument. SSE41 required for pinsrb.
20896   if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
20897     unsigned Opc;
20898     if (VT == MVT::v8i16) {
20899       assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
20900       Opc = X86ISD::PINSRW;
20901     } else {
20902       assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
20903       assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
20904       Opc = X86ISD::PINSRB;
20905     }
20906 
20907     assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
20908     N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
20909     N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
20910     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
20911   }
20912 
20913   if (Subtarget.hasSSE41()) {
20914     if (EltVT == MVT::f32) {
20915       // Bits [7:6] of the constant are the source select. This will always be
20916       //   zero here. The DAG Combiner may combine an extract_elt index into
20917       //   these bits. For example (insert (extract, 3), 2) could be matched by
20918       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
20919       // Bits [5:4] of the constant are the destination select. This is the
20920       //   value of the incoming immediate.
20921       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
20922       //   combine either bitwise AND or insert of float 0.0 to set these bits.
20923 
20924       bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
20925       if (IdxVal == 0 && (!MinSize || !X86::mayFoldLoad(N1, Subtarget))) {
20926         // If this is an insertion of 32-bits into the low 32-bits of
20927         // a vector, we prefer to generate a blend with immediate rather
20928         // than an insertps. Blends are simpler operations in hardware and so
20929         // will always have equal or better performance than insertps.
20930         // But if optimizing for size and there's a load folding opportunity,
20931         // generate insertps because blendps does not have a 32-bit memory
20932         // operand form.
20933         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
20934         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
20935                            DAG.getTargetConstant(1, dl, MVT::i8));
20936       }
20937       // Create this as a scalar to vector..
20938       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
20939       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
20940                          DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
20941     }
20942 
20943     // PINSR* works with constant index.
20944     if (EltVT == MVT::i32 || EltVT == MVT::i64)
20945       return Op;
20946   }
20947 
20948   return SDValue();
20949 }
20950 
20951 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
20952                                      SelectionDAG &DAG) {
20953   SDLoc dl(Op);
20954   MVT OpVT = Op.getSimpleValueType();
20955 
20956   // It's always cheaper to replace a xor+movd with xorps and simplifies further
20957   // combines.
20958   if (X86::isZeroNode(Op.getOperand(0)))
20959     return getZeroVector(OpVT, Subtarget, DAG, dl);
20960 
20961   // If this is a 256-bit vector result, first insert into a 128-bit
20962   // vector and then insert into the 256-bit vector.
20963   if (!OpVT.is128BitVector()) {
20964     // Insert into a 128-bit vector.
20965     unsigned SizeFactor = OpVT.getSizeInBits() / 128;
20966     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
20967                                  OpVT.getVectorNumElements() / SizeFactor);
20968 
20969     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
20970 
20971     // Insert the 128-bit vector.
20972     return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
20973   }
20974   assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
20975          "Expected an SSE type!");
20976 
20977   // Pass through a v4i32 or V8i16 SCALAR_TO_VECTOR as that's what we use in
20978   // tblgen.
20979   if (OpVT == MVT::v4i32 || (OpVT == MVT::v8i16 && Subtarget.hasFP16()))
20980     return Op;
20981 
20982   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
20983   return DAG.getBitcast(
20984       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
20985 }
20986 
20987 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
20988 // simple superregister reference or explicit instructions to insert
20989 // the upper bits of a vector.
20990 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
20991                                      SelectionDAG &DAG) {
20992   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
20993 
20994   return insert1BitVector(Op, DAG, Subtarget);
20995 }
20996 
20997 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
20998                                       SelectionDAG &DAG) {
20999   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
21000          "Only vXi1 extract_subvectors need custom lowering");
21001 
21002   SDLoc dl(Op);
21003   SDValue Vec = Op.getOperand(0);
21004   uint64_t IdxVal = Op.getConstantOperandVal(1);
21005 
21006   if (IdxVal == 0) // the operation is legal
21007     return Op;
21008 
21009   MVT VecVT = Vec.getSimpleValueType();
21010   unsigned NumElems = VecVT.getVectorNumElements();
21011 
21012   // Extend to natively supported kshift.
21013   MVT WideVecVT = VecVT;
21014   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
21015     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
21016     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
21017                       DAG.getUNDEF(WideVecVT), Vec,
21018                       DAG.getIntPtrConstant(0, dl));
21019   }
21020 
21021   // Shift to the LSB.
21022   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
21023                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
21024 
21025   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
21026                      DAG.getIntPtrConstant(0, dl));
21027 }
21028 
21029 // Returns the appropriate wrapper opcode for a global reference.
21030 unsigned X86TargetLowering::getGlobalWrapperKind(
21031     const GlobalValue *GV, const unsigned char OpFlags) const {
21032   // References to absolute symbols are never PC-relative.
21033   if (GV && GV->isAbsoluteSymbolRef())
21034     return X86ISD::Wrapper;
21035 
21036   CodeModel::Model M = getTargetMachine().getCodeModel();
21037   if (Subtarget.isPICStyleRIPRel() &&
21038       (M == CodeModel::Small || M == CodeModel::Kernel))
21039     return X86ISD::WrapperRIP;
21040 
21041   // In the medium model, functions can always be referenced RIP-relatively,
21042   // since they must be within 2GiB. This is also possible in non-PIC mode, and
21043   // shorter than the 64-bit absolute immediate that would otherwise be emitted.
21044   if (M == CodeModel::Medium && isa_and_nonnull<Function>(GV))
21045     return X86ISD::WrapperRIP;
21046 
21047   // GOTPCREL references must always use RIP.
21048   if (OpFlags == X86II::MO_GOTPCREL || OpFlags == X86II::MO_GOTPCREL_NORELAX)
21049     return X86ISD::WrapperRIP;
21050 
21051   return X86ISD::Wrapper;
21052 }
21053 
21054 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
21055 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
21056 // one of the above mentioned nodes. It has to be wrapped because otherwise
21057 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
21058 // be used to form addressing mode. These wrapped nodes will be selected
21059 // into MOV32ri.
21060 SDValue
21061 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
21062   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
21063 
21064   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
21065   // global base reg.
21066   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
21067 
21068   auto PtrVT = getPointerTy(DAG.getDataLayout());
21069   SDValue Result = DAG.getTargetConstantPool(
21070       CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
21071   SDLoc DL(CP);
21072   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
21073   // With PIC, the address is actually $g + Offset.
21074   if (OpFlag) {
21075     Result =
21076         DAG.getNode(ISD::ADD, DL, PtrVT,
21077                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
21078   }
21079 
21080   return Result;
21081 }
21082 
21083 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
21084   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
21085 
21086   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
21087   // global base reg.
21088   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
21089 
21090   auto PtrVT = getPointerTy(DAG.getDataLayout());
21091   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
21092   SDLoc DL(JT);
21093   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
21094 
21095   // With PIC, the address is actually $g + Offset.
21096   if (OpFlag)
21097     Result =
21098         DAG.getNode(ISD::ADD, DL, PtrVT,
21099                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
21100 
21101   return Result;
21102 }
21103 
21104 SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
21105                                                SelectionDAG &DAG) const {
21106   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
21107 }
21108 
21109 SDValue
21110 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
21111   // Create the TargetBlockAddressAddress node.
21112   unsigned char OpFlags =
21113     Subtarget.classifyBlockAddressReference();
21114   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
21115   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
21116   SDLoc dl(Op);
21117   auto PtrVT = getPointerTy(DAG.getDataLayout());
21118   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
21119   Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
21120 
21121   // With PIC, the address is actually $g + Offset.
21122   if (isGlobalRelativeToPICBase(OpFlags)) {
21123     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
21124                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
21125   }
21126 
21127   return Result;
21128 }
21129 
21130 /// Creates target global address or external symbol nodes for calls or
21131 /// other uses.
21132 SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
21133                                                  bool ForCall) const {
21134   // Unpack the global address or external symbol.
21135   const SDLoc &dl = SDLoc(Op);
21136   const GlobalValue *GV = nullptr;
21137   int64_t Offset = 0;
21138   const char *ExternalSym = nullptr;
21139   if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
21140     GV = G->getGlobal();
21141     Offset = G->getOffset();
21142   } else {
21143     const auto *ES = cast<ExternalSymbolSDNode>(Op);
21144     ExternalSym = ES->getSymbol();
21145   }
21146 
21147   // Calculate some flags for address lowering.
21148   const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
21149   unsigned char OpFlags;
21150   if (ForCall)
21151     OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
21152   else
21153     OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
21154   bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
21155   bool NeedsLoad = isGlobalStubReference(OpFlags);
21156 
21157   CodeModel::Model M = DAG.getTarget().getCodeModel();
21158   auto PtrVT = getPointerTy(DAG.getDataLayout());
21159   SDValue Result;
21160 
21161   if (GV) {
21162     // Create a target global address if this is a global. If possible, fold the
21163     // offset into the global address reference. Otherwise, ADD it on later.
21164     // Suppress the folding if Offset is negative: movl foo-1, %eax is not
21165     // allowed because if the address of foo is 0, the ELF R_X86_64_32
21166     // relocation will compute to a negative value, which is invalid.
21167     int64_t GlobalOffset = 0;
21168     if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
21169         X86::isOffsetSuitableForCodeModel(Offset, M, true)) {
21170       std::swap(GlobalOffset, Offset);
21171     }
21172     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
21173   } else {
21174     // If this is not a global address, this must be an external symbol.
21175     Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
21176   }
21177 
21178   // If this is a direct call, avoid the wrapper if we don't need to do any
21179   // loads or adds. This allows SDAG ISel to match direct calls.
21180   if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
21181     return Result;
21182 
21183   Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
21184 
21185   // With PIC, the address is actually $g + Offset.
21186   if (HasPICReg) {
21187     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
21188                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
21189   }
21190 
21191   // For globals that require a load from a stub to get the address, emit the
21192   // load.
21193   if (NeedsLoad)
21194     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
21195                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
21196 
21197   // If there was a non-zero offset that we didn't fold, create an explicit
21198   // addition for it.
21199   if (Offset != 0)
21200     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
21201                          DAG.getConstant(Offset, dl, PtrVT));
21202 
21203   return Result;
21204 }
21205 
21206 SDValue
21207 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
21208   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
21209 }
21210 
21211 static SDValue
21212 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
21213            SDValue *InGlue, const EVT PtrVT, unsigned ReturnReg,
21214            unsigned char OperandFlags, bool LocalDynamic = false) {
21215   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
21216   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
21217   SDLoc dl(GA);
21218   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
21219                                            GA->getValueType(0),
21220                                            GA->getOffset(),
21221                                            OperandFlags);
21222 
21223   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
21224                                            : X86ISD::TLSADDR;
21225 
21226   if (InGlue) {
21227     SDValue Ops[] = { Chain,  TGA, *InGlue };
21228     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
21229   } else {
21230     SDValue Ops[]  = { Chain, TGA };
21231     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
21232   }
21233 
21234   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
21235   MFI.setAdjustsStack(true);
21236   MFI.setHasCalls(true);
21237 
21238   SDValue Glue = Chain.getValue(1);
21239   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
21240 }
21241 
21242 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
21243 static SDValue
21244 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
21245                                 const EVT PtrVT) {
21246   SDValue InGlue;
21247   SDLoc dl(GA);  // ? function entry point might be better
21248   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
21249                                    DAG.getNode(X86ISD::GlobalBaseReg,
21250                                                SDLoc(), PtrVT), InGlue);
21251   InGlue = Chain.getValue(1);
21252 
21253   return GetTLSADDR(DAG, Chain, GA, &InGlue, PtrVT, X86::EAX, X86II::MO_TLSGD);
21254 }
21255 
21256 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
21257 static SDValue
21258 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
21259                                 const EVT PtrVT) {
21260   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
21261                     X86::RAX, X86II::MO_TLSGD);
21262 }
21263 
21264 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
21265 static SDValue
21266 LowerToTLSGeneralDynamicModelX32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
21267                                  const EVT PtrVT) {
21268   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
21269                     X86::EAX, X86II::MO_TLSGD);
21270 }
21271 
21272 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
21273                                            SelectionDAG &DAG, const EVT PtrVT,
21274                                            bool Is64Bit, bool Is64BitLP64) {
21275   SDLoc dl(GA);
21276 
21277   // Get the start address of the TLS block for this module.
21278   X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
21279       .getInfo<X86MachineFunctionInfo>();
21280   MFI->incNumLocalDynamicTLSAccesses();
21281 
21282   SDValue Base;
21283   if (Is64Bit) {
21284     unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
21285     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, ReturnReg,
21286                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
21287   } else {
21288     SDValue InGlue;
21289     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
21290         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InGlue);
21291     InGlue = Chain.getValue(1);
21292     Base = GetTLSADDR(DAG, Chain, GA, &InGlue, PtrVT, X86::EAX,
21293                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
21294   }
21295 
21296   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
21297   // of Base.
21298 
21299   // Build x@dtpoff.
21300   unsigned char OperandFlags = X86II::MO_DTPOFF;
21301   unsigned WrapperKind = X86ISD::Wrapper;
21302   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
21303                                            GA->getValueType(0),
21304                                            GA->getOffset(), OperandFlags);
21305   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
21306 
21307   // Add x@dtpoff with the base.
21308   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
21309 }
21310 
21311 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
21312 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
21313                                    const EVT PtrVT, TLSModel::Model model,
21314                                    bool is64Bit, bool isPIC) {
21315   SDLoc dl(GA);
21316 
21317   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
21318   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
21319                                                          is64Bit ? 257 : 256));
21320 
21321   SDValue ThreadPointer =
21322       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
21323                   MachinePointerInfo(Ptr));
21324 
21325   unsigned char OperandFlags = 0;
21326   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
21327   // initialexec.
21328   unsigned WrapperKind = X86ISD::Wrapper;
21329   if (model == TLSModel::LocalExec) {
21330     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
21331   } else if (model == TLSModel::InitialExec) {
21332     if (is64Bit) {
21333       OperandFlags = X86II::MO_GOTTPOFF;
21334       WrapperKind = X86ISD::WrapperRIP;
21335     } else {
21336       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
21337     }
21338   } else {
21339     llvm_unreachable("Unexpected model");
21340   }
21341 
21342   // emit "addl x@ntpoff,%eax" (local exec)
21343   // or "addl x@indntpoff,%eax" (initial exec)
21344   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
21345   SDValue TGA =
21346       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
21347                                  GA->getOffset(), OperandFlags);
21348   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
21349 
21350   if (model == TLSModel::InitialExec) {
21351     if (isPIC && !is64Bit) {
21352       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
21353                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
21354                            Offset);
21355     }
21356 
21357     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
21358                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
21359   }
21360 
21361   // The address of the thread local variable is the add of the thread
21362   // pointer with the offset of the variable.
21363   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
21364 }
21365 
21366 SDValue
21367 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
21368 
21369   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
21370 
21371   if (DAG.getTarget().useEmulatedTLS())
21372     return LowerToTLSEmulatedModel(GA, DAG);
21373 
21374   const GlobalValue *GV = GA->getGlobal();
21375   auto PtrVT = getPointerTy(DAG.getDataLayout());
21376   bool PositionIndependent = isPositionIndependent();
21377 
21378   if (Subtarget.isTargetELF()) {
21379     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
21380     switch (model) {
21381       case TLSModel::GeneralDynamic:
21382         if (Subtarget.is64Bit()) {
21383           if (Subtarget.isTarget64BitLP64())
21384             return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
21385           return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
21386         }
21387         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
21388       case TLSModel::LocalDynamic:
21389         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
21390                                            Subtarget.isTarget64BitLP64());
21391       case TLSModel::InitialExec:
21392       case TLSModel::LocalExec:
21393         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
21394                                    PositionIndependent);
21395     }
21396     llvm_unreachable("Unknown TLS model.");
21397   }
21398 
21399   if (Subtarget.isTargetDarwin()) {
21400     // Darwin only has one model of TLS.  Lower to that.
21401     unsigned char OpFlag = 0;
21402     unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
21403                            X86ISD::WrapperRIP : X86ISD::Wrapper;
21404 
21405     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
21406     // global base reg.
21407     bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
21408     if (PIC32)
21409       OpFlag = X86II::MO_TLVP_PIC_BASE;
21410     else
21411       OpFlag = X86II::MO_TLVP;
21412     SDLoc DL(Op);
21413     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
21414                                                 GA->getValueType(0),
21415                                                 GA->getOffset(), OpFlag);
21416     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
21417 
21418     // With PIC32, the address is actually $g + Offset.
21419     if (PIC32)
21420       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
21421                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
21422                            Offset);
21423 
21424     // Lowering the machine isd will make sure everything is in the right
21425     // location.
21426     SDValue Chain = DAG.getEntryNode();
21427     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
21428     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
21429     SDValue Args[] = { Chain, Offset };
21430     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
21431     Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), DL);
21432 
21433     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
21434     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
21435     MFI.setAdjustsStack(true);
21436 
21437     // And our return value (tls address) is in the standard call return value
21438     // location.
21439     unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
21440     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
21441   }
21442 
21443   if (Subtarget.isOSWindows()) {
21444     // Just use the implicit TLS architecture
21445     // Need to generate something similar to:
21446     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
21447     //                                  ; from TEB
21448     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
21449     //   mov     rcx, qword [rdx+rcx*8]
21450     //   mov     eax, .tls$:tlsvar
21451     //   [rax+rcx] contains the address
21452     // Windows 64bit: gs:0x58
21453     // Windows 32bit: fs:__tls_array
21454 
21455     SDLoc dl(GA);
21456     SDValue Chain = DAG.getEntryNode();
21457 
21458     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
21459     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
21460     // use its literal value of 0x2C.
21461     Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
21462                                         ? Type::getInt8PtrTy(*DAG.getContext(),
21463                                                              256)
21464                                         : Type::getInt32PtrTy(*DAG.getContext(),
21465                                                               257));
21466 
21467     SDValue TlsArray = Subtarget.is64Bit()
21468                            ? DAG.getIntPtrConstant(0x58, dl)
21469                            : (Subtarget.isTargetWindowsGNU()
21470                                   ? DAG.getIntPtrConstant(0x2C, dl)
21471                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
21472 
21473     SDValue ThreadPointer =
21474         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
21475 
21476     SDValue res;
21477     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
21478       res = ThreadPointer;
21479     } else {
21480       // Load the _tls_index variable
21481       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
21482       if (Subtarget.is64Bit())
21483         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
21484                              MachinePointerInfo(), MVT::i32);
21485       else
21486         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
21487 
21488       const DataLayout &DL = DAG.getDataLayout();
21489       SDValue Scale =
21490           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
21491       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
21492 
21493       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
21494     }
21495 
21496     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
21497 
21498     // Get the offset of start of .tls section
21499     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
21500                                              GA->getValueType(0),
21501                                              GA->getOffset(), X86II::MO_SECREL);
21502     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
21503 
21504     // The address of the thread local variable is the add of the thread
21505     // pointer with the offset of the variable.
21506     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
21507   }
21508 
21509   llvm_unreachable("TLS not implemented for this target.");
21510 }
21511 
21512 /// Lower SRA_PARTS and friends, which return two i32 values
21513 /// and take a 2 x i32 value to shift plus a shift amount.
21514 /// TODO: Can this be moved to general expansion code?
21515 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
21516   SDValue Lo, Hi;
21517   DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
21518   return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
21519 }
21520 
21521 // Try to use a packed vector operation to handle i64 on 32-bit targets when
21522 // AVX512DQ is enabled.
21523 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
21524                                         const X86Subtarget &Subtarget) {
21525   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
21526           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
21527           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
21528           Op.getOpcode() == ISD::UINT_TO_FP) &&
21529          "Unexpected opcode!");
21530   bool IsStrict = Op->isStrictFPOpcode();
21531   unsigned OpNo = IsStrict ? 1 : 0;
21532   SDValue Src = Op.getOperand(OpNo);
21533   MVT SrcVT = Src.getSimpleValueType();
21534   MVT VT = Op.getSimpleValueType();
21535 
21536    if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
21537        (VT != MVT::f32 && VT != MVT::f64))
21538     return SDValue();
21539 
21540   // Pack the i64 into a vector, do the operation and extract.
21541 
21542   // Using 256-bit to ensure result is 128-bits for f32 case.
21543   unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
21544   MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
21545   MVT VecVT = MVT::getVectorVT(VT, NumElts);
21546 
21547   SDLoc dl(Op);
21548   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
21549   if (IsStrict) {
21550     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
21551                                  {Op.getOperand(0), InVec});
21552     SDValue Chain = CvtVec.getValue(1);
21553     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
21554                                 DAG.getIntPtrConstant(0, dl));
21555     return DAG.getMergeValues({Value, Chain}, dl);
21556   }
21557 
21558   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
21559 
21560   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
21561                      DAG.getIntPtrConstant(0, dl));
21562 }
21563 
21564 // Try to use a packed vector operation to handle i64 on 32-bit targets.
21565 static SDValue LowerI64IntToFP16(SDValue Op, SelectionDAG &DAG,
21566                                  const X86Subtarget &Subtarget) {
21567   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
21568           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
21569           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
21570           Op.getOpcode() == ISD::UINT_TO_FP) &&
21571          "Unexpected opcode!");
21572   bool IsStrict = Op->isStrictFPOpcode();
21573   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21574   MVT SrcVT = Src.getSimpleValueType();
21575   MVT VT = Op.getSimpleValueType();
21576 
21577   if (SrcVT != MVT::i64 || Subtarget.is64Bit() || VT != MVT::f16)
21578     return SDValue();
21579 
21580   // Pack the i64 into a vector, do the operation and extract.
21581 
21582   assert(Subtarget.hasFP16() && "Expected FP16");
21583 
21584   SDLoc dl(Op);
21585   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
21586   if (IsStrict) {
21587     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {MVT::v2f16, MVT::Other},
21588                                  {Op.getOperand(0), InVec});
21589     SDValue Chain = CvtVec.getValue(1);
21590     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
21591                                 DAG.getIntPtrConstant(0, dl));
21592     return DAG.getMergeValues({Value, Chain}, dl);
21593   }
21594 
21595   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, MVT::v2f16, InVec);
21596 
21597   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
21598                      DAG.getIntPtrConstant(0, dl));
21599 }
21600 
21601 static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
21602                           const X86Subtarget &Subtarget) {
21603   switch (Opcode) {
21604     case ISD::SINT_TO_FP:
21605       // TODO: Handle wider types with AVX/AVX512.
21606       if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
21607         return false;
21608       // CVTDQ2PS or (V)CVTDQ2PD
21609       return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
21610 
21611     case ISD::UINT_TO_FP:
21612       // TODO: Handle wider types and i64 elements.
21613       if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
21614         return false;
21615       // VCVTUDQ2PS or VCVTUDQ2PD
21616       return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
21617 
21618     default:
21619       return false;
21620   }
21621 }
21622 
21623 /// Given a scalar cast operation that is extracted from a vector, try to
21624 /// vectorize the cast op followed by extraction. This will avoid an expensive
21625 /// round-trip between XMM and GPR.
21626 static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
21627                                       const X86Subtarget &Subtarget) {
21628   // TODO: This could be enhanced to handle smaller integer types by peeking
21629   // through an extend.
21630   SDValue Extract = Cast.getOperand(0);
21631   MVT DestVT = Cast.getSimpleValueType();
21632   if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21633       !isa<ConstantSDNode>(Extract.getOperand(1)))
21634     return SDValue();
21635 
21636   // See if we have a 128-bit vector cast op for this type of cast.
21637   SDValue VecOp = Extract.getOperand(0);
21638   MVT FromVT = VecOp.getSimpleValueType();
21639   unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
21640   MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
21641   MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
21642   if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
21643     return SDValue();
21644 
21645   // If we are extracting from a non-zero element, first shuffle the source
21646   // vector to allow extracting from element zero.
21647   SDLoc DL(Cast);
21648   if (!isNullConstant(Extract.getOperand(1))) {
21649     SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
21650     Mask[0] = Extract.getConstantOperandVal(1);
21651     VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
21652   }
21653   // If the source vector is wider than 128-bits, extract the low part. Do not
21654   // create an unnecessarily wide vector cast op.
21655   if (FromVT != Vec128VT)
21656     VecOp = extract128BitVector(VecOp, 0, DAG, DL);
21657 
21658   // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
21659   // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
21660   SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
21661   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
21662                      DAG.getIntPtrConstant(0, DL));
21663 }
21664 
21665 /// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
21666 /// try to vectorize the cast ops. This will avoid an expensive round-trip
21667 /// between XMM and GPR.
21668 static SDValue lowerFPToIntToFP(SDValue CastToFP, SelectionDAG &DAG,
21669                                 const X86Subtarget &Subtarget) {
21670   // TODO: Allow FP_TO_UINT.
21671   SDValue CastToInt = CastToFP.getOperand(0);
21672   MVT VT = CastToFP.getSimpleValueType();
21673   if (CastToInt.getOpcode() != ISD::FP_TO_SINT || VT.isVector())
21674     return SDValue();
21675 
21676   MVT IntVT = CastToInt.getSimpleValueType();
21677   SDValue X = CastToInt.getOperand(0);
21678   MVT SrcVT = X.getSimpleValueType();
21679   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
21680     return SDValue();
21681 
21682   // See if we have 128-bit vector cast instructions for this type of cast.
21683   // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
21684   if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
21685       IntVT != MVT::i32)
21686     return SDValue();
21687 
21688   unsigned SrcSize = SrcVT.getSizeInBits();
21689   unsigned IntSize = IntVT.getSizeInBits();
21690   unsigned VTSize = VT.getSizeInBits();
21691   MVT VecSrcVT = MVT::getVectorVT(SrcVT, 128 / SrcSize);
21692   MVT VecIntVT = MVT::getVectorVT(IntVT, 128 / IntSize);
21693   MVT VecVT = MVT::getVectorVT(VT, 128 / VTSize);
21694 
21695   // We need target-specific opcodes if this is v2f64 -> v4i32 -> v2f64.
21696   unsigned ToIntOpcode =
21697       SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
21698   unsigned ToFPOpcode =
21699       IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
21700 
21701   // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
21702   //
21703   // We are not defining the high elements (for example, zero them) because
21704   // that could nullify any performance advantage that we hoped to gain from
21705   // this vector op hack. We do not expect any adverse effects (like denorm
21706   // penalties) with cast ops.
21707   SDLoc DL(CastToFP);
21708   SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
21709   SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
21710   SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
21711   SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
21712   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
21713 }
21714 
21715 static SDValue lowerINT_TO_FP_vXi64(SDValue Op, SelectionDAG &DAG,
21716                                     const X86Subtarget &Subtarget) {
21717   SDLoc DL(Op);
21718   bool IsStrict = Op->isStrictFPOpcode();
21719   MVT VT = Op->getSimpleValueType(0);
21720   SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
21721 
21722   if (Subtarget.hasDQI()) {
21723     assert(!Subtarget.hasVLX() && "Unexpected features");
21724 
21725     assert((Src.getSimpleValueType() == MVT::v2i64 ||
21726             Src.getSimpleValueType() == MVT::v4i64) &&
21727            "Unsupported custom type");
21728 
21729     // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
21730     assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
21731            "Unexpected VT!");
21732     MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
21733 
21734     // Need to concat with zero vector for strict fp to avoid spurious
21735     // exceptions.
21736     SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
21737                            : DAG.getUNDEF(MVT::v8i64);
21738     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
21739                       DAG.getIntPtrConstant(0, DL));
21740     SDValue Res, Chain;
21741     if (IsStrict) {
21742       Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
21743                         {Op->getOperand(0), Src});
21744       Chain = Res.getValue(1);
21745     } else {
21746       Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
21747     }
21748 
21749     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
21750                       DAG.getIntPtrConstant(0, DL));
21751 
21752     if (IsStrict)
21753       return DAG.getMergeValues({Res, Chain}, DL);
21754     return Res;
21755   }
21756 
21757   bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
21758                   Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
21759   if (VT != MVT::v4f32 || IsSigned)
21760     return SDValue();
21761 
21762   SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
21763   SDValue One  = DAG.getConstant(1, DL, MVT::v4i64);
21764   SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
21765                              DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
21766                              DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
21767   SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
21768   SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
21769   SmallVector<SDValue, 4> SignCvts(4);
21770   SmallVector<SDValue, 4> Chains(4);
21771   for (int i = 0; i != 4; ++i) {
21772     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
21773                               DAG.getIntPtrConstant(i, DL));
21774     if (IsStrict) {
21775       SignCvts[i] =
21776           DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
21777                       {Op.getOperand(0), Elt});
21778       Chains[i] = SignCvts[i].getValue(1);
21779     } else {
21780       SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
21781     }
21782   }
21783   SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
21784 
21785   SDValue Slow, Chain;
21786   if (IsStrict) {
21787     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
21788     Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
21789                        {Chain, SignCvt, SignCvt});
21790     Chain = Slow.getValue(1);
21791   } else {
21792     Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
21793   }
21794 
21795   IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
21796   SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
21797 
21798   if (IsStrict)
21799     return DAG.getMergeValues({Cvt, Chain}, DL);
21800 
21801   return Cvt;
21802 }
21803 
21804 static SDValue promoteXINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
21805   bool IsStrict = Op->isStrictFPOpcode();
21806   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21807   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
21808   MVT VT = Op.getSimpleValueType();
21809   MVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
21810   SDLoc dl(Op);
21811 
21812   SDValue Rnd = DAG.getIntPtrConstant(0, dl);
21813   if (IsStrict)
21814     return DAG.getNode(
21815         ISD::STRICT_FP_ROUND, dl, {VT, MVT::Other},
21816         {Chain,
21817          DAG.getNode(Op.getOpcode(), dl, {NVT, MVT::Other}, {Chain, Src}),
21818          Rnd});
21819   return DAG.getNode(ISD::FP_ROUND, dl, VT,
21820                      DAG.getNode(Op.getOpcode(), dl, NVT, Src), Rnd);
21821 }
21822 
21823 static bool isLegalConversion(MVT VT, bool IsSigned,
21824                               const X86Subtarget &Subtarget) {
21825   if (VT == MVT::v4i32 && Subtarget.hasSSE2() && IsSigned)
21826     return true;
21827   if (VT == MVT::v8i32 && Subtarget.hasAVX() && IsSigned)
21828     return true;
21829   if (Subtarget.hasVLX() && (VT == MVT::v4i32 || VT == MVT::v8i32))
21830     return true;
21831   if (Subtarget.useAVX512Regs()) {
21832     if (VT == MVT::v16i32)
21833       return true;
21834     if (VT == MVT::v8i64 && Subtarget.hasDQI())
21835       return true;
21836   }
21837   if (Subtarget.hasDQI() && Subtarget.hasVLX() &&
21838       (VT == MVT::v2i64 || VT == MVT::v4i64))
21839     return true;
21840   return false;
21841 }
21842 
21843 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
21844                                            SelectionDAG &DAG) const {
21845   bool IsStrict = Op->isStrictFPOpcode();
21846   unsigned OpNo = IsStrict ? 1 : 0;
21847   SDValue Src = Op.getOperand(OpNo);
21848   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
21849   MVT SrcVT = Src.getSimpleValueType();
21850   MVT VT = Op.getSimpleValueType();
21851   SDLoc dl(Op);
21852 
21853   if (isSoftF16(VT, Subtarget))
21854     return promoteXINT_TO_FP(Op, DAG);
21855   else if (isLegalConversion(SrcVT, true, Subtarget))
21856     return Op;
21857 
21858   if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
21859     return LowerWin64_INT128_TO_FP(Op, DAG);
21860 
21861   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
21862     return Extract;
21863 
21864   if (SDValue R = lowerFPToIntToFP(Op, DAG, Subtarget))
21865     return R;
21866 
21867   if (SrcVT.isVector()) {
21868     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
21869       // Note: Since v2f64 is a legal type. We don't need to zero extend the
21870       // source for strict FP.
21871       if (IsStrict)
21872         return DAG.getNode(
21873             X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
21874             {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
21875                                 DAG.getUNDEF(SrcVT))});
21876       return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
21877                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
21878                                      DAG.getUNDEF(SrcVT)));
21879     }
21880     if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
21881       return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
21882 
21883     return SDValue();
21884   }
21885 
21886   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
21887          "Unknown SINT_TO_FP to lower!");
21888 
21889   bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
21890 
21891   // These are really Legal; return the operand so the caller accepts it as
21892   // Legal.
21893   if (SrcVT == MVT::i32 && UseSSEReg)
21894     return Op;
21895   if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
21896     return Op;
21897 
21898   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
21899     return V;
21900   if (SDValue V = LowerI64IntToFP16(Op, DAG, Subtarget))
21901     return V;
21902 
21903   // SSE doesn't have an i16 conversion so we need to promote.
21904   if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
21905     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
21906     if (IsStrict)
21907       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
21908                          {Chain, Ext});
21909 
21910     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
21911   }
21912 
21913   if (VT == MVT::f128 || !Subtarget.hasX87())
21914     return SDValue();
21915 
21916   SDValue ValueToStore = Src;
21917   if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
21918     // Bitcasting to f64 here allows us to do a single 64-bit store from
21919     // an SSE register, avoiding the store forwarding penalty that would come
21920     // with two 32-bit stores.
21921     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
21922 
21923   unsigned Size = SrcVT.getStoreSize();
21924   Align Alignment(Size);
21925   MachineFunction &MF = DAG.getMachineFunction();
21926   auto PtrVT = getPointerTy(MF.getDataLayout());
21927   int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
21928   MachinePointerInfo MPI =
21929       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
21930   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
21931   Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
21932   std::pair<SDValue, SDValue> Tmp =
21933       BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
21934 
21935   if (IsStrict)
21936     return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
21937 
21938   return Tmp.first;
21939 }
21940 
21941 std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
21942     EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
21943     MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
21944   // Build the FILD
21945   SDVTList Tys;
21946   bool useSSE = isScalarFPTypeInSSEReg(DstVT);
21947   if (useSSE)
21948     Tys = DAG.getVTList(MVT::f80, MVT::Other);
21949   else
21950     Tys = DAG.getVTList(DstVT, MVT::Other);
21951 
21952   SDValue FILDOps[] = {Chain, Pointer};
21953   SDValue Result =
21954       DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
21955                               Alignment, MachineMemOperand::MOLoad);
21956   Chain = Result.getValue(1);
21957 
21958   if (useSSE) {
21959     MachineFunction &MF = DAG.getMachineFunction();
21960     unsigned SSFISize = DstVT.getStoreSize();
21961     int SSFI =
21962         MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
21963     auto PtrVT = getPointerTy(MF.getDataLayout());
21964     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
21965     Tys = DAG.getVTList(MVT::Other);
21966     SDValue FSTOps[] = {Chain, Result, StackSlot};
21967     MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
21968         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
21969         MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
21970 
21971     Chain =
21972         DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
21973     Result = DAG.getLoad(
21974         DstVT, DL, Chain, StackSlot,
21975         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
21976     Chain = Result.getValue(1);
21977   }
21978 
21979   return { Result, Chain };
21980 }
21981 
21982 /// Horizontal vector math instructions may be slower than normal math with
21983 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
21984 /// implementation, and likely shuffle complexity of the alternate sequence.
21985 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
21986                                   const X86Subtarget &Subtarget) {
21987   bool IsOptimizingSize = DAG.shouldOptForSize();
21988   bool HasFastHOps = Subtarget.hasFastHorizontalOps();
21989   return !IsSingleSource || IsOptimizingSize || HasFastHOps;
21990 }
21991 
21992 /// 64-bit unsigned integer to double expansion.
21993 static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
21994                                    const X86Subtarget &Subtarget) {
21995   // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
21996   // when converting 0 when rounding toward negative infinity. Caller will
21997   // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
21998   assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!");
21999   // This algorithm is not obvious. Here it is what we're trying to output:
22000   /*
22001      movq       %rax,  %xmm0
22002      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
22003      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
22004      #ifdef __SSE3__
22005        haddpd   %xmm0, %xmm0
22006      #else
22007        pshufd   $0x4e, %xmm0, %xmm1
22008        addpd    %xmm1, %xmm0
22009      #endif
22010   */
22011 
22012   SDLoc dl(Op);
22013   LLVMContext *Context = DAG.getContext();
22014 
22015   // Build some magic constants.
22016   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
22017   Constant *C0 = ConstantDataVector::get(*Context, CV0);
22018   auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
22019   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
22020 
22021   SmallVector<Constant*,2> CV1;
22022   CV1.push_back(
22023     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
22024                                       APInt(64, 0x4330000000000000ULL))));
22025   CV1.push_back(
22026     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
22027                                       APInt(64, 0x4530000000000000ULL))));
22028   Constant *C1 = ConstantVector::get(CV1);
22029   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
22030 
22031   // Load the 64-bit value into an XMM register.
22032   SDValue XR1 =
22033       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
22034   SDValue CLod0 = DAG.getLoad(
22035       MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
22036       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
22037   SDValue Unpck1 =
22038       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
22039 
22040   SDValue CLod1 = DAG.getLoad(
22041       MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
22042       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
22043   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
22044   // TODO: Are there any fast-math-flags to propagate here?
22045   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
22046   SDValue Result;
22047 
22048   if (Subtarget.hasSSE3() &&
22049       shouldUseHorizontalOp(true, DAG, Subtarget)) {
22050     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
22051   } else {
22052     SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
22053     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
22054   }
22055   Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
22056                        DAG.getIntPtrConstant(0, dl));
22057   return Result;
22058 }
22059 
22060 /// 32-bit unsigned integer to float expansion.
22061 static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
22062                                    const X86Subtarget &Subtarget) {
22063   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
22064   SDLoc dl(Op);
22065   // FP constant to bias correct the final result.
22066   SDValue Bias = DAG.getConstantFP(
22067       llvm::bit_cast<double>(0x4330000000000000ULL), dl, MVT::f64);
22068 
22069   // Load the 32-bit value into an XMM register.
22070   SDValue Load =
22071       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
22072 
22073   // Zero out the upper parts of the register.
22074   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
22075 
22076   // Or the load with the bias.
22077   SDValue Or = DAG.getNode(
22078       ISD::OR, dl, MVT::v2i64,
22079       DAG.getBitcast(MVT::v2i64, Load),
22080       DAG.getBitcast(MVT::v2i64,
22081                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
22082   Or =
22083       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
22084                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
22085 
22086   if (Op.getNode()->isStrictFPOpcode()) {
22087     // Subtract the bias.
22088     // TODO: Are there any fast-math-flags to propagate here?
22089     SDValue Chain = Op.getOperand(0);
22090     SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
22091                               {Chain, Or, Bias});
22092 
22093     if (Op.getValueType() == Sub.getValueType())
22094       return Sub;
22095 
22096     // Handle final rounding.
22097     std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
22098         Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
22099 
22100     return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
22101   }
22102 
22103   // Subtract the bias.
22104   // TODO: Are there any fast-math-flags to propagate here?
22105   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
22106 
22107   // Handle final rounding.
22108   return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
22109 }
22110 
22111 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
22112                                      const X86Subtarget &Subtarget,
22113                                      const SDLoc &DL) {
22114   if (Op.getSimpleValueType() != MVT::v2f64)
22115     return SDValue();
22116 
22117   bool IsStrict = Op->isStrictFPOpcode();
22118 
22119   SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
22120   assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
22121 
22122   if (Subtarget.hasAVX512()) {
22123     if (!Subtarget.hasVLX()) {
22124       // Let generic type legalization widen this.
22125       if (!IsStrict)
22126         return SDValue();
22127       // Otherwise pad the integer input with 0s and widen the operation.
22128       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
22129                        DAG.getConstant(0, DL, MVT::v2i32));
22130       SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
22131                                 {Op.getOperand(0), N0});
22132       SDValue Chain = Res.getValue(1);
22133       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
22134                         DAG.getIntPtrConstant(0, DL));
22135       return DAG.getMergeValues({Res, Chain}, DL);
22136     }
22137 
22138     // Legalize to v4i32 type.
22139     N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
22140                      DAG.getUNDEF(MVT::v2i32));
22141     if (IsStrict)
22142       return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
22143                          {Op.getOperand(0), N0});
22144     return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
22145   }
22146 
22147   // Zero extend to 2i64, OR with the floating point representation of 2^52.
22148   // This gives us the floating point equivalent of 2^52 + the i32 integer
22149   // since double has 52-bits of mantissa. Then subtract 2^52 in floating
22150   // point leaving just our i32 integers in double format.
22151   SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
22152   SDValue VBias = DAG.getConstantFP(
22153       llvm::bit_cast<double>(0x4330000000000000ULL), DL, MVT::v2f64);
22154   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
22155                            DAG.getBitcast(MVT::v2i64, VBias));
22156   Or = DAG.getBitcast(MVT::v2f64, Or);
22157 
22158   if (IsStrict)
22159     return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
22160                        {Op.getOperand(0), Or, VBias});
22161   return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
22162 }
22163 
22164 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
22165                                      const X86Subtarget &Subtarget) {
22166   SDLoc DL(Op);
22167   bool IsStrict = Op->isStrictFPOpcode();
22168   SDValue V = Op->getOperand(IsStrict ? 1 : 0);
22169   MVT VecIntVT = V.getSimpleValueType();
22170   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
22171          "Unsupported custom type");
22172 
22173   if (Subtarget.hasAVX512()) {
22174     // With AVX512, but not VLX we need to widen to get a 512-bit result type.
22175     assert(!Subtarget.hasVLX() && "Unexpected features");
22176     MVT VT = Op->getSimpleValueType(0);
22177 
22178     // v8i32->v8f64 is legal with AVX512 so just return it.
22179     if (VT == MVT::v8f64)
22180       return Op;
22181 
22182     assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&
22183            "Unexpected VT!");
22184     MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
22185     MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
22186     // Need to concat with zero vector for strict fp to avoid spurious
22187     // exceptions.
22188     SDValue Tmp =
22189         IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
22190     V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
22191                     DAG.getIntPtrConstant(0, DL));
22192     SDValue Res, Chain;
22193     if (IsStrict) {
22194       Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
22195                         {Op->getOperand(0), V});
22196       Chain = Res.getValue(1);
22197     } else {
22198       Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
22199     }
22200 
22201     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
22202                       DAG.getIntPtrConstant(0, DL));
22203 
22204     if (IsStrict)
22205       return DAG.getMergeValues({Res, Chain}, DL);
22206     return Res;
22207   }
22208 
22209   if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
22210       Op->getSimpleValueType(0) == MVT::v4f64) {
22211     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
22212     Constant *Bias = ConstantFP::get(
22213         *DAG.getContext(),
22214         APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
22215     auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
22216     SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
22217     SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
22218     SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
22219     SDValue VBias = DAG.getMemIntrinsicNode(
22220         X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
22221         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(8),
22222         MachineMemOperand::MOLoad);
22223 
22224     SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
22225                              DAG.getBitcast(MVT::v4i64, VBias));
22226     Or = DAG.getBitcast(MVT::v4f64, Or);
22227 
22228     if (IsStrict)
22229       return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
22230                          {Op.getOperand(0), Or, VBias});
22231     return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
22232   }
22233 
22234   // The algorithm is the following:
22235   // #ifdef __SSE4_1__
22236   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
22237   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
22238   //                                 (uint4) 0x53000000, 0xaa);
22239   // #else
22240   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
22241   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
22242   // #endif
22243   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
22244   //     return (float4) lo + fhi;
22245 
22246   bool Is128 = VecIntVT == MVT::v4i32;
22247   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
22248   // If we convert to something else than the supported type, e.g., to v4f64,
22249   // abort early.
22250   if (VecFloatVT != Op->getSimpleValueType(0))
22251     return SDValue();
22252 
22253   // In the #idef/#else code, we have in common:
22254   // - The vector of constants:
22255   // -- 0x4b000000
22256   // -- 0x53000000
22257   // - A shift:
22258   // -- v >> 16
22259 
22260   // Create the splat vector for 0x4b000000.
22261   SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
22262   // Create the splat vector for 0x53000000.
22263   SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
22264 
22265   // Create the right shift.
22266   SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
22267   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
22268 
22269   SDValue Low, High;
22270   if (Subtarget.hasSSE41()) {
22271     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
22272     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
22273     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
22274     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
22275     // Low will be bitcasted right away, so do not bother bitcasting back to its
22276     // original type.
22277     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
22278                       VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
22279     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
22280     //                                 (uint4) 0x53000000, 0xaa);
22281     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
22282     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
22283     // High will be bitcasted right away, so do not bother bitcasting back to
22284     // its original type.
22285     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
22286                        VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
22287   } else {
22288     SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
22289     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
22290     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
22291     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
22292 
22293     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
22294     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
22295   }
22296 
22297   // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
22298   SDValue VecCstFSub = DAG.getConstantFP(
22299       APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
22300 
22301   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
22302   // NOTE: By using fsub of a positive constant instead of fadd of a negative
22303   // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
22304   // enabled. See PR24512.
22305   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
22306   // TODO: Are there any fast-math-flags to propagate here?
22307   //     (float4) lo;
22308   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
22309   //     return (float4) lo + fhi;
22310   if (IsStrict) {
22311     SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
22312                                 {Op.getOperand(0), HighBitcast, VecCstFSub});
22313     return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
22314                        {FHigh.getValue(1), LowBitcast, FHigh});
22315   }
22316 
22317   SDValue FHigh =
22318       DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
22319   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
22320 }
22321 
22322 static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
22323                                    const X86Subtarget &Subtarget) {
22324   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
22325   SDValue N0 = Op.getOperand(OpNo);
22326   MVT SrcVT = N0.getSimpleValueType();
22327   SDLoc dl(Op);
22328 
22329   switch (SrcVT.SimpleTy) {
22330   default:
22331     llvm_unreachable("Custom UINT_TO_FP is not supported!");
22332   case MVT::v2i32:
22333     return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
22334   case MVT::v4i32:
22335   case MVT::v8i32:
22336     return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
22337   case MVT::v2i64:
22338   case MVT::v4i64:
22339     return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
22340   }
22341 }
22342 
22343 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
22344                                            SelectionDAG &DAG) const {
22345   bool IsStrict = Op->isStrictFPOpcode();
22346   unsigned OpNo = IsStrict ? 1 : 0;
22347   SDValue Src = Op.getOperand(OpNo);
22348   SDLoc dl(Op);
22349   auto PtrVT = getPointerTy(DAG.getDataLayout());
22350   MVT SrcVT = Src.getSimpleValueType();
22351   MVT DstVT = Op->getSimpleValueType(0);
22352   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
22353 
22354   // Bail out when we don't have native conversion instructions.
22355   if (DstVT == MVT::f128)
22356     return SDValue();
22357 
22358   if (isSoftF16(DstVT, Subtarget))
22359     return promoteXINT_TO_FP(Op, DAG);
22360   else if (isLegalConversion(SrcVT, false, Subtarget))
22361     return Op;
22362 
22363   if (DstVT.isVector())
22364     return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
22365 
22366   if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
22367     return LowerWin64_INT128_TO_FP(Op, DAG);
22368 
22369   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
22370     return Extract;
22371 
22372   if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
22373       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
22374     // Conversions from unsigned i32 to f32/f64 are legal,
22375     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
22376     return Op;
22377   }
22378 
22379   // Promote i32 to i64 and use a signed conversion on 64-bit targets.
22380   if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
22381     Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
22382     if (IsStrict)
22383       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
22384                          {Chain, Src});
22385     return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
22386   }
22387 
22388   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
22389     return V;
22390   if (SDValue V = LowerI64IntToFP16(Op, DAG, Subtarget))
22391     return V;
22392 
22393   // The transform for i64->f64 isn't correct for 0 when rounding to negative
22394   // infinity. It produces -0.0, so disable under strictfp.
22395   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && Subtarget.hasSSE2() &&
22396       !IsStrict)
22397     return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
22398   // The transform for i32->f64/f32 isn't correct for 0 when rounding to
22399   // negative infinity. So disable under strictfp. Using FILD instead.
22400   if (SrcVT == MVT::i32 && Subtarget.hasSSE2() && DstVT != MVT::f80 &&
22401       !IsStrict)
22402     return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
22403   if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
22404       (DstVT == MVT::f32 || DstVT == MVT::f64))
22405     return SDValue();
22406 
22407   // Make a 64-bit buffer, and use it to build an FILD.
22408   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
22409   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
22410   Align SlotAlign(8);
22411   MachinePointerInfo MPI =
22412     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
22413   if (SrcVT == MVT::i32) {
22414     SDValue OffsetSlot =
22415         DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl);
22416     SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
22417     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
22418                                   OffsetSlot, MPI.getWithOffset(4), SlotAlign);
22419     std::pair<SDValue, SDValue> Tmp =
22420         BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
22421     if (IsStrict)
22422       return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
22423 
22424     return Tmp.first;
22425   }
22426 
22427   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
22428   SDValue ValueToStore = Src;
22429   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
22430     // Bitcasting to f64 here allows us to do a single 64-bit store from
22431     // an SSE register, avoiding the store forwarding penalty that would come
22432     // with two 32-bit stores.
22433     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
22434   }
22435   SDValue Store =
22436       DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
22437   // For i64 source, we need to add the appropriate power of 2 if the input
22438   // was negative. We must be careful to do the computation in x87 extended
22439   // precision, not in SSE.
22440   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
22441   SDValue Ops[] = { Store, StackSlot };
22442   SDValue Fild =
22443       DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
22444                               SlotAlign, MachineMemOperand::MOLoad);
22445   Chain = Fild.getValue(1);
22446 
22447 
22448   // Check whether the sign bit is set.
22449   SDValue SignSet = DAG.getSetCC(
22450       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
22451       Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
22452 
22453   // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
22454   APInt FF(64, 0x5F80000000000000ULL);
22455   SDValue FudgePtr = DAG.getConstantPool(
22456       ConstantInt::get(*DAG.getContext(), FF), PtrVT);
22457   Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
22458 
22459   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
22460   SDValue Zero = DAG.getIntPtrConstant(0, dl);
22461   SDValue Four = DAG.getIntPtrConstant(4, dl);
22462   SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
22463   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
22464 
22465   // Load the value out, extending it from f32 to f80.
22466   SDValue Fudge = DAG.getExtLoad(
22467       ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
22468       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
22469       CPAlignment);
22470   Chain = Fudge.getValue(1);
22471   // Extend everything to 80 bits to force it to be done on x87.
22472   // TODO: Are there any fast-math-flags to propagate here?
22473   if (IsStrict) {
22474     unsigned Opc = ISD::STRICT_FADD;
22475     // Windows needs the precision control changed to 80bits around this add.
22476     if (Subtarget.isOSWindows() && DstVT == MVT::f32)
22477       Opc = X86ISD::STRICT_FP80_ADD;
22478 
22479     SDValue Add =
22480         DAG.getNode(Opc, dl, {MVT::f80, MVT::Other}, {Chain, Fild, Fudge});
22481     // STRICT_FP_ROUND can't handle equal types.
22482     if (DstVT == MVT::f80)
22483       return Add;
22484     return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
22485                        {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
22486   }
22487   unsigned Opc = ISD::FADD;
22488   // Windows needs the precision control changed to 80bits around this add.
22489   if (Subtarget.isOSWindows() && DstVT == MVT::f32)
22490     Opc = X86ISD::FP80_ADD;
22491 
22492   SDValue Add = DAG.getNode(Opc, dl, MVT::f80, Fild, Fudge);
22493   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
22494                      DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
22495 }
22496 
22497 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
22498 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
22499 // just return an SDValue().
22500 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
22501 // to i16, i32 or i64, and we lower it to a legal sequence and return the
22502 // result.
22503 SDValue
22504 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
22505                                    bool IsSigned, SDValue &Chain) const {
22506   bool IsStrict = Op->isStrictFPOpcode();
22507   SDLoc DL(Op);
22508 
22509   EVT DstTy = Op.getValueType();
22510   SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
22511   EVT TheVT = Value.getValueType();
22512   auto PtrVT = getPointerTy(DAG.getDataLayout());
22513 
22514   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
22515     // f16 must be promoted before using the lowering in this routine.
22516     // fp128 does not use this lowering.
22517     return SDValue();
22518   }
22519 
22520   // If using FIST to compute an unsigned i64, we'll need some fixup
22521   // to handle values above the maximum signed i64.  A FIST is always
22522   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
22523   bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
22524 
22525   // FIXME: This does not generate an invalid exception if the input does not
22526   // fit in i32. PR44019
22527   if (!IsSigned && DstTy != MVT::i64) {
22528     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
22529     // The low 32 bits of the fist result will have the correct uint32 result.
22530     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
22531     DstTy = MVT::i64;
22532   }
22533 
22534   assert(DstTy.getSimpleVT() <= MVT::i64 &&
22535          DstTy.getSimpleVT() >= MVT::i16 &&
22536          "Unknown FP_TO_INT to lower!");
22537 
22538   // We lower FP->int64 into FISTP64 followed by a load from a temporary
22539   // stack slot.
22540   MachineFunction &MF = DAG.getMachineFunction();
22541   unsigned MemSize = DstTy.getStoreSize();
22542   int SSFI =
22543       MF.getFrameInfo().CreateStackObject(MemSize, Align(MemSize), false);
22544   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
22545 
22546   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
22547 
22548   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
22549 
22550   if (UnsignedFixup) {
22551     //
22552     // Conversion to unsigned i64 is implemented with a select,
22553     // depending on whether the source value fits in the range
22554     // of a signed i64.  Let Thresh be the FP equivalent of
22555     // 0x8000000000000000ULL.
22556     //
22557     //  Adjust = (Value >= Thresh) ? 0x80000000 : 0;
22558     //  FltOfs = (Value >= Thresh) ? 0x80000000 : 0;
22559     //  FistSrc = (Value - FltOfs);
22560     //  Fist-to-mem64 FistSrc
22561     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
22562     //  to XOR'ing the high 32 bits with Adjust.
22563     //
22564     // Being a power of 2, Thresh is exactly representable in all FP formats.
22565     // For X87 we'd like to use the smallest FP type for this constant, but
22566     // for DAG type consistency we have to match the FP operand type.
22567 
22568     APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
22569     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
22570     bool LosesInfo = false;
22571     if (TheVT == MVT::f64)
22572       // The rounding mode is irrelevant as the conversion should be exact.
22573       Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
22574                               &LosesInfo);
22575     else if (TheVT == MVT::f80)
22576       Status = Thresh.convert(APFloat::x87DoubleExtended(),
22577                               APFloat::rmNearestTiesToEven, &LosesInfo);
22578 
22579     assert(Status == APFloat::opOK && !LosesInfo &&
22580            "FP conversion should have been exact");
22581 
22582     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
22583 
22584     EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
22585                                    *DAG.getContext(), TheVT);
22586     SDValue Cmp;
22587     if (IsStrict) {
22588       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE, Chain,
22589                          /*IsSignaling*/ true);
22590       Chain = Cmp.getValue(1);
22591     } else {
22592       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE);
22593     }
22594 
22595     // Our preferred lowering of
22596     //
22597     // (Value >= Thresh) ? 0x8000000000000000ULL : 0
22598     //
22599     // is
22600     //
22601     // (Value >= Thresh) << 63
22602     //
22603     // but since we can get here after LegalOperations, DAGCombine might do the
22604     // wrong thing if we create a select. So, directly create the preferred
22605     // version.
22606     SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Cmp);
22607     SDValue Const63 = DAG.getConstant(63, DL, MVT::i8);
22608     Adjust = DAG.getNode(ISD::SHL, DL, MVT::i64, Zext, Const63);
22609 
22610     SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp, ThreshVal,
22611                                    DAG.getConstantFP(0.0, DL, TheVT));
22612 
22613     if (IsStrict) {
22614       Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
22615                           { Chain, Value, FltOfs });
22616       Chain = Value.getValue(1);
22617     } else
22618       Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
22619   }
22620 
22621   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
22622 
22623   // FIXME This causes a redundant load/store if the SSE-class value is already
22624   // in memory, such as if it is on the callstack.
22625   if (isScalarFPTypeInSSEReg(TheVT)) {
22626     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
22627     Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
22628     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
22629     SDValue Ops[] = { Chain, StackSlot };
22630 
22631     unsigned FLDSize = TheVT.getStoreSize();
22632     assert(FLDSize <= MemSize && "Stack slot not big enough");
22633     MachineMemOperand *MMO = MF.getMachineMemOperand(
22634         MPI, MachineMemOperand::MOLoad, FLDSize, Align(FLDSize));
22635     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
22636     Chain = Value.getValue(1);
22637   }
22638 
22639   // Build the FP_TO_INT*_IN_MEM
22640   MachineMemOperand *MMO = MF.getMachineMemOperand(
22641       MPI, MachineMemOperand::MOStore, MemSize, Align(MemSize));
22642   SDValue Ops[] = { Chain, Value, StackSlot };
22643   SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
22644                                          DAG.getVTList(MVT::Other),
22645                                          Ops, DstTy, MMO);
22646 
22647   SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
22648   Chain = Res.getValue(1);
22649 
22650   // If we need an unsigned fixup, XOR the result with adjust.
22651   if (UnsignedFixup)
22652     Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
22653 
22654   return Res;
22655 }
22656 
22657 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
22658                               const X86Subtarget &Subtarget) {
22659   MVT VT = Op.getSimpleValueType();
22660   SDValue In = Op.getOperand(0);
22661   MVT InVT = In.getSimpleValueType();
22662   SDLoc dl(Op);
22663   unsigned Opc = Op.getOpcode();
22664 
22665   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
22666   assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&
22667          "Unexpected extension opcode");
22668   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
22669          "Expected same number of elements");
22670   assert((VT.getVectorElementType() == MVT::i16 ||
22671           VT.getVectorElementType() == MVT::i32 ||
22672           VT.getVectorElementType() == MVT::i64) &&
22673          "Unexpected element type");
22674   assert((InVT.getVectorElementType() == MVT::i8 ||
22675           InVT.getVectorElementType() == MVT::i16 ||
22676           InVT.getVectorElementType() == MVT::i32) &&
22677          "Unexpected element type");
22678 
22679   unsigned ExtendInVecOpc = DAG.getOpcode_EXTEND_VECTOR_INREG(Opc);
22680 
22681   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
22682     assert(InVT == MVT::v32i8 && "Unexpected VT!");
22683     return splitVectorIntUnary(Op, DAG);
22684   }
22685 
22686   if (Subtarget.hasInt256())
22687     return Op;
22688 
22689   // Optimize vectors in AVX mode:
22690   //
22691   //   v8i16 -> v8i32
22692   //   Use vpmovzwd for 4 lower elements  v8i16 -> v4i32.
22693   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
22694   //   Concat upper and lower parts.
22695   //
22696   //   v4i32 -> v4i64
22697   //   Use vpmovzdq for 4 lower elements  v4i32 -> v2i64.
22698   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
22699   //   Concat upper and lower parts.
22700   //
22701   MVT HalfVT = VT.getHalfNumVectorElementsVT();
22702   SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
22703 
22704   // Short-circuit if we can determine that each 128-bit half is the same value.
22705   // Otherwise, this is difficult to match and optimize.
22706   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
22707     if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
22708       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
22709 
22710   SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
22711   SDValue Undef = DAG.getUNDEF(InVT);
22712   bool NeedZero = Opc == ISD::ZERO_EXTEND;
22713   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
22714   OpHi = DAG.getBitcast(HalfVT, OpHi);
22715 
22716   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
22717 }
22718 
22719 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
22720 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
22721                                    const SDLoc &dl, SelectionDAG &DAG) {
22722   assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
22723   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
22724                            DAG.getIntPtrConstant(0, dl));
22725   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
22726                            DAG.getIntPtrConstant(8, dl));
22727   Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
22728   Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
22729   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
22730   return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
22731 }
22732 
22733 static  SDValue LowerZERO_EXTEND_Mask(SDValue Op,
22734                                       const X86Subtarget &Subtarget,
22735                                       SelectionDAG &DAG) {
22736   MVT VT = Op->getSimpleValueType(0);
22737   SDValue In = Op->getOperand(0);
22738   MVT InVT = In.getSimpleValueType();
22739   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
22740   SDLoc DL(Op);
22741   unsigned NumElts = VT.getVectorNumElements();
22742 
22743   // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
22744   // avoids a constant pool load.
22745   if (VT.getVectorElementType() != MVT::i8) {
22746     SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
22747     return DAG.getNode(ISD::SRL, DL, VT, Extend,
22748                        DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
22749   }
22750 
22751   // Extend VT if BWI is not supported.
22752   MVT ExtVT = VT;
22753   if (!Subtarget.hasBWI()) {
22754     // If v16i32 is to be avoided, we'll need to split and concatenate.
22755     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
22756       return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
22757 
22758     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
22759   }
22760 
22761   // Widen to 512-bits if VLX is not supported.
22762   MVT WideVT = ExtVT;
22763   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
22764     NumElts *= 512 / ExtVT.getSizeInBits();
22765     InVT = MVT::getVectorVT(MVT::i1, NumElts);
22766     In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
22767                      In, DAG.getIntPtrConstant(0, DL));
22768     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
22769                               NumElts);
22770   }
22771 
22772   SDValue One = DAG.getConstant(1, DL, WideVT);
22773   SDValue Zero = DAG.getConstant(0, DL, WideVT);
22774 
22775   SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
22776 
22777   // Truncate if we had to extend above.
22778   if (VT != ExtVT) {
22779     WideVT = MVT::getVectorVT(MVT::i8, NumElts);
22780     SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
22781   }
22782 
22783   // Extract back to 128/256-bit if we widened.
22784   if (WideVT != VT)
22785     SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
22786                               DAG.getIntPtrConstant(0, DL));
22787 
22788   return SelectedVal;
22789 }
22790 
22791 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
22792                                 SelectionDAG &DAG) {
22793   SDValue In = Op.getOperand(0);
22794   MVT SVT = In.getSimpleValueType();
22795 
22796   if (SVT.getVectorElementType() == MVT::i1)
22797     return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
22798 
22799   assert(Subtarget.hasAVX() && "Expected AVX support");
22800   return LowerAVXExtend(Op, DAG, Subtarget);
22801 }
22802 
22803 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
22804 /// It makes use of the fact that vectors with enough leading sign/zero bits
22805 /// prevent the PACKSS/PACKUS from saturating the results.
22806 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
22807 /// within each 128-bit lane.
22808 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
22809                                       const SDLoc &DL, SelectionDAG &DAG,
22810                                       const X86Subtarget &Subtarget) {
22811   assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
22812          "Unexpected PACK opcode");
22813   assert(DstVT.isVector() && "VT not a vector?");
22814 
22815   // Requires SSE2 for PACKSS (SSE41 PACKUSDW is handled below).
22816   if (!Subtarget.hasSSE2())
22817     return SDValue();
22818 
22819   EVT SrcVT = In.getValueType();
22820 
22821   // No truncation required, we might get here due to recursive calls.
22822   if (SrcVT == DstVT)
22823     return In;
22824 
22825   // We only support vector truncation to 64bits or greater from a
22826   // 128bits or greater source.
22827   unsigned DstSizeInBits = DstVT.getSizeInBits();
22828   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
22829   if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
22830     return SDValue();
22831 
22832   unsigned NumElems = SrcVT.getVectorNumElements();
22833   if (!isPowerOf2_32(NumElems))
22834     return SDValue();
22835 
22836   LLVMContext &Ctx = *DAG.getContext();
22837   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
22838   assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
22839 
22840   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
22841 
22842   // Pack to the largest type possible:
22843   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
22844   EVT InVT = MVT::i16, OutVT = MVT::i8;
22845   if (SrcVT.getScalarSizeInBits() > 16 &&
22846       (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
22847     InVT = MVT::i32;
22848     OutVT = MVT::i16;
22849   }
22850 
22851   // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
22852   if (SrcVT.is128BitVector()) {
22853     InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
22854     OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
22855     In = DAG.getBitcast(InVT, In);
22856     SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, DAG.getUNDEF(InVT));
22857     Res = extractSubVector(Res, 0, DAG, DL, 64);
22858     return DAG.getBitcast(DstVT, Res);
22859   }
22860 
22861   // Split lower/upper subvectors.
22862   SDValue Lo, Hi;
22863   std::tie(Lo, Hi) = splitVector(In, DAG, DL);
22864 
22865   unsigned SubSizeInBits = SrcSizeInBits / 2;
22866   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
22867   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
22868 
22869   // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
22870   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
22871     Lo = DAG.getBitcast(InVT, Lo);
22872     Hi = DAG.getBitcast(InVT, Hi);
22873     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
22874     return DAG.getBitcast(DstVT, Res);
22875   }
22876 
22877   // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
22878   // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
22879   if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
22880     Lo = DAG.getBitcast(InVT, Lo);
22881     Hi = DAG.getBitcast(InVT, Hi);
22882     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
22883 
22884     // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
22885     // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
22886     // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
22887     SmallVector<int, 64> Mask;
22888     int Scale = 64 / OutVT.getScalarSizeInBits();
22889     narrowShuffleMaskElts(Scale, { 0, 2, 1, 3 }, Mask);
22890     Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
22891 
22892     if (DstVT.is256BitVector())
22893       return DAG.getBitcast(DstVT, Res);
22894 
22895     // If 512bit -> 128bit truncate another stage.
22896     EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
22897     Res = DAG.getBitcast(PackedVT, Res);
22898     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
22899   }
22900 
22901   // Recursively pack lower/upper subvectors, concat result and pack again.
22902   assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
22903 
22904   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
22905   if (PackedVT.is128BitVector()) {
22906     // Avoid CONCAT_VECTORS on sub-128bit nodes as these can fail after
22907     // type legalization.
22908     SDValue Res =
22909         truncateVectorWithPACK(Opcode, PackedVT, In, DL, DAG, Subtarget);
22910     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
22911   }
22912 
22913   EVT HalfPackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
22914   Lo = truncateVectorWithPACK(Opcode, HalfPackedVT, Lo, DL, DAG, Subtarget);
22915   Hi = truncateVectorWithPACK(Opcode, HalfPackedVT, Hi, DL, DAG, Subtarget);
22916   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
22917   return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
22918 }
22919 
22920 /// Truncate using ISD::AND mask and X86ISD::PACKUS.
22921 /// e.g. trunc <8 x i32> X to <8 x i16> -->
22922 /// MaskX = X & 0xffff (clear high bits to prevent saturation)
22923 /// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
22924 static SDValue truncateVectorWithPACKUS(EVT DstVT, SDValue In, const SDLoc &DL,
22925                                         const X86Subtarget &Subtarget,
22926                                         SelectionDAG &DAG) {
22927   EVT SrcVT = In.getValueType();
22928   APInt Mask = APInt::getLowBitsSet(SrcVT.getScalarSizeInBits(),
22929                                     DstVT.getScalarSizeInBits());
22930   In = DAG.getNode(ISD::AND, DL, SrcVT, In, DAG.getConstant(Mask, DL, SrcVT));
22931   return truncateVectorWithPACK(X86ISD::PACKUS, DstVT, In, DL, DAG, Subtarget);
22932 }
22933 
22934 /// Truncate using inreg sign extension and X86ISD::PACKSS.
22935 static SDValue truncateVectorWithPACKSS(EVT DstVT, SDValue In, const SDLoc &DL,
22936                                         const X86Subtarget &Subtarget,
22937                                         SelectionDAG &DAG) {
22938   EVT SrcVT = In.getValueType();
22939   In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, SrcVT, In,
22940                    DAG.getValueType(DstVT));
22941   return truncateVectorWithPACK(X86ISD::PACKSS, DstVT, In, DL, DAG, Subtarget);
22942 }
22943 
22944 /// This function lowers a vector truncation of 'extended sign-bits' or
22945 /// 'extended zero-bits' values.
22946 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
22947 static SDValue LowerTruncateVecPackWithSignBits(MVT DstVT, SDValue In,
22948                                                 const SDLoc &DL,
22949                                                 const X86Subtarget &Subtarget,
22950                                                 SelectionDAG &DAG) {
22951   MVT SrcVT = In.getSimpleValueType();
22952   MVT DstSVT = DstVT.getVectorElementType();
22953   MVT SrcSVT = SrcVT.getVectorElementType();
22954   if (!((SrcSVT == MVT::i16 || SrcSVT == MVT::i32 || SrcSVT == MVT::i64) &&
22955         (DstSVT == MVT::i8 || DstSVT == MVT::i16 || DstSVT == MVT::i32)))
22956     return SDValue();
22957 
22958   // Don't lower with PACK nodes on AVX512 targets if we'd need more than one.
22959   if (Subtarget.hasAVX512() &&
22960       SrcSVT.getSizeInBits() > (DstSVT.getSizeInBits() * 2))
22961     return SDValue();
22962 
22963   // Prefer to lower v4i64 -> v4i32 as a shuffle unless we can cheaply
22964   // split this for packing.
22965   if (SrcVT == MVT::v4i64 && DstVT == MVT::v4i32 &&
22966       !isFreeToSplitVector(In.getNode(), DAG) &&
22967       (!Subtarget.hasInt256() || DAG.ComputeNumSignBits(In) != 64))
22968     return SDValue();
22969 
22970   // If the upper half of the source is undef, then attempt to split and
22971   // only truncate the lower half.
22972   if (DstVT.getSizeInBits() >= 128) {
22973     SmallVector<SDValue> LowerOps;
22974     if (isUpperSubvectorUndef(In, LowerOps, DAG)) {
22975       MVT DstHalfVT = DstVT.getHalfNumVectorElementsVT();
22976       MVT SrcHalfVT = SrcVT.getHalfNumVectorElementsVT();
22977       SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcHalfVT, LowerOps);
22978       if (SDValue Res = LowerTruncateVecPackWithSignBits(DstHalfVT, Lo, DL,
22979                                                          Subtarget, DAG))
22980         return widenSubVector(Res, false, Subtarget, DAG, DL,
22981                               DstVT.getSizeInBits());
22982     }
22983   }
22984 
22985   unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
22986   unsigned NumPackedSignBits = std::min<unsigned>(DstSVT.getSizeInBits(), 16);
22987   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
22988 
22989   // Truncate with PACKUS if we are truncating a vector with leading zero
22990   // bits that extend all the way to the packed/truncated value. Pre-SSE41
22991   // we can only use PACKUSWB.
22992   KnownBits Known = DAG.computeKnownBits(In);
22993   if ((NumSrcEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
22994     if (SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, DstVT, In, DL, DAG,
22995                                            Subtarget))
22996       return V;
22997 
22998   // Truncate with PACKSS if we are truncating a vector with sign-bits
22999   // that extend all the way to the packed/truncated value.
23000   if ((NumSrcEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
23001     if (SDValue V = truncateVectorWithPACK(X86ISD::PACKSS, DstVT, In, DL, DAG,
23002                                            Subtarget))
23003       return V;
23004 
23005   return SDValue();
23006 }
23007 
23008 /// This function lowers a vector truncation from vXi32/vXi64 to vXi8/vXi16 into
23009 /// X86ISD::PACKUS/X86ISD::PACKSS operations.
23010 static SDValue LowerTruncateVecPack(MVT DstVT, SDValue In, const SDLoc &DL,
23011                                     const X86Subtarget &Subtarget,
23012                                     SelectionDAG &DAG) {
23013   MVT SrcVT = In.getSimpleValueType();
23014   MVT DstSVT = DstVT.getVectorElementType();
23015   MVT SrcSVT = SrcVT.getVectorElementType();
23016   unsigned NumElems = DstVT.getVectorNumElements();
23017   if (!((SrcSVT == MVT::i16 || SrcSVT == MVT::i32 || SrcSVT == MVT::i64) &&
23018         (DstSVT == MVT::i8 || DstSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
23019         NumElems >= 8))
23020     return SDValue();
23021 
23022   // SSSE3's pshufb results in less instructions in the cases below.
23023   if (Subtarget.hasSSSE3() && NumElems == 8) {
23024     if (SrcSVT == MVT::i16)
23025       return SDValue();
23026     if (SrcSVT == MVT::i32 && (DstSVT == MVT::i8 || !Subtarget.hasSSE41()))
23027       return SDValue();
23028   }
23029 
23030   // If the upper half of the source is undef, then attempt to split and
23031   // only truncate the lower half.
23032   if (DstVT.getSizeInBits() >= 128) {
23033     SmallVector<SDValue> LowerOps;
23034     if (isUpperSubvectorUndef(In, LowerOps, DAG)) {
23035       MVT DstHalfVT = DstVT.getHalfNumVectorElementsVT();
23036       MVT SrcHalfVT = SrcVT.getHalfNumVectorElementsVT();
23037       SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcHalfVT, LowerOps);
23038       if (SDValue Res = LowerTruncateVecPack(DstHalfVT, Lo, DL, Subtarget, DAG))
23039         return widenSubVector(Res, false, Subtarget, DAG, DL,
23040                               DstVT.getSizeInBits());
23041     }
23042   }
23043 
23044   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
23045   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
23046   // truncate 2 x v4i32 to v8i16.
23047   if (Subtarget.hasSSE41() || DstSVT == MVT::i8)
23048     return truncateVectorWithPACKUS(DstVT, In, DL, Subtarget, DAG);
23049 
23050   if (SrcSVT == MVT::i16 || SrcSVT == MVT::i32)
23051     return truncateVectorWithPACKSS(DstVT, In, DL, Subtarget, DAG);
23052 
23053   // Special case vXi64 -> vXi16, shuffle to vXi32 and then use PACKSS.
23054   if (DstSVT == MVT::i16 && SrcSVT == MVT::i64) {
23055     MVT TruncVT = MVT::getVectorVT(MVT::i32, NumElems);
23056     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, In);
23057     return truncateVectorWithPACKSS(DstVT, Trunc, DL, Subtarget, DAG);
23058   }
23059 
23060   return SDValue();
23061 }
23062 
23063 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
23064                                   const X86Subtarget &Subtarget) {
23065 
23066   SDLoc DL(Op);
23067   MVT VT = Op.getSimpleValueType();
23068   SDValue In = Op.getOperand(0);
23069   MVT InVT = In.getSimpleValueType();
23070 
23071   assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
23072 
23073   // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
23074   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
23075   if (InVT.getScalarSizeInBits() <= 16) {
23076     if (Subtarget.hasBWI()) {
23077       // legal, will go to VPMOVB2M, VPMOVW2M
23078       if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
23079         // We need to shift to get the lsb into sign position.
23080         // Shift packed bytes not supported natively, bitcast to word
23081         MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
23082         In = DAG.getNode(ISD::SHL, DL, ExtVT,
23083                          DAG.getBitcast(ExtVT, In),
23084                          DAG.getConstant(ShiftInx, DL, ExtVT));
23085         In = DAG.getBitcast(InVT, In);
23086       }
23087       return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
23088                           In, ISD::SETGT);
23089     }
23090     // Use TESTD/Q, extended vector to packed dword/qword.
23091     assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
23092            "Unexpected vector type.");
23093     unsigned NumElts = InVT.getVectorNumElements();
23094     assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
23095     // We need to change to a wider element type that we have support for.
23096     // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
23097     // For 16 element vectors we extend to v16i32 unless we are explicitly
23098     // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
23099     // we need to split into two 8 element vectors which we can extend to v8i32,
23100     // truncate and concat the results. There's an additional complication if
23101     // the original type is v16i8. In that case we can't split the v16i8
23102     // directly, so we need to shuffle high elements to low and use
23103     // sign_extend_vector_inreg.
23104     if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
23105       SDValue Lo, Hi;
23106       if (InVT == MVT::v16i8) {
23107         Lo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, In);
23108         Hi = DAG.getVectorShuffle(
23109             InVT, DL, In, In,
23110             {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
23111         Hi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, Hi);
23112       } else {
23113         assert(InVT == MVT::v16i16 && "Unexpected VT!");
23114         Lo = extract128BitVector(In, 0, DAG, DL);
23115         Hi = extract128BitVector(In, 8, DAG, DL);
23116       }
23117       // We're split now, just emit two truncates and a concat. The two
23118       // truncates will trigger legalization to come back to this function.
23119       Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
23120       Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
23121       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
23122     }
23123     // We either have 8 elements or we're allowed to use 512-bit vectors.
23124     // If we have VLX, we want to use the narrowest vector that can get the
23125     // job done so we use vXi32.
23126     MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
23127     MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
23128     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
23129     InVT = ExtVT;
23130     ShiftInx = InVT.getScalarSizeInBits() - 1;
23131   }
23132 
23133   if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
23134     // We need to shift to get the lsb into sign position.
23135     In = DAG.getNode(ISD::SHL, DL, InVT, In,
23136                      DAG.getConstant(ShiftInx, DL, InVT));
23137   }
23138   // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
23139   if (Subtarget.hasDQI())
23140     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
23141   return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
23142 }
23143 
23144 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
23145   SDLoc DL(Op);
23146   MVT VT = Op.getSimpleValueType();
23147   SDValue In = Op.getOperand(0);
23148   MVT InVT = In.getSimpleValueType();
23149   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
23150          "Invalid TRUNCATE operation");
23151 
23152   // If we're called by the type legalizer, handle a few cases.
23153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23154   if (!TLI.isTypeLegal(InVT)) {
23155     if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
23156         VT.is128BitVector() && Subtarget.hasAVX512()) {
23157       assert((InVT == MVT::v16i64 || Subtarget.hasVLX()) &&
23158              "Unexpected subtarget!");
23159       // The default behavior is to truncate one step, concatenate, and then
23160       // truncate the remainder. We'd rather produce two 64-bit results and
23161       // concatenate those.
23162       SDValue Lo, Hi;
23163       std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
23164 
23165       EVT LoVT, HiVT;
23166       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
23167 
23168       Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
23169       Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
23170       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
23171     }
23172 
23173     // Pre-AVX512 (or prefer-256bit) see if we can make use of PACKSS/PACKUS.
23174     if (!Subtarget.hasAVX512() ||
23175         (InVT.is512BitVector() && VT.is256BitVector()))
23176       if (SDValue SignPack =
23177               LowerTruncateVecPackWithSignBits(VT, In, DL, Subtarget, DAG))
23178         return SignPack;
23179 
23180     // Pre-AVX512 see if we can make use of PACKSS/PACKUS.
23181     if (!Subtarget.hasAVX512())
23182       return LowerTruncateVecPack(VT, In, DL, Subtarget, DAG);
23183 
23184     // Otherwise let default legalization handle it.
23185     return SDValue();
23186   }
23187 
23188   if (VT.getVectorElementType() == MVT::i1)
23189     return LowerTruncateVecI1(Op, DAG, Subtarget);
23190 
23191   // Attempt to truncate with PACKUS/PACKSS even on AVX512 if we'd have to
23192   // concat from subvectors to use VPTRUNC etc.
23193   if (!Subtarget.hasAVX512() || isFreeToSplitVector(In.getNode(), DAG))
23194     if (SDValue SignPack =
23195             LowerTruncateVecPackWithSignBits(VT, In, DL, Subtarget, DAG))
23196       return SignPack;
23197 
23198   // vpmovqb/w/d, vpmovdb/w, vpmovwb
23199   if (Subtarget.hasAVX512()) {
23200     if (InVT == MVT::v32i16 && !Subtarget.hasBWI()) {
23201       assert(VT == MVT::v32i8 && "Unexpected VT!");
23202       return splitVectorIntUnary(Op, DAG);
23203     }
23204 
23205     // word to byte only under BWI. Otherwise we have to promoted to v16i32
23206     // and then truncate that. But we should only do that if we haven't been
23207     // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
23208     // handled by isel patterns.
23209     if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
23210         Subtarget.canExtendTo512DQ())
23211       return Op;
23212   }
23213 
23214   // Handle truncation of V256 to V128 using shuffles.
23215   assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
23216 
23217   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
23218     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
23219     if (Subtarget.hasInt256()) {
23220       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
23221       In = DAG.getBitcast(MVT::v8i32, In);
23222       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
23223       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
23224                          DAG.getIntPtrConstant(0, DL));
23225     }
23226 
23227     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
23228                                DAG.getIntPtrConstant(0, DL));
23229     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
23230                                DAG.getIntPtrConstant(2, DL));
23231     static const int ShufMask[] = {0, 2, 4, 6};
23232     return DAG.getVectorShuffle(VT, DL, DAG.getBitcast(MVT::v4i32, OpLo),
23233                                 DAG.getBitcast(MVT::v4i32, OpHi), ShufMask);
23234   }
23235 
23236   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
23237     // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
23238     if (Subtarget.hasInt256()) {
23239       // The PSHUFB mask:
23240       static const int ShufMask1[] = { 0,  1,  4,  5,  8,  9, 12, 13,
23241                                       -1, -1, -1, -1, -1, -1, -1, -1,
23242                                       16, 17, 20, 21, 24, 25, 28, 29,
23243                                       -1, -1, -1, -1, -1, -1, -1, -1 };
23244       In = DAG.getBitcast(MVT::v32i8, In);
23245       In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
23246       In = DAG.getBitcast(MVT::v4i64, In);
23247 
23248       static const int ShufMask2[] = {0, 2, -1, -1};
23249       In = DAG.getVectorShuffle(MVT::v4i64, DL, In, In, ShufMask2);
23250       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
23251                        DAG.getIntPtrConstant(0, DL));
23252       return DAG.getBitcast(MVT::v8i16, In);
23253     }
23254 
23255     return Subtarget.hasSSE41()
23256                ? truncateVectorWithPACKUS(VT, In, DL, Subtarget, DAG)
23257                : truncateVectorWithPACKSS(VT, In, DL, Subtarget, DAG);
23258   }
23259 
23260   if (VT == MVT::v16i8 && InVT == MVT::v16i16)
23261     return truncateVectorWithPACKUS(VT, In, DL, Subtarget, DAG);
23262 
23263   llvm_unreachable("All 256->128 cases should have been handled above!");
23264 }
23265 
23266 // We can leverage the specific way the "cvttps2dq/cvttpd2dq" instruction
23267 // behaves on out of range inputs to generate optimized conversions.
23268 static SDValue expandFP_TO_UINT_SSE(MVT VT, SDValue Src, const SDLoc &dl,
23269                                     SelectionDAG &DAG,
23270                                     const X86Subtarget &Subtarget) {
23271   MVT SrcVT = Src.getSimpleValueType();
23272   unsigned DstBits = VT.getScalarSizeInBits();
23273   assert(DstBits == 32 && "expandFP_TO_UINT_SSE - only vXi32 supported");
23274 
23275   // Calculate the converted result for values in the range 0 to
23276   // 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
23277   SDValue Small = DAG.getNode(X86ISD::CVTTP2SI, dl, VT, Src);
23278   SDValue Big =
23279       DAG.getNode(X86ISD::CVTTP2SI, dl, VT,
23280                   DAG.getNode(ISD::FSUB, dl, SrcVT, Src,
23281                               DAG.getConstantFP(2147483648.0f, dl, SrcVT)));
23282 
23283   // The "CVTTP2SI" instruction conveniently sets the sign bit if
23284   // and only if the value was out of range. So we can use that
23285   // as our indicator that we rather use "Big" instead of "Small".
23286   //
23287   // Use "Small" if "IsOverflown" has all bits cleared
23288   // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
23289 
23290   // AVX1 can't use the signsplat masking for 256-bit vectors - we have to
23291   // use the slightly slower blendv select instead.
23292   if (VT == MVT::v8i32 && !Subtarget.hasAVX2()) {
23293     SDValue Overflow = DAG.getNode(ISD::OR, dl, VT, Small, Big);
23294     return DAG.getNode(X86ISD::BLENDV, dl, VT, Small, Overflow, Small);
23295   }
23296 
23297   SDValue IsOverflown =
23298       DAG.getNode(X86ISD::VSRAI, dl, VT, Small,
23299                   DAG.getTargetConstant(DstBits - 1, dl, MVT::i8));
23300   return DAG.getNode(ISD::OR, dl, VT, Small,
23301                      DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
23302 }
23303 
23304 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
23305   bool IsStrict = Op->isStrictFPOpcode();
23306   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
23307                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
23308   MVT VT = Op->getSimpleValueType(0);
23309   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
23310   SDValue Chain = IsStrict ? Op->getOperand(0) : SDValue();
23311   MVT SrcVT = Src.getSimpleValueType();
23312   SDLoc dl(Op);
23313 
23314   SDValue Res;
23315   if (isSoftF16(SrcVT, Subtarget)) {
23316     MVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
23317     if (IsStrict)
23318       return DAG.getNode(Op.getOpcode(), dl, {VT, MVT::Other},
23319                          {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
23320                                              {NVT, MVT::Other}, {Chain, Src})});
23321     return DAG.getNode(Op.getOpcode(), dl, VT,
23322                        DAG.getNode(ISD::FP_EXTEND, dl, NVT, Src));
23323   } else if (isTypeLegal(SrcVT) && isLegalConversion(VT, IsSigned, Subtarget)) {
23324     return Op;
23325   }
23326 
23327   if (VT.isVector()) {
23328     if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
23329       MVT ResVT = MVT::v4i32;
23330       MVT TruncVT = MVT::v4i1;
23331       unsigned Opc;
23332       if (IsStrict)
23333         Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
23334       else
23335         Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
23336 
23337       if (!IsSigned && !Subtarget.hasVLX()) {
23338         assert(Subtarget.useAVX512Regs() && "Unexpected features!");
23339         // Widen to 512-bits.
23340         ResVT = MVT::v8i32;
23341         TruncVT = MVT::v8i1;
23342         Opc = Op.getOpcode();
23343         // Need to concat with zero vector for strict fp to avoid spurious
23344         // exceptions.
23345         // TODO: Should we just do this for non-strict as well?
23346         SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
23347                                : DAG.getUNDEF(MVT::v8f64);
23348         Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
23349                           DAG.getIntPtrConstant(0, dl));
23350       }
23351       if (IsStrict) {
23352         Res = DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Chain, Src});
23353         Chain = Res.getValue(1);
23354       } else {
23355         Res = DAG.getNode(Opc, dl, ResVT, Src);
23356       }
23357 
23358       Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
23359       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
23360                         DAG.getIntPtrConstant(0, dl));
23361       if (IsStrict)
23362         return DAG.getMergeValues({Res, Chain}, dl);
23363       return Res;
23364     }
23365 
23366     if (Subtarget.hasFP16() && SrcVT.getVectorElementType() == MVT::f16) {
23367       if (VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16)
23368         return Op;
23369 
23370       MVT ResVT = VT;
23371       MVT EleVT = VT.getVectorElementType();
23372       if (EleVT != MVT::i64)
23373         ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
23374 
23375       if (SrcVT != MVT::v8f16) {
23376         SDValue Tmp =
23377             IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
23378         SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
23379         Ops[0] = Src;
23380         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
23381       }
23382 
23383       if (IsStrict) {
23384         Res = DAG.getNode(IsSigned ? X86ISD::STRICT_CVTTP2SI
23385                                    : X86ISD::STRICT_CVTTP2UI,
23386                           dl, {ResVT, MVT::Other}, {Chain, Src});
23387         Chain = Res.getValue(1);
23388       } else {
23389         Res = DAG.getNode(IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI, dl,
23390                           ResVT, Src);
23391       }
23392 
23393       // TODO: Need to add exception check code for strict FP.
23394       if (EleVT.getSizeInBits() < 16) {
23395         ResVT = MVT::getVectorVT(EleVT, 8);
23396         Res = DAG.getNode(ISD::TRUNCATE, dl, ResVT, Res);
23397       }
23398 
23399       if (ResVT != VT)
23400         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
23401                           DAG.getIntPtrConstant(0, dl));
23402 
23403       if (IsStrict)
23404         return DAG.getMergeValues({Res, Chain}, dl);
23405       return Res;
23406     }
23407 
23408     // v8f32/v16f32/v8f64->v8i16/v16i16 need to widen first.
23409     if (VT.getVectorElementType() == MVT::i16) {
23410       assert((SrcVT.getVectorElementType() == MVT::f32 ||
23411               SrcVT.getVectorElementType() == MVT::f64) &&
23412              "Expected f32/f64 vector!");
23413       MVT NVT = VT.changeVectorElementType(MVT::i32);
23414       if (IsStrict) {
23415         Res = DAG.getNode(IsSigned ? ISD::STRICT_FP_TO_SINT
23416                                    : ISD::STRICT_FP_TO_UINT,
23417                           dl, {NVT, MVT::Other}, {Chain, Src});
23418         Chain = Res.getValue(1);
23419       } else {
23420         Res = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl,
23421                           NVT, Src);
23422       }
23423 
23424       // TODO: Need to add exception check code for strict FP.
23425       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
23426 
23427       if (IsStrict)
23428         return DAG.getMergeValues({Res, Chain}, dl);
23429       return Res;
23430     }
23431 
23432     // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
23433     if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
23434       assert(!IsSigned && "Expected unsigned conversion!");
23435       assert(Subtarget.useAVX512Regs() && "Requires avx512f");
23436       return Op;
23437     }
23438 
23439     // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
23440     if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
23441         (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32) &&
23442         Subtarget.useAVX512Regs()) {
23443       assert(!IsSigned && "Expected unsigned conversion!");
23444       assert(!Subtarget.hasVLX() && "Unexpected features!");
23445       MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
23446       MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
23447       // Need to concat with zero vector for strict fp to avoid spurious
23448       // exceptions.
23449       // TODO: Should we just do this for non-strict as well?
23450       SDValue Tmp =
23451           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
23452       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
23453                         DAG.getIntPtrConstant(0, dl));
23454 
23455       if (IsStrict) {
23456         Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
23457                           {Chain, Src});
23458         Chain = Res.getValue(1);
23459       } else {
23460         Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
23461       }
23462 
23463       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
23464                         DAG.getIntPtrConstant(0, dl));
23465 
23466       if (IsStrict)
23467         return DAG.getMergeValues({Res, Chain}, dl);
23468       return Res;
23469     }
23470 
23471     // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
23472     if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
23473         (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32) &&
23474         Subtarget.useAVX512Regs() && Subtarget.hasDQI()) {
23475       assert(!Subtarget.hasVLX() && "Unexpected features!");
23476       MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
23477       // Need to concat with zero vector for strict fp to avoid spurious
23478       // exceptions.
23479       // TODO: Should we just do this for non-strict as well?
23480       SDValue Tmp =
23481           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
23482       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
23483                         DAG.getIntPtrConstant(0, dl));
23484 
23485       if (IsStrict) {
23486         Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
23487                           {Chain, Src});
23488         Chain = Res.getValue(1);
23489       } else {
23490         Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
23491       }
23492 
23493       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
23494                         DAG.getIntPtrConstant(0, dl));
23495 
23496       if (IsStrict)
23497         return DAG.getMergeValues({Res, Chain}, dl);
23498       return Res;
23499     }
23500 
23501     if (VT == MVT::v2i64 && SrcVT == MVT::v2f32) {
23502       if (!Subtarget.hasVLX()) {
23503         // Non-strict nodes without VLX can we widened to v4f32->v4i64 by type
23504         // legalizer and then widened again by vector op legalization.
23505         if (!IsStrict)
23506           return SDValue();
23507 
23508         SDValue Zero = DAG.getConstantFP(0.0, dl, MVT::v2f32);
23509         SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f32,
23510                                   {Src, Zero, Zero, Zero});
23511         Tmp = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
23512                           {Chain, Tmp});
23513         SDValue Chain = Tmp.getValue(1);
23514         Tmp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Tmp,
23515                           DAG.getIntPtrConstant(0, dl));
23516         return DAG.getMergeValues({Tmp, Chain}, dl);
23517       }
23518 
23519       assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL");
23520       SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
23521                                 DAG.getUNDEF(MVT::v2f32));
23522       if (IsStrict) {
23523         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
23524                                 : X86ISD::STRICT_CVTTP2UI;
23525         return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
23526       }
23527       unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
23528       return DAG.getNode(Opc, dl, VT, Tmp);
23529     }
23530 
23531     // Generate optimized instructions for pre AVX512 unsigned conversions from
23532     // vXf32 to vXi32.
23533     if ((VT == MVT::v4i32 && SrcVT == MVT::v4f32) ||
23534         (VT == MVT::v4i32 && SrcVT == MVT::v4f64) ||
23535         (VT == MVT::v8i32 && SrcVT == MVT::v8f32)) {
23536       assert(!IsSigned && "Expected unsigned conversion!");
23537       return expandFP_TO_UINT_SSE(VT, Src, dl, DAG, Subtarget);
23538     }
23539 
23540     return SDValue();
23541   }
23542 
23543   assert(!VT.isVector());
23544 
23545   bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
23546 
23547   if (!IsSigned && UseSSEReg) {
23548     // Conversions from f32/f64 with AVX512 should be legal.
23549     if (Subtarget.hasAVX512())
23550       return Op;
23551 
23552     // We can leverage the specific way the "cvttss2si/cvttsd2si" instruction
23553     // behaves on out of range inputs to generate optimized conversions.
23554     if (!IsStrict && ((VT == MVT::i32 && !Subtarget.is64Bit()) ||
23555                       (VT == MVT::i64 && Subtarget.is64Bit()))) {
23556       unsigned DstBits = VT.getScalarSizeInBits();
23557       APInt UIntLimit = APInt::getSignMask(DstBits);
23558       SDValue FloatOffset = DAG.getNode(ISD::UINT_TO_FP, dl, SrcVT,
23559                                         DAG.getConstant(UIntLimit, dl, VT));
23560       MVT SrcVecVT = MVT::getVectorVT(SrcVT, 128 / SrcVT.getScalarSizeInBits());
23561 
23562       // Calculate the converted result for values in the range:
23563       // (i32) 0 to 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
23564       // (i64) 0 to 2^63-1 ("Small") and from 2^63 to 2^64-1 ("Big").
23565       SDValue Small =
23566           DAG.getNode(X86ISD::CVTTS2SI, dl, VT,
23567                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT, Src));
23568       SDValue Big = DAG.getNode(
23569           X86ISD::CVTTS2SI, dl, VT,
23570           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT,
23571                       DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FloatOffset)));
23572 
23573       // The "CVTTS2SI" instruction conveniently sets the sign bit if
23574       // and only if the value was out of range. So we can use that
23575       // as our indicator that we rather use "Big" instead of "Small".
23576       //
23577       // Use "Small" if "IsOverflown" has all bits cleared
23578       // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
23579       SDValue IsOverflown = DAG.getNode(
23580           ISD::SRA, dl, VT, Small, DAG.getConstant(DstBits - 1, dl, MVT::i8));
23581       return DAG.getNode(ISD::OR, dl, VT, Small,
23582                          DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
23583     }
23584 
23585     // Use default expansion for i64.
23586     if (VT == MVT::i64)
23587       return SDValue();
23588 
23589     assert(VT == MVT::i32 && "Unexpected VT!");
23590 
23591     // Promote i32 to i64 and use a signed operation on 64-bit targets.
23592     // FIXME: This does not generate an invalid exception if the input does not
23593     // fit in i32. PR44019
23594     if (Subtarget.is64Bit()) {
23595       if (IsStrict) {
23596         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i64, MVT::Other},
23597                           {Chain, Src});
23598         Chain = Res.getValue(1);
23599       } else
23600         Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
23601 
23602       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
23603       if (IsStrict)
23604         return DAG.getMergeValues({Res, Chain}, dl);
23605       return Res;
23606     }
23607 
23608     // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
23609     // use fisttp which will be handled later.
23610     if (!Subtarget.hasSSE3())
23611       return SDValue();
23612   }
23613 
23614   // Promote i16 to i32 if we can use a SSE operation or the type is f128.
23615   // FIXME: This does not generate an invalid exception if the input does not
23616   // fit in i16. PR44019
23617   if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
23618     assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!");
23619     if (IsStrict) {
23620       Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i32, MVT::Other},
23621                         {Chain, Src});
23622       Chain = Res.getValue(1);
23623     } else
23624       Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
23625 
23626     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
23627     if (IsStrict)
23628       return DAG.getMergeValues({Res, Chain}, dl);
23629     return Res;
23630   }
23631 
23632   // If this is a FP_TO_SINT using SSEReg we're done.
23633   if (UseSSEReg && IsSigned)
23634     return Op;
23635 
23636   // fp128 needs to use a libcall.
23637   if (SrcVT == MVT::f128) {
23638     RTLIB::Libcall LC;
23639     if (IsSigned)
23640       LC = RTLIB::getFPTOSINT(SrcVT, VT);
23641     else
23642       LC = RTLIB::getFPTOUINT(SrcVT, VT);
23643 
23644     MakeLibCallOptions CallOptions;
23645     std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, Src, CallOptions,
23646                                                   SDLoc(Op), Chain);
23647 
23648     if (IsStrict)
23649       return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
23650 
23651     return Tmp.first;
23652   }
23653 
23654   // Fall back to X87.
23655   if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
23656     if (IsStrict)
23657       return DAG.getMergeValues({V, Chain}, dl);
23658     return V;
23659   }
23660 
23661   llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.");
23662 }
23663 
23664 SDValue X86TargetLowering::LowerLRINT_LLRINT(SDValue Op,
23665                                              SelectionDAG &DAG) const {
23666   SDValue Src = Op.getOperand(0);
23667   MVT SrcVT = Src.getSimpleValueType();
23668 
23669   if (SrcVT == MVT::f16)
23670     return SDValue();
23671 
23672   // If the source is in an SSE register, the node is Legal.
23673   if (isScalarFPTypeInSSEReg(SrcVT))
23674     return Op;
23675 
23676   return LRINT_LLRINTHelper(Op.getNode(), DAG);
23677 }
23678 
23679 SDValue X86TargetLowering::LRINT_LLRINTHelper(SDNode *N,
23680                                               SelectionDAG &DAG) const {
23681   EVT DstVT = N->getValueType(0);
23682   SDValue Src = N->getOperand(0);
23683   EVT SrcVT = Src.getValueType();
23684 
23685   if (SrcVT != MVT::f32 && SrcVT != MVT::f64 && SrcVT != MVT::f80) {
23686     // f16 must be promoted before using the lowering in this routine.
23687     // fp128 does not use this lowering.
23688     return SDValue();
23689   }
23690 
23691   SDLoc DL(N);
23692   SDValue Chain = DAG.getEntryNode();
23693 
23694   bool UseSSE = isScalarFPTypeInSSEReg(SrcVT);
23695 
23696   // If we're converting from SSE, the stack slot needs to hold both types.
23697   // Otherwise it only needs to hold the DstVT.
23698   EVT OtherVT = UseSSE ? SrcVT : DstVT;
23699   SDValue StackPtr = DAG.CreateStackTemporary(DstVT, OtherVT);
23700   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
23701   MachinePointerInfo MPI =
23702       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
23703 
23704   if (UseSSE) {
23705     assert(DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!");
23706     Chain = DAG.getStore(Chain, DL, Src, StackPtr, MPI);
23707     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
23708     SDValue Ops[] = { Chain, StackPtr };
23709 
23710     Src = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, SrcVT, MPI,
23711                                   /*Align*/ std::nullopt,
23712                                   MachineMemOperand::MOLoad);
23713     Chain = Src.getValue(1);
23714   }
23715 
23716   SDValue StoreOps[] = { Chain, Src, StackPtr };
23717   Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, DL, DAG.getVTList(MVT::Other),
23718                                   StoreOps, DstVT, MPI, /*Align*/ std::nullopt,
23719                                   MachineMemOperand::MOStore);
23720 
23721   return DAG.getLoad(DstVT, DL, Chain, StackPtr, MPI);
23722 }
23723 
23724 SDValue
23725 X86TargetLowering::LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) const {
23726   // This is based on the TargetLowering::expandFP_TO_INT_SAT implementation,
23727   // but making use of X86 specifics to produce better instruction sequences.
23728   SDNode *Node = Op.getNode();
23729   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
23730   unsigned FpToIntOpcode = IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
23731   SDLoc dl(SDValue(Node, 0));
23732   SDValue Src = Node->getOperand(0);
23733 
23734   // There are three types involved here: SrcVT is the source floating point
23735   // type, DstVT is the type of the result, and TmpVT is the result of the
23736   // intermediate FP_TO_*INT operation we'll use (which may be a promotion of
23737   // DstVT).
23738   EVT SrcVT = Src.getValueType();
23739   EVT DstVT = Node->getValueType(0);
23740   EVT TmpVT = DstVT;
23741 
23742   // This code is only for floats and doubles. Fall back to generic code for
23743   // anything else.
23744   if (!isScalarFPTypeInSSEReg(SrcVT) || isSoftF16(SrcVT, Subtarget))
23745     return SDValue();
23746 
23747   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
23748   unsigned SatWidth = SatVT.getScalarSizeInBits();
23749   unsigned DstWidth = DstVT.getScalarSizeInBits();
23750   unsigned TmpWidth = TmpVT.getScalarSizeInBits();
23751   assert(SatWidth <= DstWidth && SatWidth <= TmpWidth &&
23752          "Expected saturation width smaller than result width");
23753 
23754   // Promote result of FP_TO_*INT to at least 32 bits.
23755   if (TmpWidth < 32) {
23756     TmpVT = MVT::i32;
23757     TmpWidth = 32;
23758   }
23759 
23760   // Promote conversions to unsigned 32-bit to 64-bit, because it will allow
23761   // us to use a native signed conversion instead.
23762   if (SatWidth == 32 && !IsSigned && Subtarget.is64Bit()) {
23763     TmpVT = MVT::i64;
23764     TmpWidth = 64;
23765   }
23766 
23767   // If the saturation width is smaller than the size of the temporary result,
23768   // we can always use signed conversion, which is native.
23769   if (SatWidth < TmpWidth)
23770     FpToIntOpcode = ISD::FP_TO_SINT;
23771 
23772   // Determine minimum and maximum integer values and their corresponding
23773   // floating-point values.
23774   APInt MinInt, MaxInt;
23775   if (IsSigned) {
23776     MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
23777     MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
23778   } else {
23779     MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
23780     MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
23781   }
23782 
23783   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
23784   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
23785 
23786   APFloat::opStatus MinStatus = MinFloat.convertFromAPInt(
23787     MinInt, IsSigned, APFloat::rmTowardZero);
23788   APFloat::opStatus MaxStatus = MaxFloat.convertFromAPInt(
23789     MaxInt, IsSigned, APFloat::rmTowardZero);
23790   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact)
23791                           && !(MaxStatus & APFloat::opStatus::opInexact);
23792 
23793   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
23794   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
23795 
23796   // If the integer bounds are exactly representable as floats, emit a
23797   // min+max+fptoi sequence. Otherwise use comparisons and selects.
23798   if (AreExactFloatBounds) {
23799     if (DstVT != TmpVT) {
23800       // Clamp by MinFloat from below. If Src is NaN, propagate NaN.
23801       SDValue MinClamped = DAG.getNode(
23802         X86ISD::FMAX, dl, SrcVT, MinFloatNode, Src);
23803       // Clamp by MaxFloat from above. If Src is NaN, propagate NaN.
23804       SDValue BothClamped = DAG.getNode(
23805         X86ISD::FMIN, dl, SrcVT, MaxFloatNode, MinClamped);
23806       // Convert clamped value to integer.
23807       SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, BothClamped);
23808 
23809       // NaN will become INDVAL, with the top bit set and the rest zero.
23810       // Truncation will discard the top bit, resulting in zero.
23811       return DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
23812     }
23813 
23814     // Clamp by MinFloat from below. If Src is NaN, the result is MinFloat.
23815     SDValue MinClamped = DAG.getNode(
23816       X86ISD::FMAX, dl, SrcVT, Src, MinFloatNode);
23817     // Clamp by MaxFloat from above. NaN cannot occur.
23818     SDValue BothClamped = DAG.getNode(
23819       X86ISD::FMINC, dl, SrcVT, MinClamped, MaxFloatNode);
23820     // Convert clamped value to integer.
23821     SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, DstVT, BothClamped);
23822 
23823     if (!IsSigned) {
23824       // In the unsigned case we're done, because we mapped NaN to MinFloat,
23825       // which is zero.
23826       return FpToInt;
23827     }
23828 
23829     // Otherwise, select zero if Src is NaN.
23830     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
23831     return DAG.getSelectCC(
23832       dl, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
23833   }
23834 
23835   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
23836   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
23837 
23838   // Result of direct conversion, which may be selected away.
23839   SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, Src);
23840 
23841   if (DstVT != TmpVT) {
23842     // NaN will become INDVAL, with the top bit set and the rest zero.
23843     // Truncation will discard the top bit, resulting in zero.
23844     FpToInt = DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
23845   }
23846 
23847   SDValue Select = FpToInt;
23848   // For signed conversions where we saturate to the same size as the
23849   // result type of the fptoi instructions, INDVAL coincides with integer
23850   // minimum, so we don't need to explicitly check it.
23851   if (!IsSigned || SatWidth != TmpVT.getScalarSizeInBits()) {
23852     // If Src ULT MinFloat, select MinInt. In particular, this also selects
23853     // MinInt if Src is NaN.
23854     Select = DAG.getSelectCC(
23855       dl, Src, MinFloatNode, MinIntNode, Select, ISD::CondCode::SETULT);
23856   }
23857 
23858   // If Src OGT MaxFloat, select MaxInt.
23859   Select = DAG.getSelectCC(
23860     dl, Src, MaxFloatNode, MaxIntNode, Select, ISD::CondCode::SETOGT);
23861 
23862   // In the unsigned case we are done, because we mapped NaN to MinInt, which
23863   // is already zero. The promoted case was already handled above.
23864   if (!IsSigned || DstVT != TmpVT) {
23865     return Select;
23866   }
23867 
23868   // Otherwise, select 0 if Src is NaN.
23869   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
23870   return DAG.getSelectCC(
23871     dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
23872 }
23873 
23874 SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
23875   bool IsStrict = Op->isStrictFPOpcode();
23876 
23877   SDLoc DL(Op);
23878   MVT VT = Op.getSimpleValueType();
23879   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
23880   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
23881   MVT SVT = In.getSimpleValueType();
23882 
23883   // Let f16->f80 get lowered to a libcall, except for darwin, where we should
23884   // lower it to an fp_extend via f32 (as only f16<>f32 libcalls are available)
23885   if (VT == MVT::f128 || (SVT == MVT::f16 && VT == MVT::f80 &&
23886                           !Subtarget.getTargetTriple().isOSDarwin()))
23887     return SDValue();
23888 
23889   if ((SVT == MVT::v8f16 && Subtarget.hasF16C()) ||
23890       (SVT == MVT::v16f16 && Subtarget.useAVX512Regs()))
23891     return Op;
23892 
23893   if (SVT == MVT::f16) {
23894     if (Subtarget.hasFP16())
23895       return Op;
23896 
23897     if (VT != MVT::f32) {
23898       if (IsStrict)
23899         return DAG.getNode(
23900             ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other},
23901             {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, DL,
23902                                 {MVT::f32, MVT::Other}, {Chain, In})});
23903 
23904       return DAG.getNode(ISD::FP_EXTEND, DL, VT,
23905                          DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, In));
23906     }
23907 
23908     if (!Subtarget.hasF16C()) {
23909       if (!Subtarget.getTargetTriple().isOSDarwin())
23910         return SDValue();
23911 
23912       assert(VT == MVT::f32 && SVT == MVT::f16 && "unexpected extend libcall");
23913 
23914       // Need a libcall, but ABI for f16 is soft-float on MacOS.
23915       TargetLowering::CallLoweringInfo CLI(DAG);
23916       Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
23917 
23918       In = DAG.getBitcast(MVT::i16, In);
23919       TargetLowering::ArgListTy Args;
23920       TargetLowering::ArgListEntry Entry;
23921       Entry.Node = In;
23922       Entry.Ty = EVT(MVT::i16).getTypeForEVT(*DAG.getContext());
23923       Entry.IsSExt = false;
23924       Entry.IsZExt = true;
23925       Args.push_back(Entry);
23926 
23927       SDValue Callee = DAG.getExternalSymbol(
23928           getLibcallName(RTLIB::FPEXT_F16_F32),
23929           getPointerTy(DAG.getDataLayout()));
23930       CLI.setDebugLoc(DL).setChain(Chain).setLibCallee(
23931           CallingConv::C, EVT(VT).getTypeForEVT(*DAG.getContext()), Callee,
23932           std::move(Args));
23933 
23934       SDValue Res;
23935       std::tie(Res,Chain) = LowerCallTo(CLI);
23936       if (IsStrict)
23937         Res = DAG.getMergeValues({Res, Chain}, DL);
23938 
23939       return Res;
23940     }
23941 
23942     In = DAG.getBitcast(MVT::i16, In);
23943     In = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v8i16,
23944                      getZeroVector(MVT::v8i16, Subtarget, DAG, DL), In,
23945                      DAG.getIntPtrConstant(0, DL));
23946     SDValue Res;
23947     if (IsStrict) {
23948       Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, DL, {MVT::v4f32, MVT::Other},
23949                         {Chain, In});
23950       Chain = Res.getValue(1);
23951     } else {
23952       Res = DAG.getNode(X86ISD::CVTPH2PS, DL, MVT::v4f32, In,
23953                         DAG.getTargetConstant(4, DL, MVT::i32));
23954     }
23955     Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Res,
23956                       DAG.getIntPtrConstant(0, DL));
23957     if (IsStrict)
23958       return DAG.getMergeValues({Res, Chain}, DL);
23959     return Res;
23960   }
23961 
23962   if (!SVT.isVector())
23963     return Op;
23964 
23965   if (SVT.getVectorElementType() == MVT::bf16) {
23966     // FIXME: Do we need to support strict FP?
23967     assert(!IsStrict && "Strict FP doesn't support BF16");
23968     if (VT.getVectorElementType() == MVT::f64) {
23969       MVT TmpVT = VT.changeVectorElementType(MVT::f32);
23970       return DAG.getNode(ISD::FP_EXTEND, DL, VT,
23971                          DAG.getNode(ISD::FP_EXTEND, DL, TmpVT, In));
23972     }
23973     assert(VT.getVectorElementType() == MVT::f32 && "Unexpected fpext");
23974     MVT NVT = SVT.changeVectorElementType(MVT::i32);
23975     In = DAG.getBitcast(SVT.changeTypeToInteger(), In);
23976     In = DAG.getNode(ISD::ZERO_EXTEND, DL, NVT, In);
23977     In = DAG.getNode(ISD::SHL, DL, NVT, In, DAG.getConstant(16, DL, NVT));
23978     return DAG.getBitcast(VT, In);
23979   }
23980 
23981   if (SVT.getVectorElementType() == MVT::f16) {
23982     if (Subtarget.hasFP16() && isTypeLegal(SVT))
23983       return Op;
23984     assert(Subtarget.hasF16C() && "Unexpected features!");
23985     if (SVT == MVT::v2f16)
23986       In = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f16, In,
23987                        DAG.getUNDEF(MVT::v2f16));
23988     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8f16, In,
23989                               DAG.getUNDEF(MVT::v4f16));
23990     if (IsStrict)
23991       return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
23992                          {Op->getOperand(0), Res});
23993     return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
23994   } else if (VT == MVT::v4f64 || VT == MVT::v8f64) {
23995     return Op;
23996   }
23997 
23998   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
23999 
24000   SDValue Res =
24001       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
24002   if (IsStrict)
24003     return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
24004                        {Op->getOperand(0), Res});
24005   return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
24006 }
24007 
24008 SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
24009   bool IsStrict = Op->isStrictFPOpcode();
24010 
24011   SDLoc DL(Op);
24012   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
24013   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
24014   MVT VT = Op.getSimpleValueType();
24015   MVT SVT = In.getSimpleValueType();
24016 
24017   if (SVT == MVT::f128 || (VT == MVT::f16 && SVT == MVT::f80))
24018     return SDValue();
24019 
24020   if (VT == MVT::f16 && (SVT == MVT::f64 || SVT == MVT::f32) &&
24021       !Subtarget.hasFP16() && (SVT == MVT::f64 || !Subtarget.hasF16C())) {
24022     if (!Subtarget.getTargetTriple().isOSDarwin())
24023       return SDValue();
24024 
24025     // We need a libcall but the ABI for f16 libcalls on MacOS is soft.
24026     TargetLowering::CallLoweringInfo CLI(DAG);
24027     Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
24028 
24029     TargetLowering::ArgListTy Args;
24030     TargetLowering::ArgListEntry Entry;
24031     Entry.Node = In;
24032     Entry.Ty = EVT(SVT).getTypeForEVT(*DAG.getContext());
24033     Entry.IsSExt = false;
24034     Entry.IsZExt = true;
24035     Args.push_back(Entry);
24036 
24037     SDValue Callee = DAG.getExternalSymbol(
24038         getLibcallName(SVT == MVT::f64 ? RTLIB::FPROUND_F64_F16
24039                                        : RTLIB::FPROUND_F32_F16),
24040         getPointerTy(DAG.getDataLayout()));
24041     CLI.setDebugLoc(DL).setChain(Chain).setLibCallee(
24042         CallingConv::C, EVT(MVT::i16).getTypeForEVT(*DAG.getContext()), Callee,
24043         std::move(Args));
24044 
24045     SDValue Res;
24046     std::tie(Res, Chain) = LowerCallTo(CLI);
24047 
24048     Res = DAG.getBitcast(MVT::f16, Res);
24049 
24050     if (IsStrict)
24051       Res = DAG.getMergeValues({Res, Chain}, DL);
24052 
24053     return Res;
24054   }
24055 
24056   if (VT.getScalarType() == MVT::bf16) {
24057     if (SVT.getScalarType() == MVT::f32 && isTypeLegal(VT))
24058       return Op;
24059     return SDValue();
24060   }
24061 
24062   if (VT.getScalarType() == MVT::f16 && !Subtarget.hasFP16()) {
24063     if (!Subtarget.hasF16C() || SVT.getScalarType() != MVT::f32)
24064       return SDValue();
24065 
24066     if (VT.isVector())
24067       return Op;
24068 
24069     SDValue Res;
24070     SDValue Rnd = DAG.getTargetConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, DL,
24071                                         MVT::i32);
24072     if (IsStrict) {
24073       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4f32,
24074                         DAG.getConstantFP(0, DL, MVT::v4f32), In,
24075                         DAG.getIntPtrConstant(0, DL));
24076       Res = DAG.getNode(X86ISD::STRICT_CVTPS2PH, DL, {MVT::v8i16, MVT::Other},
24077                         {Chain, Res, Rnd});
24078       Chain = Res.getValue(1);
24079     } else {
24080       // FIXME: Should we use zeros for upper elements for non-strict?
24081       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, In);
24082       Res = DAG.getNode(X86ISD::CVTPS2PH, DL, MVT::v8i16, Res, Rnd);
24083     }
24084 
24085     Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i16, Res,
24086                       DAG.getIntPtrConstant(0, DL));
24087     Res = DAG.getBitcast(MVT::f16, Res);
24088 
24089     if (IsStrict)
24090       return DAG.getMergeValues({Res, Chain}, DL);
24091 
24092     return Res;
24093   }
24094 
24095   return Op;
24096 }
24097 
24098 static SDValue LowerFP16_TO_FP(SDValue Op, SelectionDAG &DAG) {
24099   bool IsStrict = Op->isStrictFPOpcode();
24100   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
24101   assert(Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 &&
24102          "Unexpected VT!");
24103 
24104   SDLoc dl(Op);
24105   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16,
24106                             DAG.getConstant(0, dl, MVT::v8i16), Src,
24107                             DAG.getIntPtrConstant(0, dl));
24108 
24109   SDValue Chain;
24110   if (IsStrict) {
24111     Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {MVT::v4f32, MVT::Other},
24112                       {Op.getOperand(0), Res});
24113     Chain = Res.getValue(1);
24114   } else {
24115     Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
24116   }
24117 
24118   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
24119                     DAG.getIntPtrConstant(0, dl));
24120 
24121   if (IsStrict)
24122     return DAG.getMergeValues({Res, Chain}, dl);
24123 
24124   return Res;
24125 }
24126 
24127 static SDValue LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) {
24128   bool IsStrict = Op->isStrictFPOpcode();
24129   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
24130   assert(Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 &&
24131          "Unexpected VT!");
24132 
24133   SDLoc dl(Op);
24134   SDValue Res, Chain;
24135   if (IsStrict) {
24136     Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4f32,
24137                       DAG.getConstantFP(0, dl, MVT::v4f32), Src,
24138                       DAG.getIntPtrConstant(0, dl));
24139     Res = DAG.getNode(
24140         X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
24141         {Op.getOperand(0), Res, DAG.getTargetConstant(4, dl, MVT::i32)});
24142     Chain = Res.getValue(1);
24143   } else {
24144     // FIXME: Should we use zeros for upper elements for non-strict?
24145     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, Src);
24146     Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
24147                       DAG.getTargetConstant(4, dl, MVT::i32));
24148   }
24149 
24150   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Res,
24151                     DAG.getIntPtrConstant(0, dl));
24152 
24153   if (IsStrict)
24154     return DAG.getMergeValues({Res, Chain}, dl);
24155 
24156   return Res;
24157 }
24158 
24159 SDValue X86TargetLowering::LowerFP_TO_BF16(SDValue Op,
24160                                            SelectionDAG &DAG) const {
24161   SDLoc DL(Op);
24162   MakeLibCallOptions CallOptions;
24163   RTLIB::Libcall LC =
24164       RTLIB::getFPROUND(Op.getOperand(0).getValueType(), MVT::bf16);
24165   SDValue Res =
24166       makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
24167   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i16,
24168                      DAG.getBitcast(MVT::i32, Res));
24169 }
24170 
24171 /// Depending on uarch and/or optimizing for size, we might prefer to use a
24172 /// vector operation in place of the typical scalar operation.
24173 static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
24174                                          const X86Subtarget &Subtarget) {
24175   // If both operands have other uses, this is probably not profitable.
24176   SDValue LHS = Op.getOperand(0);
24177   SDValue RHS = Op.getOperand(1);
24178   if (!LHS.hasOneUse() && !RHS.hasOneUse())
24179     return Op;
24180 
24181   // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
24182   bool IsFP = Op.getSimpleValueType().isFloatingPoint();
24183   if (IsFP && !Subtarget.hasSSE3())
24184     return Op;
24185   if (!IsFP && !Subtarget.hasSSSE3())
24186     return Op;
24187 
24188   // Extract from a common vector.
24189   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
24190       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
24191       LHS.getOperand(0) != RHS.getOperand(0) ||
24192       !isa<ConstantSDNode>(LHS.getOperand(1)) ||
24193       !isa<ConstantSDNode>(RHS.getOperand(1)) ||
24194       !shouldUseHorizontalOp(true, DAG, Subtarget))
24195     return Op;
24196 
24197   // Allow commuted 'hadd' ops.
24198   // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
24199   unsigned HOpcode;
24200   switch (Op.getOpcode()) {
24201     case ISD::ADD: HOpcode = X86ISD::HADD; break;
24202     case ISD::SUB: HOpcode = X86ISD::HSUB; break;
24203     case ISD::FADD: HOpcode = X86ISD::FHADD; break;
24204     case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
24205     default:
24206       llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
24207   }
24208   unsigned LExtIndex = LHS.getConstantOperandVal(1);
24209   unsigned RExtIndex = RHS.getConstantOperandVal(1);
24210   if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
24211       (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
24212     std::swap(LExtIndex, RExtIndex);
24213 
24214   if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
24215     return Op;
24216 
24217   SDValue X = LHS.getOperand(0);
24218   EVT VecVT = X.getValueType();
24219   unsigned BitWidth = VecVT.getSizeInBits();
24220   unsigned NumLanes = BitWidth / 128;
24221   unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
24222   assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
24223          "Not expecting illegal vector widths here");
24224 
24225   // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
24226   // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
24227   SDLoc DL(Op);
24228   if (BitWidth == 256 || BitWidth == 512) {
24229     unsigned LaneIdx = LExtIndex / NumEltsPerLane;
24230     X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
24231     LExtIndex %= NumEltsPerLane;
24232   }
24233 
24234   // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
24235   // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
24236   // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
24237   // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
24238   SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
24239   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
24240                      DAG.getIntPtrConstant(LExtIndex / 2, DL));
24241 }
24242 
24243 /// Depending on uarch and/or optimizing for size, we might prefer to use a
24244 /// vector operation in place of the typical scalar operation.
24245 SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
24246   assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
24247          "Only expecting float/double");
24248   return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
24249 }
24250 
24251 /// ISD::FROUND is defined to round to nearest with ties rounding away from 0.
24252 /// This mode isn't supported in hardware on X86. But as long as we aren't
24253 /// compiling with trapping math, we can emulate this with
24254 /// trunc(X + copysign(nextafter(0.5, 0.0), X)).
24255 static SDValue LowerFROUND(SDValue Op, SelectionDAG &DAG) {
24256   SDValue N0 = Op.getOperand(0);
24257   SDLoc dl(Op);
24258   MVT VT = Op.getSimpleValueType();
24259 
24260   // N0 += copysign(nextafter(0.5, 0.0), N0)
24261   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
24262   bool Ignored;
24263   APFloat Point5Pred = APFloat(0.5f);
24264   Point5Pred.convert(Sem, APFloat::rmNearestTiesToEven, &Ignored);
24265   Point5Pred.next(/*nextDown*/true);
24266 
24267   SDValue Adder = DAG.getNode(ISD::FCOPYSIGN, dl, VT,
24268                               DAG.getConstantFP(Point5Pred, dl, VT), N0);
24269   N0 = DAG.getNode(ISD::FADD, dl, VT, N0, Adder);
24270 
24271   // Truncate the result to remove fraction.
24272   return DAG.getNode(ISD::FTRUNC, dl, VT, N0);
24273 }
24274 
24275 /// The only differences between FABS and FNEG are the mask and the logic op.
24276 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
24277 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
24278   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
24279          "Wrong opcode for lowering FABS or FNEG.");
24280 
24281   bool IsFABS = (Op.getOpcode() == ISD::FABS);
24282 
24283   // If this is a FABS and it has an FNEG user, bail out to fold the combination
24284   // into an FNABS. We'll lower the FABS after that if it is still in use.
24285   if (IsFABS)
24286     for (SDNode *User : Op->uses())
24287       if (User->getOpcode() == ISD::FNEG)
24288         return Op;
24289 
24290   SDLoc dl(Op);
24291   MVT VT = Op.getSimpleValueType();
24292 
24293   bool IsF128 = (VT == MVT::f128);
24294   assert(VT.isFloatingPoint() && VT != MVT::f80 &&
24295          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
24296          "Unexpected type in LowerFABSorFNEG");
24297 
24298   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
24299   // decide if we should generate a 16-byte constant mask when we only need 4 or
24300   // 8 bytes for the scalar case.
24301 
24302   // There are no scalar bitwise logical SSE/AVX instructions, so we
24303   // generate a 16-byte vector constant and logic op even for the scalar case.
24304   // Using a 16-byte mask allows folding the load of the mask with
24305   // the logic op, so it can save (~4 bytes) on code size.
24306   bool IsFakeVector = !VT.isVector() && !IsF128;
24307   MVT LogicVT = VT;
24308   if (IsFakeVector)
24309     LogicVT = (VT == MVT::f64)   ? MVT::v2f64
24310               : (VT == MVT::f32) ? MVT::v4f32
24311                                  : MVT::v8f16;
24312 
24313   unsigned EltBits = VT.getScalarSizeInBits();
24314   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
24315   APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
24316                            APInt::getSignMask(EltBits);
24317   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
24318   SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
24319 
24320   SDValue Op0 = Op.getOperand(0);
24321   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
24322   unsigned LogicOp = IsFABS  ? X86ISD::FAND :
24323                      IsFNABS ? X86ISD::FOR  :
24324                                X86ISD::FXOR;
24325   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
24326 
24327   if (VT.isVector() || IsF128)
24328     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
24329 
24330   // For the scalar case extend to a 128-bit vector, perform the logic op,
24331   // and extract the scalar result back out.
24332   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
24333   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
24334   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
24335                      DAG.getIntPtrConstant(0, dl));
24336 }
24337 
24338 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
24339   SDValue Mag = Op.getOperand(0);
24340   SDValue Sign = Op.getOperand(1);
24341   SDLoc dl(Op);
24342 
24343   // If the sign operand is smaller, extend it first.
24344   MVT VT = Op.getSimpleValueType();
24345   if (Sign.getSimpleValueType().bitsLT(VT))
24346     Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
24347 
24348   // And if it is bigger, shrink it first.
24349   if (Sign.getSimpleValueType().bitsGT(VT))
24350     Sign = DAG.getNode(ISD::FP_ROUND, dl, VT, Sign,
24351                        DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
24352 
24353   // At this point the operands and the result should have the same
24354   // type, and that won't be f80 since that is not custom lowered.
24355   bool IsF128 = (VT == MVT::f128);
24356   assert(VT.isFloatingPoint() && VT != MVT::f80 &&
24357          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
24358          "Unexpected type in LowerFCOPYSIGN");
24359 
24360   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
24361 
24362   // Perform all scalar logic operations as 16-byte vectors because there are no
24363   // scalar FP logic instructions in SSE.
24364   // TODO: This isn't necessary. If we used scalar types, we might avoid some
24365   // unnecessary splats, but we might miss load folding opportunities. Should
24366   // this decision be based on OptimizeForSize?
24367   bool IsFakeVector = !VT.isVector() && !IsF128;
24368   MVT LogicVT = VT;
24369   if (IsFakeVector)
24370     LogicVT = (VT == MVT::f64)   ? MVT::v2f64
24371               : (VT == MVT::f32) ? MVT::v4f32
24372                                  : MVT::v8f16;
24373 
24374   // The mask constants are automatically splatted for vector types.
24375   unsigned EltSizeInBits = VT.getScalarSizeInBits();
24376   SDValue SignMask = DAG.getConstantFP(
24377       APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
24378   SDValue MagMask = DAG.getConstantFP(
24379       APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
24380 
24381   // First, clear all bits but the sign bit from the second operand (sign).
24382   if (IsFakeVector)
24383     Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
24384   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
24385 
24386   // Next, clear the sign bit from the first operand (magnitude).
24387   // TODO: If we had general constant folding for FP logic ops, this check
24388   // wouldn't be necessary.
24389   SDValue MagBits;
24390   if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
24391     APFloat APF = Op0CN->getValueAPF();
24392     APF.clearSign();
24393     MagBits = DAG.getConstantFP(APF, dl, LogicVT);
24394   } else {
24395     // If the magnitude operand wasn't a constant, we need to AND out the sign.
24396     if (IsFakeVector)
24397       Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
24398     MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
24399   }
24400 
24401   // OR the magnitude value with the sign bit.
24402   SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
24403   return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
24404                                           DAG.getIntPtrConstant(0, dl));
24405 }
24406 
24407 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
24408   SDValue N0 = Op.getOperand(0);
24409   SDLoc dl(Op);
24410   MVT VT = Op.getSimpleValueType();
24411 
24412   MVT OpVT = N0.getSimpleValueType();
24413   assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
24414          "Unexpected type for FGETSIGN");
24415 
24416   // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
24417   MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
24418   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
24419   Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
24420   Res = DAG.getZExtOrTrunc(Res, dl, VT);
24421   Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
24422   return Res;
24423 }
24424 
24425 /// Helper for attempting to create a X86ISD::BT node.
24426 static SDValue getBT(SDValue Src, SDValue BitNo, const SDLoc &DL, SelectionDAG &DAG) {
24427   // If Src is i8, promote it to i32 with any_extend.  There is no i8 BT
24428   // instruction.  Since the shift amount is in-range-or-undefined, we know
24429   // that doing a bittest on the i32 value is ok.  We extend to i32 because
24430   // the encoding for the i16 version is larger than the i32 version.
24431   // Also promote i16 to i32 for performance / code size reason.
24432   if (Src.getValueType().getScalarSizeInBits() < 32)
24433     Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
24434 
24435   // No legal type found, give up.
24436   if (!DAG.getTargetLoweringInfo().isTypeLegal(Src.getValueType()))
24437     return SDValue();
24438 
24439   // See if we can use the 32-bit instruction instead of the 64-bit one for a
24440   // shorter encoding. Since the former takes the modulo 32 of BitNo and the
24441   // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
24442   // known to be zero.
24443   if (Src.getValueType() == MVT::i64 &&
24444       DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
24445     Src = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Src);
24446 
24447   // If the operand types disagree, extend the shift amount to match.  Since
24448   // BT ignores high bits (like shifts) we can use anyextend.
24449   if (Src.getValueType() != BitNo.getValueType()) {
24450     // Peek through a mask/modulo operation.
24451     // TODO: DAGCombine fails to do this as it just checks isTruncateFree, but
24452     // we probably need a better IsDesirableToPromoteOp to handle this as well.
24453     if (BitNo.getOpcode() == ISD::AND && BitNo->hasOneUse())
24454       BitNo = DAG.getNode(ISD::AND, DL, Src.getValueType(),
24455                           DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(),
24456                                       BitNo.getOperand(0)),
24457                           DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(),
24458                                       BitNo.getOperand(1)));
24459     else
24460       BitNo = DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(), BitNo);
24461   }
24462 
24463   return DAG.getNode(X86ISD::BT, DL, MVT::i32, Src, BitNo);
24464 }
24465 
24466 /// Helper for creating a X86ISD::SETCC node.
24467 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
24468                         SelectionDAG &DAG) {
24469   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
24470                      DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
24471 }
24472 
24473 /// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
24474 /// recognizable memcmp expansion.
24475 static bool isOrXorXorTree(SDValue X, bool Root = true) {
24476   if (X.getOpcode() == ISD::OR)
24477     return isOrXorXorTree(X.getOperand(0), false) &&
24478            isOrXorXorTree(X.getOperand(1), false);
24479   if (Root)
24480     return false;
24481   return X.getOpcode() == ISD::XOR;
24482 }
24483 
24484 /// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
24485 /// expansion.
24486 template <typename F>
24487 static SDValue emitOrXorXorTree(SDValue X, const SDLoc &DL, SelectionDAG &DAG,
24488                                 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
24489   SDValue Op0 = X.getOperand(0);
24490   SDValue Op1 = X.getOperand(1);
24491   if (X.getOpcode() == ISD::OR) {
24492     SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
24493     SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
24494     if (VecVT != CmpVT)
24495       return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
24496     if (HasPT)
24497       return DAG.getNode(ISD::OR, DL, VecVT, A, B);
24498     return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
24499   }
24500   if (X.getOpcode() == ISD::XOR) {
24501     SDValue A = SToV(Op0);
24502     SDValue B = SToV(Op1);
24503     if (VecVT != CmpVT)
24504       return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
24505     if (HasPT)
24506       return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
24507     return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
24508   }
24509   llvm_unreachable("Impossible");
24510 }
24511 
24512 /// Try to map a 128-bit or larger integer comparison to vector instructions
24513 /// before type legalization splits it up into chunks.
24514 static SDValue combineVectorSizedSetCCEquality(EVT VT, SDValue X, SDValue Y,
24515                                                ISD::CondCode CC,
24516                                                const SDLoc &DL,
24517                                                SelectionDAG &DAG,
24518                                                const X86Subtarget &Subtarget) {
24519   assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
24520 
24521   // We're looking for an oversized integer equality comparison.
24522   EVT OpVT = X.getValueType();
24523   unsigned OpSize = OpVT.getSizeInBits();
24524   if (!OpVT.isScalarInteger() || OpSize < 128)
24525     return SDValue();
24526 
24527   // Ignore a comparison with zero because that gets special treatment in
24528   // EmitTest(). But make an exception for the special case of a pair of
24529   // logically-combined vector-sized operands compared to zero. This pattern may
24530   // be generated by the memcmp expansion pass with oversized integer compares
24531   // (see PR33325).
24532   bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
24533   if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
24534     return SDValue();
24535 
24536   // Don't perform this combine if constructing the vector will be expensive.
24537   auto IsVectorBitCastCheap = [](SDValue X) {
24538     X = peekThroughBitcasts(X);
24539     return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
24540            X.getOpcode() == ISD::LOAD;
24541   };
24542   if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
24543       !IsOrXorXorTreeCCZero)
24544     return SDValue();
24545 
24546   // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
24547   // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
24548   // Otherwise use PCMPEQ (plus AND) and mask testing.
24549   bool NoImplicitFloatOps =
24550       DAG.getMachineFunction().getFunction().hasFnAttribute(
24551           Attribute::NoImplicitFloat);
24552   if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
24553       ((OpSize == 128 && Subtarget.hasSSE2()) ||
24554        (OpSize == 256 && Subtarget.hasAVX()) ||
24555        (OpSize == 512 && Subtarget.useAVX512Regs()))) {
24556     bool HasPT = Subtarget.hasSSE41();
24557 
24558     // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
24559     // vector registers are essentially free. (Technically, widening registers
24560     // prevents load folding, but the tradeoff is worth it.)
24561     bool PreferKOT = Subtarget.preferMaskRegisters();
24562     bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
24563 
24564     EVT VecVT = MVT::v16i8;
24565     EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
24566     if (OpSize == 256) {
24567       VecVT = MVT::v32i8;
24568       CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
24569     }
24570     EVT CastVT = VecVT;
24571     bool NeedsAVX512FCast = false;
24572     if (OpSize == 512 || NeedZExt) {
24573       if (Subtarget.hasBWI()) {
24574         VecVT = MVT::v64i8;
24575         CmpVT = MVT::v64i1;
24576         if (OpSize == 512)
24577           CastVT = VecVT;
24578       } else {
24579         VecVT = MVT::v16i32;
24580         CmpVT = MVT::v16i1;
24581         CastVT = OpSize == 512   ? VecVT
24582                  : OpSize == 256 ? MVT::v8i32
24583                                  : MVT::v4i32;
24584         NeedsAVX512FCast = true;
24585       }
24586     }
24587 
24588     auto ScalarToVector = [&](SDValue X) -> SDValue {
24589       bool TmpZext = false;
24590       EVT TmpCastVT = CastVT;
24591       if (X.getOpcode() == ISD::ZERO_EXTEND) {
24592         SDValue OrigX = X.getOperand(0);
24593         unsigned OrigSize = OrigX.getScalarValueSizeInBits();
24594         if (OrigSize < OpSize) {
24595           if (OrigSize == 128) {
24596             TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
24597             X = OrigX;
24598             TmpZext = true;
24599           } else if (OrigSize == 256) {
24600             TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
24601             X = OrigX;
24602             TmpZext = true;
24603           }
24604         }
24605       }
24606       X = DAG.getBitcast(TmpCastVT, X);
24607       if (!NeedZExt && !TmpZext)
24608         return X;
24609       return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
24610                          DAG.getConstant(0, DL, VecVT), X,
24611                          DAG.getVectorIdxConstant(0, DL));
24612     };
24613 
24614     SDValue Cmp;
24615     if (IsOrXorXorTreeCCZero) {
24616       // This is a bitwise-combined equality comparison of 2 pairs of vectors:
24617       // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
24618       // Use 2 vector equality compares and 'and' the results before doing a
24619       // MOVMSK.
24620       Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
24621     } else {
24622       SDValue VecX = ScalarToVector(X);
24623       SDValue VecY = ScalarToVector(Y);
24624       if (VecVT != CmpVT) {
24625         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
24626       } else if (HasPT) {
24627         Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
24628       } else {
24629         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
24630       }
24631     }
24632     // AVX512 should emit a setcc that will lower to kortest.
24633     if (VecVT != CmpVT) {
24634       EVT KRegVT = CmpVT == MVT::v64i1   ? MVT::i64
24635                    : CmpVT == MVT::v32i1 ? MVT::i32
24636                                          : MVT::i16;
24637       return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
24638                           DAG.getConstant(0, DL, KRegVT), CC);
24639     }
24640     if (HasPT) {
24641       SDValue BCCmp =
24642           DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64, Cmp);
24643       SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
24644       X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
24645       SDValue X86SetCC = getSETCC(X86CC, PT, DL, DAG);
24646       return DAG.getNode(ISD::TRUNCATE, DL, VT, X86SetCC.getValue(0));
24647     }
24648     // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
24649     // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
24650     // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
24651     assert(Cmp.getValueType() == MVT::v16i8 &&
24652            "Non 128-bit vector on pre-SSE41 target");
24653     SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
24654     SDValue FFFFs = DAG.getConstant(0xFFFF, DL, MVT::i32);
24655     return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
24656   }
24657 
24658   return SDValue();
24659 }
24660 
24661 /// Helper for matching BINOP(EXTRACTELT(X,0),BINOP(EXTRACTELT(X,1),...))
24662 /// style scalarized (associative) reduction patterns. Partial reductions
24663 /// are supported when the pointer SrcMask is non-null.
24664 /// TODO - move this to SelectionDAG?
24665 static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
24666                                  SmallVectorImpl<SDValue> &SrcOps,
24667                                  SmallVectorImpl<APInt> *SrcMask = nullptr) {
24668   SmallVector<SDValue, 8> Opnds;
24669   DenseMap<SDValue, APInt> SrcOpMap;
24670   EVT VT = MVT::Other;
24671 
24672   // Recognize a special case where a vector is casted into wide integer to
24673   // test all 0s.
24674   assert(Op.getOpcode() == unsigned(BinOp) &&
24675          "Unexpected bit reduction opcode");
24676   Opnds.push_back(Op.getOperand(0));
24677   Opnds.push_back(Op.getOperand(1));
24678 
24679   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
24680     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
24681     // BFS traverse all BinOp operands.
24682     if (I->getOpcode() == unsigned(BinOp)) {
24683       Opnds.push_back(I->getOperand(0));
24684       Opnds.push_back(I->getOperand(1));
24685       // Re-evaluate the number of nodes to be traversed.
24686       e += 2; // 2 more nodes (LHS and RHS) are pushed.
24687       continue;
24688     }
24689 
24690     // Quit if a non-EXTRACT_VECTOR_ELT
24691     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24692       return false;
24693 
24694     // Quit if without a constant index.
24695     auto *Idx = dyn_cast<ConstantSDNode>(I->getOperand(1));
24696     if (!Idx)
24697       return false;
24698 
24699     SDValue Src = I->getOperand(0);
24700     DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
24701     if (M == SrcOpMap.end()) {
24702       VT = Src.getValueType();
24703       // Quit if not the same type.
24704       if (!SrcOpMap.empty() && VT != SrcOpMap.begin()->first.getValueType())
24705         return false;
24706       unsigned NumElts = VT.getVectorNumElements();
24707       APInt EltCount = APInt::getZero(NumElts);
24708       M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
24709       SrcOps.push_back(Src);
24710     }
24711 
24712     // Quit if element already used.
24713     unsigned CIdx = Idx->getZExtValue();
24714     if (M->second[CIdx])
24715       return false;
24716     M->second.setBit(CIdx);
24717   }
24718 
24719   if (SrcMask) {
24720     // Collect the source partial masks.
24721     for (SDValue &SrcOp : SrcOps)
24722       SrcMask->push_back(SrcOpMap[SrcOp]);
24723   } else {
24724     // Quit if not all elements are used.
24725     for (const auto &I : SrcOpMap)
24726       if (!I.second.isAllOnes())
24727         return false;
24728   }
24729 
24730   return true;
24731 }
24732 
24733 // Helper function for comparing all bits of two vectors.
24734 static SDValue LowerVectorAllEqual(const SDLoc &DL, SDValue LHS, SDValue RHS,
24735                                    ISD::CondCode CC, const APInt &OriginalMask,
24736                                    const X86Subtarget &Subtarget,
24737                                    SelectionDAG &DAG, X86::CondCode &X86CC) {
24738   EVT VT = LHS.getValueType();
24739   unsigned ScalarSize = VT.getScalarSizeInBits();
24740   if (OriginalMask.getBitWidth() != ScalarSize) {
24741     assert(ScalarSize == 1 && "Element Mask vs Vector bitwidth mismatch");
24742     return SDValue();
24743   }
24744 
24745   // Quit if not convertable to legal scalar or 128/256-bit vector.
24746   if (!llvm::has_single_bit<uint32_t>(VT.getSizeInBits()))
24747     return SDValue();
24748 
24749   // FCMP may use ISD::SETNE when nnan - early out if we manage to get here.
24750   if (VT.isFloatingPoint())
24751     return SDValue();
24752 
24753   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
24754   X86CC = (CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE);
24755 
24756   APInt Mask = OriginalMask;
24757 
24758   auto MaskBits = [&](SDValue Src) {
24759     if (Mask.isAllOnes())
24760       return Src;
24761     EVT SrcVT = Src.getValueType();
24762     SDValue MaskValue = DAG.getConstant(Mask, DL, SrcVT);
24763     return DAG.getNode(ISD::AND, DL, SrcVT, Src, MaskValue);
24764   };
24765 
24766   // For sub-128-bit vector, cast to (legal) integer and compare with zero.
24767   if (VT.getSizeInBits() < 128) {
24768     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
24769     if (!DAG.getTargetLoweringInfo().isTypeLegal(IntVT)) {
24770       if (IntVT != MVT::i64)
24771         return SDValue();
24772       auto SplitLHS = DAG.SplitScalar(DAG.getBitcast(IntVT, MaskBits(LHS)), DL,
24773                                       MVT::i32, MVT::i32);
24774       auto SplitRHS = DAG.SplitScalar(DAG.getBitcast(IntVT, MaskBits(RHS)), DL,
24775                                       MVT::i32, MVT::i32);
24776       SDValue Lo =
24777           DAG.getNode(ISD::XOR, DL, MVT::i32, SplitLHS.first, SplitRHS.first);
24778       SDValue Hi =
24779           DAG.getNode(ISD::XOR, DL, MVT::i32, SplitLHS.second, SplitRHS.second);
24780       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
24781                          DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi),
24782                          DAG.getConstant(0, DL, MVT::i32));
24783     }
24784     return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
24785                        DAG.getBitcast(IntVT, MaskBits(LHS)),
24786                        DAG.getBitcast(IntVT, MaskBits(RHS)));
24787   }
24788 
24789   // Without PTEST, a masked v2i64 or-reduction is not faster than
24790   // scalarization.
24791   bool UseKORTEST = Subtarget.useAVX512Regs();
24792   bool UsePTEST = Subtarget.hasSSE41();
24793   if (!UsePTEST && !Mask.isAllOnes() && ScalarSize > 32)
24794     return SDValue();
24795 
24796   // Split down to 128/256/512-bit vector.
24797   unsigned TestSize = UseKORTEST ? 512 : (Subtarget.hasAVX() ? 256 : 128);
24798 
24799   // If the input vector has vector elements wider than the target test size,
24800   // then cast to <X x i64> so it will safely split.
24801   if (ScalarSize > TestSize) {
24802     if (!Mask.isAllOnes())
24803       return SDValue();
24804     VT = EVT::getVectorVT(*DAG.getContext(), MVT::i64, VT.getSizeInBits() / 64);
24805     LHS = DAG.getBitcast(VT, LHS);
24806     RHS = DAG.getBitcast(VT, RHS);
24807     Mask = APInt::getAllOnes(64);
24808   }
24809 
24810   if (VT.getSizeInBits() > TestSize) {
24811     KnownBits KnownRHS = DAG.computeKnownBits(RHS);
24812     if (KnownRHS.isConstant() && KnownRHS.getConstant() == Mask) {
24813       // If ICMP(AND(LHS,MASK),MASK) - reduce using AND splits.
24814       while (VT.getSizeInBits() > TestSize) {
24815         auto Split = DAG.SplitVector(LHS, DL);
24816         VT = Split.first.getValueType();
24817         LHS = DAG.getNode(ISD::AND, DL, VT, Split.first, Split.second);
24818       }
24819       RHS = DAG.getAllOnesConstant(DL, VT);
24820     } else if (!UsePTEST && !KnownRHS.isZero()) {
24821       // MOVMSK Special Case:
24822       // ALLOF(CMPEQ(X,Y)) -> AND(CMPEQ(X[0],Y[0]),CMPEQ(X[1],Y[1]),....)
24823       MVT SVT = ScalarSize >= 32 ? MVT::i32 : MVT::i8;
24824       VT = MVT::getVectorVT(SVT, VT.getSizeInBits() / SVT.getSizeInBits());
24825       LHS = DAG.getBitcast(VT, MaskBits(LHS));
24826       RHS = DAG.getBitcast(VT, MaskBits(RHS));
24827       EVT BoolVT = VT.changeVectorElementType(MVT::i1);
24828       SDValue V = DAG.getSetCC(DL, BoolVT, LHS, RHS, ISD::SETEQ);
24829       V = DAG.getSExtOrTrunc(V, DL, VT);
24830       while (VT.getSizeInBits() > TestSize) {
24831         auto Split = DAG.SplitVector(V, DL);
24832         VT = Split.first.getValueType();
24833         V = DAG.getNode(ISD::AND, DL, VT, Split.first, Split.second);
24834       }
24835       V = DAG.getNOT(DL, V, VT);
24836       V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
24837       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
24838                          DAG.getConstant(0, DL, MVT::i32));
24839     } else {
24840       // Convert to a ICMP_EQ(XOR(LHS,RHS),0) pattern.
24841       SDValue V = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
24842       while (VT.getSizeInBits() > TestSize) {
24843         auto Split = DAG.SplitVector(V, DL);
24844         VT = Split.first.getValueType();
24845         V = DAG.getNode(ISD::OR, DL, VT, Split.first, Split.second);
24846       }
24847       LHS = V;
24848       RHS = DAG.getConstant(0, DL, VT);
24849     }
24850   }
24851 
24852   if (UseKORTEST && VT.is512BitVector()) {
24853     MVT TestVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
24854     MVT BoolVT = TestVT.changeVectorElementType(MVT::i1);
24855     LHS = DAG.getBitcast(TestVT, MaskBits(LHS));
24856     RHS = DAG.getBitcast(TestVT, MaskBits(RHS));
24857     SDValue V = DAG.getSetCC(DL, BoolVT, LHS, RHS, ISD::SETNE);
24858     return DAG.getNode(X86ISD::KORTEST, DL, MVT::i32, V, V);
24859   }
24860 
24861   if (UsePTEST) {
24862     MVT TestVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
24863     LHS = DAG.getBitcast(TestVT, MaskBits(LHS));
24864     RHS = DAG.getBitcast(TestVT, MaskBits(RHS));
24865     SDValue V = DAG.getNode(ISD::XOR, DL, TestVT, LHS, RHS);
24866     return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, V, V);
24867   }
24868 
24869   assert(VT.getSizeInBits() == 128 && "Failure to split to 128-bits");
24870   MVT MaskVT = ScalarSize >= 32 ? MVT::v4i32 : MVT::v16i8;
24871   LHS = DAG.getBitcast(MaskVT, MaskBits(LHS));
24872   RHS = DAG.getBitcast(MaskVT, MaskBits(RHS));
24873   SDValue V = DAG.getNode(X86ISD::PCMPEQ, DL, MaskVT, LHS, RHS);
24874   V = DAG.getNOT(DL, V, MaskVT);
24875   V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
24876   return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
24877                      DAG.getConstant(0, DL, MVT::i32));
24878 }
24879 
24880 // Check whether an AND/OR'd reduction tree is PTEST-able, or if we can fallback
24881 // to CMP(MOVMSK(PCMPEQB(X,Y))).
24882 static SDValue MatchVectorAllEqualTest(SDValue LHS, SDValue RHS,
24883                                        ISD::CondCode CC, const SDLoc &DL,
24884                                        const X86Subtarget &Subtarget,
24885                                        SelectionDAG &DAG,
24886                                        X86::CondCode &X86CC) {
24887   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
24888 
24889   bool CmpNull = isNullConstant(RHS);
24890   bool CmpAllOnes = isAllOnesConstant(RHS);
24891   if (!CmpNull && !CmpAllOnes)
24892     return SDValue();
24893 
24894   SDValue Op = LHS;
24895   if (!Subtarget.hasSSE2() || !Op->hasOneUse())
24896     return SDValue();
24897 
24898   // Check whether we're masking/truncating an OR-reduction result, in which
24899   // case track the masked bits.
24900   // TODO: Add CmpAllOnes support.
24901   APInt Mask = APInt::getAllOnes(Op.getScalarValueSizeInBits());
24902   if (CmpNull) {
24903     switch (Op.getOpcode()) {
24904     case ISD::TRUNCATE: {
24905       SDValue Src = Op.getOperand(0);
24906       Mask = APInt::getLowBitsSet(Src.getScalarValueSizeInBits(),
24907                                   Op.getScalarValueSizeInBits());
24908       Op = Src;
24909       break;
24910     }
24911     case ISD::AND: {
24912       if (auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24913         Mask = Cst->getAPIntValue();
24914         Op = Op.getOperand(0);
24915       }
24916       break;
24917     }
24918     }
24919   }
24920 
24921   ISD::NodeType LogicOp = CmpNull ? ISD::OR : ISD::AND;
24922 
24923   // Match icmp(or(extract(X,0),extract(X,1)),0) anyof reduction patterns.
24924   // Match icmp(and(extract(X,0),extract(X,1)),-1) allof reduction patterns.
24925   SmallVector<SDValue, 8> VecIns;
24926   if (Op.getOpcode() == LogicOp && matchScalarReduction(Op, LogicOp, VecIns)) {
24927     EVT VT = VecIns[0].getValueType();
24928     assert(llvm::all_of(VecIns,
24929                         [VT](SDValue V) { return VT == V.getValueType(); }) &&
24930            "Reduction source vector mismatch");
24931 
24932     // Quit if not splittable to scalar/128/256/512-bit vector.
24933     if (!llvm::has_single_bit<uint32_t>(VT.getSizeInBits()))
24934       return SDValue();
24935 
24936     // If more than one full vector is evaluated, AND/OR them first before
24937     // PTEST.
24938     for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1;
24939          Slot += 2, e += 1) {
24940       // Each iteration will AND/OR 2 nodes and append the result until there is
24941       // only 1 node left, i.e. the final value of all vectors.
24942       SDValue LHS = VecIns[Slot];
24943       SDValue RHS = VecIns[Slot + 1];
24944       VecIns.push_back(DAG.getNode(LogicOp, DL, VT, LHS, RHS));
24945     }
24946 
24947     return LowerVectorAllEqual(DL, VecIns.back(),
24948                                CmpNull ? DAG.getConstant(0, DL, VT)
24949                                        : DAG.getAllOnesConstant(DL, VT),
24950                                CC, Mask, Subtarget, DAG, X86CC);
24951   }
24952 
24953   // Match icmp(reduce_or(X),0) anyof reduction patterns.
24954   // Match icmp(reduce_and(X),-1) allof reduction patterns.
24955   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24956     ISD::NodeType BinOp;
24957     if (SDValue Match =
24958             DAG.matchBinOpReduction(Op.getNode(), BinOp, {LogicOp})) {
24959       EVT MatchVT = Match.getValueType();
24960       return LowerVectorAllEqual(DL, Match,
24961                                  CmpNull ? DAG.getConstant(0, DL, MatchVT)
24962                                          : DAG.getAllOnesConstant(DL, MatchVT),
24963                                  CC, Mask, Subtarget, DAG, X86CC);
24964     }
24965   }
24966 
24967   if (Mask.isAllOnes()) {
24968     assert(!Op.getValueType().isVector() &&
24969            "Illegal vector type for reduction pattern");
24970     SDValue Src = peekThroughBitcasts(Op);
24971     if (Src.getValueType().isFixedLengthVector() &&
24972         Src.getValueType().getScalarType() == MVT::i1) {
24973       // Match icmp(bitcast(icmp_ne(X,Y)),0) reduction patterns.
24974       // Match icmp(bitcast(icmp_eq(X,Y)),-1) reduction patterns.
24975       if (Src.getOpcode() == ISD::SETCC) {
24976         SDValue LHS = Src.getOperand(0);
24977         SDValue RHS = Src.getOperand(1);
24978         EVT LHSVT = LHS.getValueType();
24979         ISD::CondCode SrcCC = cast<CondCodeSDNode>(Src.getOperand(2))->get();
24980         if (SrcCC == (CmpNull ? ISD::SETNE : ISD::SETEQ) &&
24981             llvm::has_single_bit<uint32_t>(LHSVT.getSizeInBits())) {
24982           APInt SrcMask = APInt::getAllOnes(LHSVT.getScalarSizeInBits());
24983           return LowerVectorAllEqual(DL, LHS, RHS, CC, SrcMask, Subtarget, DAG,
24984                                      X86CC);
24985         }
24986       }
24987       // Match icmp(bitcast(vXi1 trunc(Y)),0) reduction patterns.
24988       // Match icmp(bitcast(vXi1 trunc(Y)),-1) reduction patterns.
24989       // Peek through truncation, mask the LSB and compare against zero/LSB.
24990       if (Src.getOpcode() == ISD::TRUNCATE) {
24991         SDValue Inner = Src.getOperand(0);
24992         EVT InnerVT = Inner.getValueType();
24993         if (llvm::has_single_bit<uint32_t>(InnerVT.getSizeInBits())) {
24994           unsigned BW = InnerVT.getScalarSizeInBits();
24995           APInt SrcMask = APInt(BW, 1);
24996           APInt Cmp = CmpNull ? APInt::getZero(BW) : SrcMask;
24997           return LowerVectorAllEqual(DL, Inner,
24998                                      DAG.getConstant(Cmp, DL, InnerVT), CC,
24999                                      SrcMask, Subtarget, DAG, X86CC);
25000         }
25001       }
25002     }
25003   }
25004 
25005   return SDValue();
25006 }
25007 
25008 /// return true if \c Op has a use that doesn't just read flags.
25009 static bool hasNonFlagsUse(SDValue Op) {
25010   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
25011        ++UI) {
25012     SDNode *User = *UI;
25013     unsigned UOpNo = UI.getOperandNo();
25014     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
25015       // Look pass truncate.
25016       UOpNo = User->use_begin().getOperandNo();
25017       User = *User->use_begin();
25018     }
25019 
25020     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
25021         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
25022       return true;
25023   }
25024   return false;
25025 }
25026 
25027 // Transform to an x86-specific ALU node with flags if there is a chance of
25028 // using an RMW op or only the flags are used. Otherwise, leave
25029 // the node alone and emit a 'cmp' or 'test' instruction.
25030 static bool isProfitableToUseFlagOp(SDValue Op) {
25031   for (SDNode *U : Op->uses())
25032     if (U->getOpcode() != ISD::CopyToReg &&
25033         U->getOpcode() != ISD::SETCC &&
25034         U->getOpcode() != ISD::STORE)
25035       return false;
25036 
25037   return true;
25038 }
25039 
25040 /// Emit nodes that will be selected as "test Op0,Op0", or something
25041 /// equivalent.
25042 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
25043                         SelectionDAG &DAG, const X86Subtarget &Subtarget) {
25044   // CF and OF aren't always set the way we want. Determine which
25045   // of these we need.
25046   bool NeedCF = false;
25047   bool NeedOF = false;
25048   switch (X86CC) {
25049   default: break;
25050   case X86::COND_A: case X86::COND_AE:
25051   case X86::COND_B: case X86::COND_BE:
25052     NeedCF = true;
25053     break;
25054   case X86::COND_G: case X86::COND_GE:
25055   case X86::COND_L: case X86::COND_LE:
25056   case X86::COND_O: case X86::COND_NO: {
25057     // Check if we really need to set the
25058     // Overflow flag. If NoSignedWrap is present
25059     // that is not actually needed.
25060     switch (Op->getOpcode()) {
25061     case ISD::ADD:
25062     case ISD::SUB:
25063     case ISD::MUL:
25064     case ISD::SHL:
25065       if (Op.getNode()->getFlags().hasNoSignedWrap())
25066         break;
25067       [[fallthrough]];
25068     default:
25069       NeedOF = true;
25070       break;
25071     }
25072     break;
25073   }
25074   }
25075   // See if we can use the EFLAGS value from the operand instead of
25076   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
25077   // we prove that the arithmetic won't overflow, we can't use OF or CF.
25078   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
25079     // Emit a CMP with 0, which is the TEST pattern.
25080     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
25081                        DAG.getConstant(0, dl, Op.getValueType()));
25082   }
25083   unsigned Opcode = 0;
25084   unsigned NumOperands = 0;
25085 
25086   SDValue ArithOp = Op;
25087 
25088   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
25089   // which may be the result of a CAST.  We use the variable 'Op', which is the
25090   // non-casted variable when we check for possible users.
25091   switch (ArithOp.getOpcode()) {
25092   case ISD::AND:
25093     // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
25094     // because a TEST instruction will be better.
25095     if (!hasNonFlagsUse(Op))
25096       break;
25097 
25098     [[fallthrough]];
25099   case ISD::ADD:
25100   case ISD::SUB:
25101   case ISD::OR:
25102   case ISD::XOR:
25103     if (!isProfitableToUseFlagOp(Op))
25104       break;
25105 
25106     // Otherwise use a regular EFLAGS-setting instruction.
25107     switch (ArithOp.getOpcode()) {
25108     default: llvm_unreachable("unexpected operator!");
25109     case ISD::ADD: Opcode = X86ISD::ADD; break;
25110     case ISD::SUB: Opcode = X86ISD::SUB; break;
25111     case ISD::XOR: Opcode = X86ISD::XOR; break;
25112     case ISD::AND: Opcode = X86ISD::AND; break;
25113     case ISD::OR:  Opcode = X86ISD::OR;  break;
25114     }
25115 
25116     NumOperands = 2;
25117     break;
25118   case X86ISD::ADD:
25119   case X86ISD::SUB:
25120   case X86ISD::OR:
25121   case X86ISD::XOR:
25122   case X86ISD::AND:
25123     return SDValue(Op.getNode(), 1);
25124   case ISD::SSUBO:
25125   case ISD::USUBO: {
25126     // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
25127     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
25128     return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
25129                        Op->getOperand(1)).getValue(1);
25130   }
25131   default:
25132     break;
25133   }
25134 
25135   if (Opcode == 0) {
25136     // Emit a CMP with 0, which is the TEST pattern.
25137     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
25138                        DAG.getConstant(0, dl, Op.getValueType()));
25139   }
25140   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
25141   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
25142 
25143   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
25144   DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
25145   return SDValue(New.getNode(), 1);
25146 }
25147 
25148 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
25149 /// equivalent.
25150 static SDValue EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
25151                        const SDLoc &dl, SelectionDAG &DAG,
25152                        const X86Subtarget &Subtarget) {
25153   if (isNullConstant(Op1))
25154     return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
25155 
25156   EVT CmpVT = Op0.getValueType();
25157 
25158   assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||
25159           CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!");
25160 
25161   // Only promote the compare up to I32 if it is a 16 bit operation
25162   // with an immediate.  16 bit immediates are to be avoided.
25163   if (CmpVT == MVT::i16 && !Subtarget.isAtom() &&
25164       !DAG.getMachineFunction().getFunction().hasMinSize()) {
25165     ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
25166     ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
25167     // Don't do this if the immediate can fit in 8-bits.
25168     if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
25169         (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
25170       unsigned ExtendOp =
25171           isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
25172       if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
25173         // For equality comparisons try to use SIGN_EXTEND if the input was
25174         // truncate from something with enough sign bits.
25175         if (Op0.getOpcode() == ISD::TRUNCATE) {
25176           if (DAG.ComputeMaxSignificantBits(Op0.getOperand(0)) <= 16)
25177             ExtendOp = ISD::SIGN_EXTEND;
25178         } else if (Op1.getOpcode() == ISD::TRUNCATE) {
25179           if (DAG.ComputeMaxSignificantBits(Op1.getOperand(0)) <= 16)
25180             ExtendOp = ISD::SIGN_EXTEND;
25181         }
25182       }
25183 
25184       CmpVT = MVT::i32;
25185       Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
25186       Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
25187     }
25188   }
25189 
25190   // Try to shrink i64 compares if the input has enough zero bits.
25191   // FIXME: Do this for non-constant compares for constant on LHS?
25192   if (CmpVT == MVT::i64 && isa<ConstantSDNode>(Op1) && !isX86CCSigned(X86CC) &&
25193       Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
25194       cast<ConstantSDNode>(Op1)->getAPIntValue().getActiveBits() <= 32 &&
25195       DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
25196     CmpVT = MVT::i32;
25197     Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
25198     Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
25199   }
25200 
25201   // 0-x == y --> x+y == 0
25202   // 0-x != y --> x+y != 0
25203   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op0.getOperand(0)) &&
25204       Op0.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
25205     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
25206     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(1), Op1);
25207     return Add.getValue(1);
25208   }
25209 
25210   // x == 0-y --> x+y == 0
25211   // x != 0-y --> x+y != 0
25212   if (Op1.getOpcode() == ISD::SUB && isNullConstant(Op1.getOperand(0)) &&
25213       Op1.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
25214     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
25215     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0, Op1.getOperand(1));
25216     return Add.getValue(1);
25217   }
25218 
25219   // Use SUB instead of CMP to enable CSE between SUB and CMP.
25220   SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
25221   SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
25222   return Sub.getValue(1);
25223 }
25224 
25225 /// Check if replacement of SQRT with RSQRT should be disabled.
25226 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
25227   EVT VT = Op.getValueType();
25228 
25229   // We don't need to replace SQRT with RSQRT for half type.
25230   if (VT.getScalarType() == MVT::f16)
25231     return true;
25232 
25233   // We never want to use both SQRT and RSQRT instructions for the same input.
25234   if (DAG.doesNodeExist(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
25235     return false;
25236 
25237   if (VT.isVector())
25238     return Subtarget.hasFastVectorFSQRT();
25239   return Subtarget.hasFastScalarFSQRT();
25240 }
25241 
25242 /// The minimum architected relative accuracy is 2^-12. We need one
25243 /// Newton-Raphson step to have a good float result (24 bits of precision).
25244 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
25245                                            SelectionDAG &DAG, int Enabled,
25246                                            int &RefinementSteps,
25247                                            bool &UseOneConstNR,
25248                                            bool Reciprocal) const {
25249   SDLoc DL(Op);
25250   EVT VT = Op.getValueType();
25251 
25252   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
25253   // It is likely not profitable to do this for f64 because a double-precision
25254   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
25255   // instructions: convert to single, rsqrtss, convert back to double, refine
25256   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
25257   // along with FMA, this could be a throughput win.
25258   // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
25259   // after legalize types.
25260   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
25261       (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
25262       (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
25263       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
25264       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
25265     if (RefinementSteps == ReciprocalEstimate::Unspecified)
25266       RefinementSteps = 1;
25267 
25268     UseOneConstNR = false;
25269     // There is no FSQRT for 512-bits, but there is RSQRT14.
25270     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
25271     SDValue Estimate = DAG.getNode(Opcode, DL, VT, Op);
25272     if (RefinementSteps == 0 && !Reciprocal)
25273       Estimate = DAG.getNode(ISD::FMUL, DL, VT, Op, Estimate);
25274     return Estimate;
25275   }
25276 
25277   if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
25278       Subtarget.hasFP16()) {
25279     assert(Reciprocal && "Don't replace SQRT with RSQRT for half type");
25280     if (RefinementSteps == ReciprocalEstimate::Unspecified)
25281       RefinementSteps = 0;
25282 
25283     if (VT == MVT::f16) {
25284       SDValue Zero = DAG.getIntPtrConstant(0, DL);
25285       SDValue Undef = DAG.getUNDEF(MVT::v8f16);
25286       Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
25287       Op = DAG.getNode(X86ISD::RSQRT14S, DL, MVT::v8f16, Undef, Op);
25288       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
25289     }
25290 
25291     return DAG.getNode(X86ISD::RSQRT14, DL, VT, Op);
25292   }
25293   return SDValue();
25294 }
25295 
25296 /// The minimum architected relative accuracy is 2^-12. We need one
25297 /// Newton-Raphson step to have a good float result (24 bits of precision).
25298 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
25299                                             int Enabled,
25300                                             int &RefinementSteps) const {
25301   SDLoc DL(Op);
25302   EVT VT = Op.getValueType();
25303 
25304   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
25305   // It is likely not profitable to do this for f64 because a double-precision
25306   // reciprocal estimate with refinement on x86 prior to FMA requires
25307   // 15 instructions: convert to single, rcpss, convert back to double, refine
25308   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
25309   // along with FMA, this could be a throughput win.
25310 
25311   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
25312       (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
25313       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
25314       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
25315     // Enable estimate codegen with 1 refinement step for vector division.
25316     // Scalar division estimates are disabled because they break too much
25317     // real-world code. These defaults are intended to match GCC behavior.
25318     if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
25319       return SDValue();
25320 
25321     if (RefinementSteps == ReciprocalEstimate::Unspecified)
25322       RefinementSteps = 1;
25323 
25324     // There is no FSQRT for 512-bits, but there is RCP14.
25325     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
25326     return DAG.getNode(Opcode, DL, VT, Op);
25327   }
25328 
25329   if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
25330       Subtarget.hasFP16()) {
25331     if (RefinementSteps == ReciprocalEstimate::Unspecified)
25332       RefinementSteps = 0;
25333 
25334     if (VT == MVT::f16) {
25335       SDValue Zero = DAG.getIntPtrConstant(0, DL);
25336       SDValue Undef = DAG.getUNDEF(MVT::v8f16);
25337       Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
25338       Op = DAG.getNode(X86ISD::RCP14S, DL, MVT::v8f16, Undef, Op);
25339       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
25340     }
25341 
25342     return DAG.getNode(X86ISD::RCP14, DL, VT, Op);
25343   }
25344   return SDValue();
25345 }
25346 
25347 /// If we have at least two divisions that use the same divisor, convert to
25348 /// multiplication by a reciprocal. This may need to be adjusted for a given
25349 /// CPU if a division's cost is not at least twice the cost of a multiplication.
25350 /// This is because we still need one division to calculate the reciprocal and
25351 /// then we need two multiplies by that reciprocal as replacements for the
25352 /// original divisions.
25353 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
25354   return 2;
25355 }
25356 
25357 SDValue
25358 X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
25359                                  SelectionDAG &DAG,
25360                                  SmallVectorImpl<SDNode *> &Created) const {
25361   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
25362   if (isIntDivCheap(N->getValueType(0), Attr))
25363     return SDValue(N,0); // Lower SDIV as SDIV
25364 
25365   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
25366          "Unexpected divisor!");
25367 
25368   // Only perform this transform if CMOV is supported otherwise the select
25369   // below will become a branch.
25370   if (!Subtarget.canUseCMOV())
25371     return SDValue();
25372 
25373   // fold (sdiv X, pow2)
25374   EVT VT = N->getValueType(0);
25375   // FIXME: Support i8.
25376   if (VT != MVT::i16 && VT != MVT::i32 &&
25377       !(Subtarget.is64Bit() && VT == MVT::i64))
25378     return SDValue();
25379 
25380   unsigned Lg2 = Divisor.countr_zero();
25381 
25382   // If the divisor is 2 or -2, the default expansion is better.
25383   if (Lg2 == 1)
25384     return SDValue();
25385 
25386   SDLoc DL(N);
25387   SDValue N0 = N->getOperand(0);
25388   SDValue Zero = DAG.getConstant(0, DL, VT);
25389   APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
25390   SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
25391 
25392   // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
25393   SDValue Cmp = DAG.getSetCC(DL, MVT::i8, N0, Zero, ISD::SETLT);
25394   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
25395   SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
25396 
25397   Created.push_back(Cmp.getNode());
25398   Created.push_back(Add.getNode());
25399   Created.push_back(CMov.getNode());
25400 
25401   // Divide by pow2.
25402   SDValue SRA =
25403       DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, MVT::i8));
25404 
25405   // If we're dividing by a positive value, we're done.  Otherwise, we must
25406   // negate the result.
25407   if (Divisor.isNonNegative())
25408     return SRA;
25409 
25410   Created.push_back(SRA.getNode());
25411   return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
25412 }
25413 
25414 /// Result of 'and' is compared against zero. Change to a BT node if possible.
25415 /// Returns the BT node and the condition code needed to use it.
25416 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC, const SDLoc &dl,
25417                             SelectionDAG &DAG, X86::CondCode &X86CC) {
25418   assert(And.getOpcode() == ISD::AND && "Expected AND node!");
25419   SDValue Op0 = And.getOperand(0);
25420   SDValue Op1 = And.getOperand(1);
25421   if (Op0.getOpcode() == ISD::TRUNCATE)
25422     Op0 = Op0.getOperand(0);
25423   if (Op1.getOpcode() == ISD::TRUNCATE)
25424     Op1 = Op1.getOperand(0);
25425 
25426   SDValue Src, BitNo;
25427   if (Op1.getOpcode() == ISD::SHL)
25428     std::swap(Op0, Op1);
25429   if (Op0.getOpcode() == ISD::SHL) {
25430     if (isOneConstant(Op0.getOperand(0))) {
25431       // If we looked past a truncate, check that it's only truncating away
25432       // known zeros.
25433       unsigned BitWidth = Op0.getValueSizeInBits();
25434       unsigned AndBitWidth = And.getValueSizeInBits();
25435       if (BitWidth > AndBitWidth) {
25436         KnownBits Known = DAG.computeKnownBits(Op0);
25437         if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
25438           return SDValue();
25439       }
25440       Src = Op1;
25441       BitNo = Op0.getOperand(1);
25442     }
25443   } else if (Op1.getOpcode() == ISD::Constant) {
25444     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
25445     uint64_t AndRHSVal = AndRHS->getZExtValue();
25446     SDValue AndLHS = Op0;
25447 
25448     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
25449       Src = AndLHS.getOperand(0);
25450       BitNo = AndLHS.getOperand(1);
25451     } else {
25452       // Use BT if the immediate can't be encoded in a TEST instruction or we
25453       // are optimizing for size and the immedaite won't fit in a byte.
25454       bool OptForSize = DAG.shouldOptForSize();
25455       if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
25456           isPowerOf2_64(AndRHSVal)) {
25457         Src = AndLHS;
25458         BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
25459                                 Src.getValueType());
25460       }
25461     }
25462   }
25463 
25464   // No patterns found, give up.
25465   if (!Src.getNode())
25466     return SDValue();
25467 
25468   // Remove any bit flip.
25469   if (isBitwiseNot(Src)) {
25470     Src = Src.getOperand(0);
25471     CC = CC == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
25472   }
25473 
25474   // Attempt to create the X86ISD::BT node.
25475   if (SDValue BT = getBT(Src, BitNo, dl, DAG)) {
25476     X86CC = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
25477     return BT;
25478   }
25479 
25480   return SDValue();
25481 }
25482 
25483 // Check if pre-AVX condcode can be performed by a single FCMP op.
25484 static bool cheapX86FSETCC_SSE(ISD::CondCode SetCCOpcode) {
25485   return (SetCCOpcode != ISD::SETONE) && (SetCCOpcode != ISD::SETUEQ);
25486 }
25487 
25488 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
25489 /// CMPs.
25490 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
25491                                    SDValue &Op1, bool &IsAlwaysSignaling) {
25492   unsigned SSECC;
25493   bool Swap = false;
25494 
25495   // SSE Condition code mapping:
25496   //  0 - EQ
25497   //  1 - LT
25498   //  2 - LE
25499   //  3 - UNORD
25500   //  4 - NEQ
25501   //  5 - NLT
25502   //  6 - NLE
25503   //  7 - ORD
25504   switch (SetCCOpcode) {
25505   default: llvm_unreachable("Unexpected SETCC condition");
25506   case ISD::SETOEQ:
25507   case ISD::SETEQ:  SSECC = 0; break;
25508   case ISD::SETOGT:
25509   case ISD::SETGT:  Swap = true; [[fallthrough]];
25510   case ISD::SETLT:
25511   case ISD::SETOLT: SSECC = 1; break;
25512   case ISD::SETOGE:
25513   case ISD::SETGE:  Swap = true; [[fallthrough]];
25514   case ISD::SETLE:
25515   case ISD::SETOLE: SSECC = 2; break;
25516   case ISD::SETUO:  SSECC = 3; break;
25517   case ISD::SETUNE:
25518   case ISD::SETNE:  SSECC = 4; break;
25519   case ISD::SETULE: Swap = true; [[fallthrough]];
25520   case ISD::SETUGE: SSECC = 5; break;
25521   case ISD::SETULT: Swap = true; [[fallthrough]];
25522   case ISD::SETUGT: SSECC = 6; break;
25523   case ISD::SETO:   SSECC = 7; break;
25524   case ISD::SETUEQ: SSECC = 8; break;
25525   case ISD::SETONE: SSECC = 12; break;
25526   }
25527   if (Swap)
25528     std::swap(Op0, Op1);
25529 
25530   switch (SetCCOpcode) {
25531   default:
25532     IsAlwaysSignaling = true;
25533     break;
25534   case ISD::SETEQ:
25535   case ISD::SETOEQ:
25536   case ISD::SETUEQ:
25537   case ISD::SETNE:
25538   case ISD::SETONE:
25539   case ISD::SETUNE:
25540   case ISD::SETO:
25541   case ISD::SETUO:
25542     IsAlwaysSignaling = false;
25543     break;
25544   }
25545 
25546   return SSECC;
25547 }
25548 
25549 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
25550 /// concatenate the result back.
25551 static SDValue splitIntVSETCC(EVT VT, SDValue LHS, SDValue RHS,
25552                               ISD::CondCode Cond, SelectionDAG &DAG,
25553                               const SDLoc &dl) {
25554   assert(VT.isInteger() && VT == LHS.getValueType() &&
25555          VT == RHS.getValueType() && "Unsupported VTs!");
25556 
25557   SDValue CC = DAG.getCondCode(Cond);
25558 
25559   // Extract the LHS Lo/Hi vectors
25560   SDValue LHS1, LHS2;
25561   std::tie(LHS1, LHS2) = splitVector(LHS, DAG, dl);
25562 
25563   // Extract the RHS Lo/Hi vectors
25564   SDValue RHS1, RHS2;
25565   std::tie(RHS1, RHS2) = splitVector(RHS, DAG, dl);
25566 
25567   // Issue the operation on the smaller types and concatenate the result back
25568   EVT LoVT, HiVT;
25569   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
25570   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
25571                      DAG.getNode(ISD::SETCC, dl, LoVT, LHS1, RHS1, CC),
25572                      DAG.getNode(ISD::SETCC, dl, HiVT, LHS2, RHS2, CC));
25573 }
25574 
25575 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
25576 
25577   SDValue Op0 = Op.getOperand(0);
25578   SDValue Op1 = Op.getOperand(1);
25579   SDValue CC = Op.getOperand(2);
25580   MVT VT = Op.getSimpleValueType();
25581   SDLoc dl(Op);
25582 
25583   assert(VT.getVectorElementType() == MVT::i1 &&
25584          "Cannot set masked compare for this operation");
25585 
25586   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
25587 
25588   // Prefer SETGT over SETLT.
25589   if (SetCCOpcode == ISD::SETLT) {
25590     SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
25591     std::swap(Op0, Op1);
25592   }
25593 
25594   return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
25595 }
25596 
25597 /// Given a buildvector constant, return a new vector constant with each element
25598 /// incremented or decremented. If incrementing or decrementing would result in
25599 /// unsigned overflow or underflow or this is not a simple vector constant,
25600 /// return an empty value.
25601 static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc,
25602                                     bool NSW) {
25603   auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
25604   if (!BV || !V.getValueType().isSimple())
25605     return SDValue();
25606 
25607   MVT VT = V.getSimpleValueType();
25608   MVT EltVT = VT.getVectorElementType();
25609   unsigned NumElts = VT.getVectorNumElements();
25610   SmallVector<SDValue, 8> NewVecC;
25611   SDLoc DL(V);
25612   for (unsigned i = 0; i < NumElts; ++i) {
25613     auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
25614     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
25615       return SDValue();
25616 
25617     // Avoid overflow/underflow.
25618     const APInt &EltC = Elt->getAPIntValue();
25619     if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isZero()))
25620       return SDValue();
25621     if (NSW && ((IsInc && EltC.isMaxSignedValue()) ||
25622                 (!IsInc && EltC.isMinSignedValue())))
25623       return SDValue();
25624 
25625     NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
25626   }
25627 
25628   return DAG.getBuildVector(VT, DL, NewVecC);
25629 }
25630 
25631 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
25632 /// Op0 u<= Op1:
25633 ///   t = psubus Op0, Op1
25634 ///   pcmpeq t, <0..0>
25635 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
25636                                     ISD::CondCode Cond, const SDLoc &dl,
25637                                     const X86Subtarget &Subtarget,
25638                                     SelectionDAG &DAG) {
25639   if (!Subtarget.hasSSE2())
25640     return SDValue();
25641 
25642   MVT VET = VT.getVectorElementType();
25643   if (VET != MVT::i8 && VET != MVT::i16)
25644     return SDValue();
25645 
25646   switch (Cond) {
25647   default:
25648     return SDValue();
25649   case ISD::SETULT: {
25650     // If the comparison is against a constant we can turn this into a
25651     // setule.  With psubus, setule does not require a swap.  This is
25652     // beneficial because the constant in the register is no longer
25653     // destructed as the destination so it can be hoisted out of a loop.
25654     // Only do this pre-AVX since vpcmp* is no longer destructive.
25655     if (Subtarget.hasAVX())
25656       return SDValue();
25657     SDValue ULEOp1 =
25658         incDecVectorConstant(Op1, DAG, /*IsInc*/ false, /*NSW*/ false);
25659     if (!ULEOp1)
25660       return SDValue();
25661     Op1 = ULEOp1;
25662     break;
25663   }
25664   case ISD::SETUGT: {
25665     // If the comparison is against a constant, we can turn this into a setuge.
25666     // This is beneficial because materializing a constant 0 for the PCMPEQ is
25667     // probably cheaper than XOR+PCMPGT using 2 different vector constants:
25668     // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
25669     SDValue UGEOp1 =
25670         incDecVectorConstant(Op1, DAG, /*IsInc*/ true, /*NSW*/ false);
25671     if (!UGEOp1)
25672       return SDValue();
25673     Op1 = Op0;
25674     Op0 = UGEOp1;
25675     break;
25676   }
25677   // Psubus is better than flip-sign because it requires no inversion.
25678   case ISD::SETUGE:
25679     std::swap(Op0, Op1);
25680     break;
25681   case ISD::SETULE:
25682     break;
25683   }
25684 
25685   SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
25686   return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
25687                      DAG.getConstant(0, dl, VT));
25688 }
25689 
25690 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
25691                            SelectionDAG &DAG) {
25692   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
25693                   Op.getOpcode() == ISD::STRICT_FSETCCS;
25694   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
25695   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
25696   SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
25697   MVT VT = Op->getSimpleValueType(0);
25698   ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
25699   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
25700   SDLoc dl(Op);
25701 
25702   if (isFP) {
25703     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
25704     assert(EltVT == MVT::f16 || EltVT == MVT::f32 || EltVT == MVT::f64);
25705     if (isSoftF16(EltVT, Subtarget))
25706       return SDValue();
25707 
25708     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
25709     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
25710 
25711     // If we have a strict compare with a vXi1 result and the input is 128/256
25712     // bits we can't use a masked compare unless we have VLX. If we use a wider
25713     // compare like we do for non-strict, we might trigger spurious exceptions
25714     // from the upper elements. Instead emit a AVX compare and convert to mask.
25715     unsigned Opc;
25716     if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1 &&
25717         (!IsStrict || Subtarget.hasVLX() ||
25718          Op0.getSimpleValueType().is512BitVector())) {
25719 #ifndef NDEBUG
25720       unsigned Num = VT.getVectorNumElements();
25721       assert(Num <= 16 || (Num == 32 && EltVT == MVT::f16));
25722 #endif
25723       Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
25724     } else {
25725       Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
25726       // The SSE/AVX packed FP comparison nodes are defined with a
25727       // floating-point vector result that matches the operand type. This allows
25728       // them to work with an SSE1 target (integer vector types are not legal).
25729       VT = Op0.getSimpleValueType();
25730     }
25731 
25732     SDValue Cmp;
25733     bool IsAlwaysSignaling;
25734     unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
25735     if (!Subtarget.hasAVX()) {
25736       // TODO: We could use following steps to handle a quiet compare with
25737       // signaling encodings.
25738       // 1. Get ordered masks from a quiet ISD::SETO
25739       // 2. Use the masks to mask potential unordered elements in operand A, B
25740       // 3. Get the compare results of masked A, B
25741       // 4. Calculating final result using the mask and result from 3
25742       // But currently, we just fall back to scalar operations.
25743       if (IsStrict && IsAlwaysSignaling && !IsSignaling)
25744         return SDValue();
25745 
25746       // Insert an extra signaling instruction to raise exception.
25747       if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
25748         SDValue SignalCmp = DAG.getNode(
25749             Opc, dl, {VT, MVT::Other},
25750             {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
25751         // FIXME: It seems we need to update the flags of all new strict nodes.
25752         // Otherwise, mayRaiseFPException in MI will return false due to
25753         // NoFPExcept = false by default. However, I didn't find it in other
25754         // patches.
25755         SignalCmp->setFlags(Op->getFlags());
25756         Chain = SignalCmp.getValue(1);
25757       }
25758 
25759       // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
25760       // emit two comparisons and a logic op to tie them together.
25761       if (!cheapX86FSETCC_SSE(Cond)) {
25762         // LLVM predicate is SETUEQ or SETONE.
25763         unsigned CC0, CC1;
25764         unsigned CombineOpc;
25765         if (Cond == ISD::SETUEQ) {
25766           CC0 = 3; // UNORD
25767           CC1 = 0; // EQ
25768           CombineOpc = X86ISD::FOR;
25769         } else {
25770           assert(Cond == ISD::SETONE);
25771           CC0 = 7; // ORD
25772           CC1 = 4; // NEQ
25773           CombineOpc = X86ISD::FAND;
25774         }
25775 
25776         SDValue Cmp0, Cmp1;
25777         if (IsStrict) {
25778           Cmp0 = DAG.getNode(
25779               Opc, dl, {VT, MVT::Other},
25780               {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
25781           Cmp1 = DAG.getNode(
25782               Opc, dl, {VT, MVT::Other},
25783               {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
25784           Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
25785                               Cmp1.getValue(1));
25786         } else {
25787           Cmp0 = DAG.getNode(
25788               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
25789           Cmp1 = DAG.getNode(
25790               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
25791         }
25792         Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
25793       } else {
25794         if (IsStrict) {
25795           Cmp = DAG.getNode(
25796               Opc, dl, {VT, MVT::Other},
25797               {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
25798           Chain = Cmp.getValue(1);
25799         } else
25800           Cmp = DAG.getNode(
25801               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
25802       }
25803     } else {
25804       // Handle all other FP comparisons here.
25805       if (IsStrict) {
25806         // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
25807         SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
25808         Cmp = DAG.getNode(
25809             Opc, dl, {VT, MVT::Other},
25810             {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
25811         Chain = Cmp.getValue(1);
25812       } else
25813         Cmp = DAG.getNode(
25814             Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
25815     }
25816 
25817     if (VT.getFixedSizeInBits() >
25818         Op.getSimpleValueType().getFixedSizeInBits()) {
25819       // We emitted a compare with an XMM/YMM result. Finish converting to a
25820       // mask register using a vptestm.
25821       EVT CastVT = EVT(VT).changeVectorElementTypeToInteger();
25822       Cmp = DAG.getBitcast(CastVT, Cmp);
25823       Cmp = DAG.getSetCC(dl, Op.getSimpleValueType(), Cmp,
25824                          DAG.getConstant(0, dl, CastVT), ISD::SETNE);
25825     } else {
25826       // If this is SSE/AVX CMPP, bitcast the result back to integer to match
25827       // the result type of SETCC. The bitcast is expected to be optimized
25828       // away during combining/isel.
25829       Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
25830     }
25831 
25832     if (IsStrict)
25833       return DAG.getMergeValues({Cmp, Chain}, dl);
25834 
25835     return Cmp;
25836   }
25837 
25838   assert(!IsStrict && "Strict SETCC only handles FP operands.");
25839 
25840   MVT VTOp0 = Op0.getSimpleValueType();
25841   (void)VTOp0;
25842   assert(VTOp0 == Op1.getSimpleValueType() &&
25843          "Expected operands with same type!");
25844   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
25845          "Invalid number of packed elements for source and destination!");
25846 
25847   // The non-AVX512 code below works under the assumption that source and
25848   // destination types are the same.
25849   assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
25850          "Value types for source and destination must be the same!");
25851 
25852   // The result is boolean, but operands are int/float
25853   if (VT.getVectorElementType() == MVT::i1) {
25854     // In AVX-512 architecture setcc returns mask with i1 elements,
25855     // But there is no compare instruction for i8 and i16 elements in KNL.
25856     assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
25857            "Unexpected operand type");
25858     return LowerIntVSETCC_AVX512(Op, DAG);
25859   }
25860 
25861   // Lower using XOP integer comparisons.
25862   if (VT.is128BitVector() && Subtarget.hasXOP()) {
25863     // Translate compare code to XOP PCOM compare mode.
25864     unsigned CmpMode = 0;
25865     switch (Cond) {
25866     default: llvm_unreachable("Unexpected SETCC condition");
25867     case ISD::SETULT:
25868     case ISD::SETLT: CmpMode = 0x00; break;
25869     case ISD::SETULE:
25870     case ISD::SETLE: CmpMode = 0x01; break;
25871     case ISD::SETUGT:
25872     case ISD::SETGT: CmpMode = 0x02; break;
25873     case ISD::SETUGE:
25874     case ISD::SETGE: CmpMode = 0x03; break;
25875     case ISD::SETEQ: CmpMode = 0x04; break;
25876     case ISD::SETNE: CmpMode = 0x05; break;
25877     }
25878 
25879     // Are we comparing unsigned or signed integers?
25880     unsigned Opc =
25881         ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
25882 
25883     return DAG.getNode(Opc, dl, VT, Op0, Op1,
25884                        DAG.getTargetConstant(CmpMode, dl, MVT::i8));
25885   }
25886 
25887   // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
25888   // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
25889   if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
25890     SDValue BC0 = peekThroughBitcasts(Op0);
25891     if (BC0.getOpcode() == ISD::AND) {
25892       APInt UndefElts;
25893       SmallVector<APInt, 64> EltBits;
25894       if (getTargetConstantBitsFromNode(BC0.getOperand(1),
25895                                         VT.getScalarSizeInBits(), UndefElts,
25896                                         EltBits, false, false)) {
25897         if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
25898           Cond = ISD::SETEQ;
25899           Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
25900         }
25901       }
25902     }
25903   }
25904 
25905   // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
25906   if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
25907       Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
25908     ConstantSDNode *C1 = isConstOrConstSplat(Op1);
25909     if (C1 && C1->getAPIntValue().isPowerOf2()) {
25910       unsigned BitWidth = VT.getScalarSizeInBits();
25911       unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
25912 
25913       SDValue Result = Op0.getOperand(0);
25914       Result = DAG.getNode(ISD::SHL, dl, VT, Result,
25915                            DAG.getConstant(ShiftAmt, dl, VT));
25916       Result = DAG.getNode(ISD::SRA, dl, VT, Result,
25917                            DAG.getConstant(BitWidth - 1, dl, VT));
25918       return Result;
25919     }
25920   }
25921 
25922   // Break 256-bit integer vector compare into smaller ones.
25923   if (VT.is256BitVector() && !Subtarget.hasInt256())
25924     return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
25925 
25926   // Break 512-bit integer vector compare into smaller ones.
25927   // TODO: Try harder to use VPCMPx + VPMOV2x?
25928   if (VT.is512BitVector())
25929     return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
25930 
25931   // If we have a limit constant, try to form PCMPGT (signed cmp) to avoid
25932   // not-of-PCMPEQ:
25933   // X != INT_MIN --> X >s INT_MIN
25934   // X != INT_MAX --> X <s INT_MAX --> INT_MAX >s X
25935   // +X != 0 --> +X >s 0
25936   APInt ConstValue;
25937   if (Cond == ISD::SETNE &&
25938       ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
25939     if (ConstValue.isMinSignedValue())
25940       Cond = ISD::SETGT;
25941     else if (ConstValue.isMaxSignedValue())
25942       Cond = ISD::SETLT;
25943     else if (ConstValue.isZero() && DAG.SignBitIsZero(Op0))
25944       Cond = ISD::SETGT;
25945   }
25946 
25947   // If both operands are known non-negative, then an unsigned compare is the
25948   // same as a signed compare and there's no need to flip signbits.
25949   // TODO: We could check for more general simplifications here since we're
25950   // computing known bits.
25951   bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
25952                    !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
25953 
25954   // Special case: Use min/max operations for unsigned compares.
25955   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25956   if (ISD::isUnsignedIntSetCC(Cond) &&
25957       (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
25958       TLI.isOperationLegal(ISD::UMIN, VT)) {
25959     // If we have a constant operand, increment/decrement it and change the
25960     // condition to avoid an invert.
25961     if (Cond == ISD::SETUGT) {
25962       // X > C --> X >= (C+1) --> X == umax(X, C+1)
25963       if (SDValue UGTOp1 =
25964               incDecVectorConstant(Op1, DAG, /*IsInc*/ true, /*NSW*/ false)) {
25965         Op1 = UGTOp1;
25966         Cond = ISD::SETUGE;
25967       }
25968     }
25969     if (Cond == ISD::SETULT) {
25970       // X < C --> X <= (C-1) --> X == umin(X, C-1)
25971       if (SDValue ULTOp1 =
25972               incDecVectorConstant(Op1, DAG, /*IsInc*/ false, /*NSW*/ false)) {
25973         Op1 = ULTOp1;
25974         Cond = ISD::SETULE;
25975       }
25976     }
25977     bool Invert = false;
25978     unsigned Opc;
25979     switch (Cond) {
25980     default: llvm_unreachable("Unexpected condition code");
25981     case ISD::SETUGT: Invert = true; [[fallthrough]];
25982     case ISD::SETULE: Opc = ISD::UMIN; break;
25983     case ISD::SETULT: Invert = true; [[fallthrough]];
25984     case ISD::SETUGE: Opc = ISD::UMAX; break;
25985     }
25986 
25987     SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
25988     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
25989 
25990     // If the logical-not of the result is required, perform that now.
25991     if (Invert)
25992       Result = DAG.getNOT(dl, Result, VT);
25993 
25994     return Result;
25995   }
25996 
25997   // Try to use SUBUS and PCMPEQ.
25998   if (FlipSigns)
25999     if (SDValue V =
26000             LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
26001       return V;
26002 
26003   // We are handling one of the integer comparisons here. Since SSE only has
26004   // GT and EQ comparisons for integer, swapping operands and multiple
26005   // operations may be required for some comparisons.
26006   unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
26007                                                             : X86ISD::PCMPGT;
26008   bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
26009               Cond == ISD::SETGE || Cond == ISD::SETUGE;
26010   bool Invert = Cond == ISD::SETNE ||
26011                 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
26012 
26013   if (Swap)
26014     std::swap(Op0, Op1);
26015 
26016   // Check that the operation in question is available (most are plain SSE2,
26017   // but PCMPGTQ and PCMPEQQ have different requirements).
26018   if (VT == MVT::v2i64) {
26019     if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
26020       assert(Subtarget.hasSSE2() && "Don't know how to lower!");
26021 
26022       // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
26023       // the odd elements over the even elements.
26024       if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
26025         Op0 = DAG.getConstant(0, dl, MVT::v4i32);
26026         Op1 = DAG.getBitcast(MVT::v4i32, Op1);
26027 
26028         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
26029         static const int MaskHi[] = { 1, 1, 3, 3 };
26030         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
26031 
26032         return DAG.getBitcast(VT, Result);
26033       }
26034 
26035       if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
26036         Op0 = DAG.getBitcast(MVT::v4i32, Op0);
26037         Op1 = DAG.getConstant(-1, dl, MVT::v4i32);
26038 
26039         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
26040         static const int MaskHi[] = { 1, 1, 3, 3 };
26041         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
26042 
26043         return DAG.getBitcast(VT, Result);
26044       }
26045 
26046       // Since SSE has no unsigned integer comparisons, we need to flip the sign
26047       // bits of the inputs before performing those operations. The lower
26048       // compare is always unsigned.
26049       SDValue SB = DAG.getConstant(FlipSigns ? 0x8000000080000000ULL
26050                                              : 0x0000000080000000ULL,
26051                                    dl, MVT::v2i64);
26052 
26053       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
26054       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
26055 
26056       // Cast everything to the right type.
26057       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
26058       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
26059 
26060       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
26061       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
26062       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
26063 
26064       // Create masks for only the low parts/high parts of the 64 bit integers.
26065       static const int MaskHi[] = { 1, 1, 3, 3 };
26066       static const int MaskLo[] = { 0, 0, 2, 2 };
26067       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
26068       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
26069       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
26070 
26071       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
26072       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
26073 
26074       if (Invert)
26075         Result = DAG.getNOT(dl, Result, MVT::v4i32);
26076 
26077       return DAG.getBitcast(VT, Result);
26078     }
26079 
26080     if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
26081       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
26082       // pcmpeqd + pshufd + pand.
26083       assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
26084 
26085       // First cast everything to the right type.
26086       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
26087       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
26088 
26089       // Do the compare.
26090       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
26091 
26092       // Make sure the lower and upper halves are both all-ones.
26093       static const int Mask[] = { 1, 0, 3, 2 };
26094       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
26095       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
26096 
26097       if (Invert)
26098         Result = DAG.getNOT(dl, Result, MVT::v4i32);
26099 
26100       return DAG.getBitcast(VT, Result);
26101     }
26102   }
26103 
26104   // Since SSE has no unsigned integer comparisons, we need to flip the sign
26105   // bits of the inputs before performing those operations.
26106   if (FlipSigns) {
26107     MVT EltVT = VT.getVectorElementType();
26108     SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
26109                                  VT);
26110     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
26111     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
26112   }
26113 
26114   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
26115 
26116   // If the logical-not of the result is required, perform that now.
26117   if (Invert)
26118     Result = DAG.getNOT(dl, Result, VT);
26119 
26120   return Result;
26121 }
26122 
26123 // Try to select this as a KORTEST+SETCC or KTEST+SETCC if possible.
26124 static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
26125                               const SDLoc &dl, SelectionDAG &DAG,
26126                               const X86Subtarget &Subtarget,
26127                               SDValue &X86CC) {
26128   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
26129 
26130   // Must be a bitcast from vXi1.
26131   if (Op0.getOpcode() != ISD::BITCAST)
26132     return SDValue();
26133 
26134   Op0 = Op0.getOperand(0);
26135   MVT VT = Op0.getSimpleValueType();
26136   if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
26137       !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
26138       !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
26139     return SDValue();
26140 
26141   X86::CondCode X86Cond;
26142   if (isNullConstant(Op1)) {
26143     X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
26144   } else if (isAllOnesConstant(Op1)) {
26145     // C flag is set for all ones.
26146     X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
26147   } else
26148     return SDValue();
26149 
26150   // If the input is an AND, we can combine it's operands into the KTEST.
26151   bool KTestable = false;
26152   if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
26153     KTestable = true;
26154   if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
26155     KTestable = true;
26156   if (!isNullConstant(Op1))
26157     KTestable = false;
26158   if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
26159     SDValue LHS = Op0.getOperand(0);
26160     SDValue RHS = Op0.getOperand(1);
26161     X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
26162     return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
26163   }
26164 
26165   // If the input is an OR, we can combine it's operands into the KORTEST.
26166   SDValue LHS = Op0;
26167   SDValue RHS = Op0;
26168   if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
26169     LHS = Op0.getOperand(0);
26170     RHS = Op0.getOperand(1);
26171   }
26172 
26173   X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
26174   return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
26175 }
26176 
26177 /// Emit flags for the given setcc condition and operands. Also returns the
26178 /// corresponding X86 condition code constant in X86CC.
26179 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
26180                                              ISD::CondCode CC, const SDLoc &dl,
26181                                              SelectionDAG &DAG,
26182                                              SDValue &X86CC) const {
26183   // Equality Combines.
26184   if (CC == ISD::SETEQ || CC == ISD::SETNE) {
26185     X86::CondCode X86CondCode;
26186 
26187     // Optimize to BT if possible.
26188     // Lower (X & (1 << N)) == 0 to BT(X, N).
26189     // Lower ((X >>u N) & 1) != 0 to BT(X, N).
26190     // Lower ((X >>s N) & 1) != 0 to BT(X, N).
26191     if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1)) {
26192       if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CondCode)) {
26193         X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
26194         return BT;
26195       }
26196     }
26197 
26198     // Try to use PTEST/PMOVMSKB for a tree AND/ORs equality compared with -1/0.
26199     if (SDValue CmpZ = MatchVectorAllEqualTest(Op0, Op1, CC, dl, Subtarget, DAG,
26200                                                X86CondCode)) {
26201       X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
26202       return CmpZ;
26203     }
26204 
26205     // Try to lower using KORTEST or KTEST.
26206     if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
26207       return Test;
26208 
26209     // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms
26210     // of these.
26211     if (isOneConstant(Op1) || isNullConstant(Op1)) {
26212       // If the input is a setcc, then reuse the input setcc or use a new one
26213       // with the inverted condition.
26214       if (Op0.getOpcode() == X86ISD::SETCC) {
26215         bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
26216 
26217         X86CC = Op0.getOperand(0);
26218         if (Invert) {
26219           X86CondCode = (X86::CondCode)Op0.getConstantOperandVal(0);
26220           X86CondCode = X86::GetOppositeBranchCondition(X86CondCode);
26221           X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
26222         }
26223 
26224         return Op0.getOperand(1);
26225       }
26226     }
26227 
26228     // Try to use the carry flag from the add in place of an separate CMP for:
26229     // (seteq (add X, -1), -1). Similar for setne.
26230     if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
26231         Op0.getOperand(1) == Op1) {
26232       if (isProfitableToUseFlagOp(Op0)) {
26233         SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
26234 
26235         SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
26236                                   Op0.getOperand(1));
26237         DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
26238         X86CondCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
26239         X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
26240         return SDValue(New.getNode(), 1);
26241       }
26242     }
26243   }
26244 
26245   X86::CondCode CondCode =
26246       TranslateX86CC(CC, dl, /*IsFP*/ false, Op0, Op1, DAG);
26247   assert(CondCode != X86::COND_INVALID && "Unexpected condition code!");
26248 
26249   SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget);
26250   X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
26251   return EFLAGS;
26252 }
26253 
26254 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
26255 
26256   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
26257                   Op.getOpcode() == ISD::STRICT_FSETCCS;
26258   MVT VT = Op->getSimpleValueType(0);
26259 
26260   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
26261 
26262   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
26263   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
26264   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
26265   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
26266   SDLoc dl(Op);
26267   ISD::CondCode CC =
26268       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
26269 
26270   if (isSoftF16(Op0.getValueType(), Subtarget))
26271     return SDValue();
26272 
26273   // Handle f128 first, since one possible outcome is a normal integer
26274   // comparison which gets handled by emitFlagsForSetcc.
26275   if (Op0.getValueType() == MVT::f128) {
26276     softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
26277                         Op.getOpcode() == ISD::STRICT_FSETCCS);
26278 
26279     // If softenSetCCOperands returned a scalar, use it.
26280     if (!Op1.getNode()) {
26281       assert(Op0.getValueType() == Op.getValueType() &&
26282              "Unexpected setcc expansion!");
26283       if (IsStrict)
26284         return DAG.getMergeValues({Op0, Chain}, dl);
26285       return Op0;
26286     }
26287   }
26288 
26289   if (Op0.getSimpleValueType().isInteger()) {
26290     // Attempt to canonicalize SGT/UGT -> SGE/UGE compares with constant which
26291     // reduces the number of EFLAGs bit reads (the GE conditions don't read ZF),
26292     // this may translate to less uops depending on uarch implementation. The
26293     // equivalent for SLE/ULE -> SLT/ULT isn't likely to happen as we already
26294     // canonicalize to that CondCode.
26295     // NOTE: Only do this if incrementing the constant doesn't increase the bit
26296     // encoding size - so it must either already be a i8 or i32 immediate, or it
26297     // shrinks down to that. We don't do this for any i64's to avoid additional
26298     // constant materializations.
26299     // TODO: Can we move this to TranslateX86CC to handle jumps/branches too?
26300     if (auto *Op1C = dyn_cast<ConstantSDNode>(Op1)) {
26301       const APInt &Op1Val = Op1C->getAPIntValue();
26302       if (!Op1Val.isZero()) {
26303         // Ensure the constant+1 doesn't overflow.
26304         if ((CC == ISD::CondCode::SETGT && !Op1Val.isMaxSignedValue()) ||
26305             (CC == ISD::CondCode::SETUGT && !Op1Val.isMaxValue())) {
26306           APInt Op1ValPlusOne = Op1Val + 1;
26307           if (Op1ValPlusOne.isSignedIntN(32) &&
26308               (!Op1Val.isSignedIntN(8) || Op1ValPlusOne.isSignedIntN(8))) {
26309             Op1 = DAG.getConstant(Op1ValPlusOne, dl, Op0.getValueType());
26310             CC = CC == ISD::CondCode::SETGT ? ISD::CondCode::SETGE
26311                                             : ISD::CondCode::SETUGE;
26312           }
26313         }
26314       }
26315     }
26316 
26317     SDValue X86CC;
26318     SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
26319     SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
26320     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
26321   }
26322 
26323   // Handle floating point.
26324   X86::CondCode CondCode = TranslateX86CC(CC, dl, /*IsFP*/ true, Op0, Op1, DAG);
26325   if (CondCode == X86::COND_INVALID)
26326     return SDValue();
26327 
26328   SDValue EFLAGS;
26329   if (IsStrict) {
26330     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
26331     EFLAGS =
26332         DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
26333                     dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
26334     Chain = EFLAGS.getValue(1);
26335   } else {
26336     EFLAGS = DAG.getNode(X86ISD::FCMP, dl, MVT::i32, Op0, Op1);
26337   }
26338 
26339   SDValue X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
26340   SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
26341   return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
26342 }
26343 
26344 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
26345   SDValue LHS = Op.getOperand(0);
26346   SDValue RHS = Op.getOperand(1);
26347   SDValue Carry = Op.getOperand(2);
26348   SDValue Cond = Op.getOperand(3);
26349   SDLoc DL(Op);
26350 
26351   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
26352   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
26353 
26354   // Recreate the carry if needed.
26355   EVT CarryVT = Carry.getValueType();
26356   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
26357                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
26358 
26359   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
26360   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
26361   return getSETCC(CC, Cmp.getValue(1), DL, DAG);
26362 }
26363 
26364 // This function returns three things: the arithmetic computation itself
26365 // (Value), an EFLAGS result (Overflow), and a condition code (Cond).  The
26366 // flag and the condition code define the case in which the arithmetic
26367 // computation overflows.
26368 static std::pair<SDValue, SDValue>
26369 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
26370   assert(Op.getResNo() == 0 && "Unexpected result number!");
26371   SDValue Value, Overflow;
26372   SDValue LHS = Op.getOperand(0);
26373   SDValue RHS = Op.getOperand(1);
26374   unsigned BaseOp = 0;
26375   SDLoc DL(Op);
26376   switch (Op.getOpcode()) {
26377   default: llvm_unreachable("Unknown ovf instruction!");
26378   case ISD::SADDO:
26379     BaseOp = X86ISD::ADD;
26380     Cond = X86::COND_O;
26381     break;
26382   case ISD::UADDO:
26383     BaseOp = X86ISD::ADD;
26384     Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
26385     break;
26386   case ISD::SSUBO:
26387     BaseOp = X86ISD::SUB;
26388     Cond = X86::COND_O;
26389     break;
26390   case ISD::USUBO:
26391     BaseOp = X86ISD::SUB;
26392     Cond = X86::COND_B;
26393     break;
26394   case ISD::SMULO:
26395     BaseOp = X86ISD::SMUL;
26396     Cond = X86::COND_O;
26397     break;
26398   case ISD::UMULO:
26399     BaseOp = X86ISD::UMUL;
26400     Cond = X86::COND_O;
26401     break;
26402   }
26403 
26404   if (BaseOp) {
26405     // Also sets EFLAGS.
26406     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
26407     Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
26408     Overflow = Value.getValue(1);
26409   }
26410 
26411   return std::make_pair(Value, Overflow);
26412 }
26413 
26414 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
26415   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
26416   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
26417   // looks for this combo and may remove the "setcc" instruction if the "setcc"
26418   // has only one use.
26419   SDLoc DL(Op);
26420   X86::CondCode Cond;
26421   SDValue Value, Overflow;
26422   std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
26423 
26424   SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
26425   assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!");
26426   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
26427 }
26428 
26429 /// Return true if opcode is a X86 logical comparison.
26430 static bool isX86LogicalCmp(SDValue Op) {
26431   unsigned Opc = Op.getOpcode();
26432   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
26433       Opc == X86ISD::FCMP)
26434     return true;
26435   if (Op.getResNo() == 1 &&
26436       (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
26437        Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
26438        Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
26439     return true;
26440 
26441   return false;
26442 }
26443 
26444 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
26445   if (V.getOpcode() != ISD::TRUNCATE)
26446     return false;
26447 
26448   SDValue VOp0 = V.getOperand(0);
26449   unsigned InBits = VOp0.getValueSizeInBits();
26450   unsigned Bits = V.getValueSizeInBits();
26451   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
26452 }
26453 
26454 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
26455   bool AddTest = true;
26456   SDValue Cond  = Op.getOperand(0);
26457   SDValue Op1 = Op.getOperand(1);
26458   SDValue Op2 = Op.getOperand(2);
26459   SDLoc DL(Op);
26460   MVT VT = Op1.getSimpleValueType();
26461   SDValue CC;
26462 
26463   if (isSoftF16(VT, Subtarget)) {
26464     MVT NVT = VT.changeTypeToInteger();
26465     return DAG.getBitcast(VT, DAG.getNode(ISD::SELECT, DL, NVT, Cond,
26466                                           DAG.getBitcast(NVT, Op1),
26467                                           DAG.getBitcast(NVT, Op2)));
26468   }
26469 
26470   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
26471   // are available or VBLENDV if AVX is available.
26472   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
26473   if (Cond.getOpcode() == ISD::SETCC && isScalarFPTypeInSSEReg(VT) &&
26474       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
26475     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
26476     bool IsAlwaysSignaling;
26477     unsigned SSECC =
26478         translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
26479                            CondOp0, CondOp1, IsAlwaysSignaling);
26480 
26481     if (Subtarget.hasAVX512()) {
26482       SDValue Cmp =
26483           DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
26484                       DAG.getTargetConstant(SSECC, DL, MVT::i8));
26485       assert(!VT.isVector() && "Not a scalar type?");
26486       return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
26487     }
26488 
26489     if (SSECC < 8 || Subtarget.hasAVX()) {
26490       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
26491                                 DAG.getTargetConstant(SSECC, DL, MVT::i8));
26492 
26493       // If we have AVX, we can use a variable vector select (VBLENDV) instead
26494       // of 3 logic instructions for size savings and potentially speed.
26495       // Unfortunately, there is no scalar form of VBLENDV.
26496 
26497       // If either operand is a +0.0 constant, don't try this. We can expect to
26498       // optimize away at least one of the logic instructions later in that
26499       // case, so that sequence would be faster than a variable blend.
26500 
26501       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
26502       // uses XMM0 as the selection register. That may need just as many
26503       // instructions as the AND/ANDN/OR sequence due to register moves, so
26504       // don't bother.
26505       if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
26506           !isNullFPConstant(Op2)) {
26507         // Convert to vectors, do a VSELECT, and convert back to scalar.
26508         // All of the conversions should be optimized away.
26509         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
26510         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
26511         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
26512         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
26513 
26514         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
26515         VCmp = DAG.getBitcast(VCmpVT, VCmp);
26516 
26517         SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
26518 
26519         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
26520                            VSel, DAG.getIntPtrConstant(0, DL));
26521       }
26522       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
26523       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
26524       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
26525     }
26526   }
26527 
26528   // AVX512 fallback is to lower selects of scalar floats to masked moves.
26529   if (isScalarFPTypeInSSEReg(VT) && Subtarget.hasAVX512()) {
26530     SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
26531     return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
26532   }
26533 
26534   if (Cond.getOpcode() == ISD::SETCC &&
26535       !isSoftF16(Cond.getOperand(0).getSimpleValueType(), Subtarget)) {
26536     if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
26537       Cond = NewCond;
26538       // If the condition was updated, it's possible that the operands of the
26539       // select were also updated (for example, EmitTest has a RAUW). Refresh
26540       // the local references to the select operands in case they got stale.
26541       Op1 = Op.getOperand(1);
26542       Op2 = Op.getOperand(2);
26543     }
26544   }
26545 
26546   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
26547   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
26548   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
26549   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
26550   // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
26551   // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
26552   // (select (x > 0), x, 0) -> (~(x >> (size_in_bits(x)-1))) & x
26553   // (select (x < 0), x, 0) -> ((x >> (size_in_bits(x)-1))) & x
26554   if (Cond.getOpcode() == X86ISD::SETCC &&
26555       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
26556       isNullConstant(Cond.getOperand(1).getOperand(1))) {
26557     SDValue Cmp = Cond.getOperand(1);
26558     SDValue CmpOp0 = Cmp.getOperand(0);
26559     unsigned CondCode = Cond.getConstantOperandVal(0);
26560 
26561     // Special handling for __builtin_ffs(X) - 1 pattern which looks like
26562     // (select (seteq X, 0), -1, (cttz_zero_undef X)). Disable the special
26563     // handle to keep the CMP with 0. This should be removed by
26564     // optimizeCompareInst by using the flags from the BSR/TZCNT used for the
26565     // cttz_zero_undef.
26566     auto MatchFFSMinus1 = [&](SDValue Op1, SDValue Op2) {
26567       return (Op1.getOpcode() == ISD::CTTZ_ZERO_UNDEF && Op1.hasOneUse() &&
26568               Op1.getOperand(0) == CmpOp0 && isAllOnesConstant(Op2));
26569     };
26570     if (Subtarget.canUseCMOV() && (VT == MVT::i32 || VT == MVT::i64) &&
26571         ((CondCode == X86::COND_NE && MatchFFSMinus1(Op1, Op2)) ||
26572          (CondCode == X86::COND_E && MatchFFSMinus1(Op2, Op1)))) {
26573       // Keep Cmp.
26574     } else if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
26575         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
26576       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
26577       SDVTList CmpVTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
26578 
26579       // 'X - 1' sets the carry flag if X == 0.
26580       // '0 - X' sets the carry flag if X != 0.
26581       // Convert the carry flag to a -1/0 mask with sbb:
26582       // select (X != 0), -1, Y --> 0 - X; or (sbb), Y
26583       // select (X == 0), Y, -1 --> 0 - X; or (sbb), Y
26584       // select (X != 0), Y, -1 --> X - 1; or (sbb), Y
26585       // select (X == 0), -1, Y --> X - 1; or (sbb), Y
26586       SDValue Sub;
26587       if (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE)) {
26588         SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
26589         Sub = DAG.getNode(X86ISD::SUB, DL, CmpVTs, Zero, CmpOp0);
26590       } else {
26591         SDValue One = DAG.getConstant(1, DL, CmpOp0.getValueType());
26592         Sub = DAG.getNode(X86ISD::SUB, DL, CmpVTs, CmpOp0, One);
26593       }
26594       SDValue SBB = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26595                                 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
26596                                 Sub.getValue(1));
26597       return DAG.getNode(ISD::OR, DL, VT, SBB, Y);
26598     } else if (!Subtarget.canUseCMOV() && CondCode == X86::COND_E &&
26599                CmpOp0.getOpcode() == ISD::AND &&
26600                isOneConstant(CmpOp0.getOperand(1))) {
26601       SDValue Src1, Src2;
26602       // true if Op2 is XOR or OR operator and one of its operands
26603       // is equal to Op1
26604       // ( a , a op b) || ( b , a op b)
26605       auto isOrXorPattern = [&]() {
26606         if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
26607             (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
26608           Src1 =
26609               Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
26610           Src2 = Op1;
26611           return true;
26612         }
26613         return false;
26614       };
26615 
26616       if (isOrXorPattern()) {
26617         SDValue Neg;
26618         unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
26619         // we need mask of all zeros or ones with same size of the other
26620         // operands.
26621         if (CmpSz > VT.getSizeInBits())
26622           Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
26623         else if (CmpSz < VT.getSizeInBits())
26624           Neg = DAG.getNode(ISD::AND, DL, VT,
26625               DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
26626               DAG.getConstant(1, DL, VT));
26627         else
26628           Neg = CmpOp0;
26629         SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
26630                                    Neg); // -(and (x, 0x1))
26631         SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
26632         return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2);  // And Op y
26633       }
26634     } else if ((VT == MVT::i32 || VT == MVT::i64) && isNullConstant(Op2) &&
26635                Cmp.getNode()->hasOneUse() && (CmpOp0 == Op1) &&
26636                ((CondCode == X86::COND_S) ||                    // smin(x, 0)
26637                 (CondCode == X86::COND_G && hasAndNot(Op1)))) { // smax(x, 0)
26638       // (select (x < 0), x, 0) -> ((x >> (size_in_bits(x)-1))) & x
26639       //
26640       // If the comparison is testing for a positive value, we have to invert
26641       // the sign bit mask, so only do that transform if the target has a
26642       // bitwise 'and not' instruction (the invert is free).
26643       // (select (x > 0), x, 0) -> (~(x >> (size_in_bits(x)-1))) & x
26644       unsigned ShCt = VT.getSizeInBits() - 1;
26645       SDValue ShiftAmt = DAG.getConstant(ShCt, DL, VT);
26646       SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, Op1, ShiftAmt);
26647       if (CondCode == X86::COND_G)
26648         Shift = DAG.getNOT(DL, Shift, VT);
26649       return DAG.getNode(ISD::AND, DL, VT, Shift, Op1);
26650     }
26651   }
26652 
26653   // Look past (and (setcc_carry (cmp ...)), 1).
26654   if (Cond.getOpcode() == ISD::AND &&
26655       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
26656       isOneConstant(Cond.getOperand(1)))
26657     Cond = Cond.getOperand(0);
26658 
26659   // If condition flag is set by a X86ISD::CMP, then use it as the condition
26660   // setting operand in place of the X86ISD::SETCC.
26661   unsigned CondOpcode = Cond.getOpcode();
26662   if (CondOpcode == X86ISD::SETCC ||
26663       CondOpcode == X86ISD::SETCC_CARRY) {
26664     CC = Cond.getOperand(0);
26665 
26666     SDValue Cmp = Cond.getOperand(1);
26667     bool IllegalFPCMov = false;
26668     if (VT.isFloatingPoint() && !VT.isVector() &&
26669         !isScalarFPTypeInSSEReg(VT) && Subtarget.canUseCMOV())  // FPStack?
26670       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
26671 
26672     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
26673         Cmp.getOpcode() == X86ISD::BT) { // FIXME
26674       Cond = Cmp;
26675       AddTest = false;
26676     }
26677   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
26678              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
26679              CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
26680     SDValue Value;
26681     X86::CondCode X86Cond;
26682     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
26683 
26684     CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
26685     AddTest = false;
26686   }
26687 
26688   if (AddTest) {
26689     // Look past the truncate if the high bits are known zero.
26690     if (isTruncWithZeroHighBitsInput(Cond, DAG))
26691       Cond = Cond.getOperand(0);
26692 
26693     // We know the result of AND is compared against zero. Try to match
26694     // it to BT.
26695     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
26696       X86::CondCode X86CondCode;
26697       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, X86CondCode)) {
26698         CC = DAG.getTargetConstant(X86CondCode, DL, MVT::i8);
26699         Cond = BT;
26700         AddTest = false;
26701       }
26702     }
26703   }
26704 
26705   if (AddTest) {
26706     CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
26707     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
26708   }
26709 
26710   // a <  b ? -1 :  0 -> RES = ~setcc_carry
26711   // a <  b ?  0 : -1 -> RES = setcc_carry
26712   // a >= b ? -1 :  0 -> RES = setcc_carry
26713   // a >= b ?  0 : -1 -> RES = ~setcc_carry
26714   if (Cond.getOpcode() == X86ISD::SUB) {
26715     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
26716 
26717     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
26718         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
26719         (isNullConstant(Op1) || isNullConstant(Op2))) {
26720       SDValue Res =
26721           DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
26722                       DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
26723       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
26724         return DAG.getNOT(DL, Res, Res.getValueType());
26725       return Res;
26726     }
26727   }
26728 
26729   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
26730   // widen the cmov and push the truncate through. This avoids introducing a new
26731   // branch during isel and doesn't add any extensions.
26732   if (Op.getValueType() == MVT::i8 &&
26733       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
26734     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
26735     if (T1.getValueType() == T2.getValueType() &&
26736         // Exclude CopyFromReg to avoid partial register stalls.
26737         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
26738       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
26739                                  CC, Cond);
26740       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
26741     }
26742   }
26743 
26744   // Or finally, promote i8 cmovs if we have CMOV,
26745   //                 or i16 cmovs if it won't prevent folding a load.
26746   // FIXME: we should not limit promotion of i8 case to only when the CMOV is
26747   //        legal, but EmitLoweredSelect() can not deal with these extensions
26748   //        being inserted between two CMOV's. (in i16 case too TBN)
26749   //        https://bugs.llvm.org/show_bug.cgi?id=40974
26750   if ((Op.getValueType() == MVT::i8 && Subtarget.canUseCMOV()) ||
26751       (Op.getValueType() == MVT::i16 && !X86::mayFoldLoad(Op1, Subtarget) &&
26752        !X86::mayFoldLoad(Op2, Subtarget))) {
26753     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
26754     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
26755     SDValue Ops[] = { Op2, Op1, CC, Cond };
26756     SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
26757     return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
26758   }
26759 
26760   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
26761   // condition is true.
26762   SDValue Ops[] = { Op2, Op1, CC, Cond };
26763   return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops, Op->getFlags());
26764 }
26765 
26766 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
26767                                      const X86Subtarget &Subtarget,
26768                                      SelectionDAG &DAG) {
26769   MVT VT = Op->getSimpleValueType(0);
26770   SDValue In = Op->getOperand(0);
26771   MVT InVT = In.getSimpleValueType();
26772   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
26773   MVT VTElt = VT.getVectorElementType();
26774   SDLoc dl(Op);
26775 
26776   unsigned NumElts = VT.getVectorNumElements();
26777 
26778   // Extend VT if the scalar type is i8/i16 and BWI is not supported.
26779   MVT ExtVT = VT;
26780   if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
26781     // If v16i32 is to be avoided, we'll need to split and concatenate.
26782     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
26783       return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
26784 
26785     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
26786   }
26787 
26788   // Widen to 512-bits if VLX is not supported.
26789   MVT WideVT = ExtVT;
26790   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
26791     NumElts *= 512 / ExtVT.getSizeInBits();
26792     InVT = MVT::getVectorVT(MVT::i1, NumElts);
26793     In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
26794                      In, DAG.getIntPtrConstant(0, dl));
26795     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
26796   }
26797 
26798   SDValue V;
26799   MVT WideEltVT = WideVT.getVectorElementType();
26800   if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
26801       (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
26802     V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
26803   } else {
26804     SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
26805     SDValue Zero = DAG.getConstant(0, dl, WideVT);
26806     V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
26807   }
26808 
26809   // Truncate if we had to extend i16/i8 above.
26810   if (VT != ExtVT) {
26811     WideVT = MVT::getVectorVT(VTElt, NumElts);
26812     V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
26813   }
26814 
26815   // Extract back to 128/256-bit if we widened.
26816   if (WideVT != VT)
26817     V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
26818                     DAG.getIntPtrConstant(0, dl));
26819 
26820   return V;
26821 }
26822 
26823 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
26824                                SelectionDAG &DAG) {
26825   SDValue In = Op->getOperand(0);
26826   MVT InVT = In.getSimpleValueType();
26827 
26828   if (InVT.getVectorElementType() == MVT::i1)
26829     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
26830 
26831   assert(Subtarget.hasAVX() && "Expected AVX support");
26832   return LowerAVXExtend(Op, DAG, Subtarget);
26833 }
26834 
26835 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
26836 // For sign extend this needs to handle all vector sizes and SSE4.1 and
26837 // non-SSE4.1 targets. For zero extend this should only handle inputs of
26838 // MVT::v64i8 when BWI is not supported, but AVX512 is.
26839 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
26840                                         const X86Subtarget &Subtarget,
26841                                         SelectionDAG &DAG) {
26842   SDValue In = Op->getOperand(0);
26843   MVT VT = Op->getSimpleValueType(0);
26844   MVT InVT = In.getSimpleValueType();
26845 
26846   MVT SVT = VT.getVectorElementType();
26847   MVT InSVT = InVT.getVectorElementType();
26848   assert(SVT.getFixedSizeInBits() > InSVT.getFixedSizeInBits());
26849 
26850   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
26851     return SDValue();
26852   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
26853     return SDValue();
26854   if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
26855       !(VT.is256BitVector() && Subtarget.hasAVX()) &&
26856       !(VT.is512BitVector() && Subtarget.hasAVX512()))
26857     return SDValue();
26858 
26859   SDLoc dl(Op);
26860   unsigned Opc = Op.getOpcode();
26861   unsigned NumElts = VT.getVectorNumElements();
26862 
26863   // For 256-bit vectors, we only need the lower (128-bit) half of the input.
26864   // For 512-bit vectors, we need 128-bits or 256-bits.
26865   if (InVT.getSizeInBits() > 128) {
26866     // Input needs to be at least the same number of elements as output, and
26867     // at least 128-bits.
26868     int InSize = InSVT.getSizeInBits() * NumElts;
26869     In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
26870     InVT = In.getSimpleValueType();
26871   }
26872 
26873   // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
26874   // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
26875   // need to be handled here for 256/512-bit results.
26876   if (Subtarget.hasInt256()) {
26877     assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
26878 
26879     if (InVT.getVectorNumElements() != NumElts)
26880       return DAG.getNode(Op.getOpcode(), dl, VT, In);
26881 
26882     // FIXME: Apparently we create inreg operations that could be regular
26883     // extends.
26884     unsigned ExtOpc =
26885         Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
26886                                              : ISD::ZERO_EXTEND;
26887     return DAG.getNode(ExtOpc, dl, VT, In);
26888   }
26889 
26890   // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
26891   if (Subtarget.hasAVX()) {
26892     assert(VT.is256BitVector() && "256-bit vector expected");
26893     MVT HalfVT = VT.getHalfNumVectorElementsVT();
26894     int HalfNumElts = HalfVT.getVectorNumElements();
26895 
26896     unsigned NumSrcElts = InVT.getVectorNumElements();
26897     SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
26898     for (int i = 0; i != HalfNumElts; ++i)
26899       HiMask[i] = HalfNumElts + i;
26900 
26901     SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
26902     SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
26903     Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
26904     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
26905   }
26906 
26907   // We should only get here for sign extend.
26908   assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
26909   assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
26910   unsigned InNumElts = InVT.getVectorNumElements();
26911 
26912   // If the source elements are already all-signbits, we don't need to extend,
26913   // just splat the elements.
26914   APInt DemandedElts = APInt::getLowBitsSet(InNumElts, NumElts);
26915   if (DAG.ComputeNumSignBits(In, DemandedElts) == InVT.getScalarSizeInBits()) {
26916     unsigned Scale = InNumElts / NumElts;
26917     SmallVector<int, 16> ShuffleMask;
26918     for (unsigned I = 0; I != NumElts; ++I)
26919       ShuffleMask.append(Scale, I);
26920     return DAG.getBitcast(VT,
26921                           DAG.getVectorShuffle(InVT, dl, In, In, ShuffleMask));
26922   }
26923 
26924   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
26925   SDValue Curr = In;
26926   SDValue SignExt = Curr;
26927 
26928   // As SRAI is only available on i16/i32 types, we expand only up to i32
26929   // and handle i64 separately.
26930   if (InVT != MVT::v4i32) {
26931     MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
26932 
26933     unsigned DestWidth = DestVT.getScalarSizeInBits();
26934     unsigned Scale = DestWidth / InSVT.getSizeInBits();
26935     unsigned DestElts = DestVT.getVectorNumElements();
26936 
26937     // Build a shuffle mask that takes each input element and places it in the
26938     // MSBs of the new element size.
26939     SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
26940     for (unsigned i = 0; i != DestElts; ++i)
26941       Mask[i * Scale + (Scale - 1)] = i;
26942 
26943     Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
26944     Curr = DAG.getBitcast(DestVT, Curr);
26945 
26946     unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
26947     SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
26948                           DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
26949   }
26950 
26951   if (VT == MVT::v2i64) {
26952     assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT");
26953     SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
26954     SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
26955     SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
26956     SignExt = DAG.getBitcast(VT, SignExt);
26957   }
26958 
26959   return SignExt;
26960 }
26961 
26962 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
26963                                 SelectionDAG &DAG) {
26964   MVT VT = Op->getSimpleValueType(0);
26965   SDValue In = Op->getOperand(0);
26966   MVT InVT = In.getSimpleValueType();
26967   SDLoc dl(Op);
26968 
26969   if (InVT.getVectorElementType() == MVT::i1)
26970     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
26971 
26972   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
26973   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
26974          "Expected same number of elements");
26975   assert((VT.getVectorElementType() == MVT::i16 ||
26976           VT.getVectorElementType() == MVT::i32 ||
26977           VT.getVectorElementType() == MVT::i64) &&
26978          "Unexpected element type");
26979   assert((InVT.getVectorElementType() == MVT::i8 ||
26980           InVT.getVectorElementType() == MVT::i16 ||
26981           InVT.getVectorElementType() == MVT::i32) &&
26982          "Unexpected element type");
26983 
26984   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
26985     assert(InVT == MVT::v32i8 && "Unexpected VT!");
26986     return splitVectorIntUnary(Op, DAG);
26987   }
26988 
26989   if (Subtarget.hasInt256())
26990     return Op;
26991 
26992   // Optimize vectors in AVX mode
26993   // Sign extend  v8i16 to v8i32 and
26994   //              v4i32 to v4i64
26995   //
26996   // Divide input vector into two parts
26997   // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
26998   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
26999   // concat the vectors to original VT
27000   MVT HalfVT = VT.getHalfNumVectorElementsVT();
27001   SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
27002 
27003   unsigned NumElems = InVT.getVectorNumElements();
27004   SmallVector<int,8> ShufMask(NumElems, -1);
27005   for (unsigned i = 0; i != NumElems/2; ++i)
27006     ShufMask[i] = i + NumElems/2;
27007 
27008   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
27009   OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
27010 
27011   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
27012 }
27013 
27014 /// Change a vector store into a pair of half-size vector stores.
27015 static SDValue splitVectorStore(StoreSDNode *Store, SelectionDAG &DAG) {
27016   SDValue StoredVal = Store->getValue();
27017   assert((StoredVal.getValueType().is256BitVector() ||
27018           StoredVal.getValueType().is512BitVector()) &&
27019          "Expecting 256/512-bit op");
27020 
27021   // Splitting volatile memory ops is not allowed unless the operation was not
27022   // legal to begin with. Assume the input store is legal (this transform is
27023   // only used for targets with AVX). Note: It is possible that we have an
27024   // illegal type like v2i128, and so we could allow splitting a volatile store
27025   // in that case if that is important.
27026   if (!Store->isSimple())
27027     return SDValue();
27028 
27029   SDLoc DL(Store);
27030   SDValue Value0, Value1;
27031   std::tie(Value0, Value1) = splitVector(StoredVal, DAG, DL);
27032   unsigned HalfOffset = Value0.getValueType().getStoreSize();
27033   SDValue Ptr0 = Store->getBasePtr();
27034   SDValue Ptr1 =
27035       DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(HalfOffset), DL);
27036   SDValue Ch0 =
27037       DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
27038                    Store->getOriginalAlign(),
27039                    Store->getMemOperand()->getFlags());
27040   SDValue Ch1 = DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
27041                              Store->getPointerInfo().getWithOffset(HalfOffset),
27042                              Store->getOriginalAlign(),
27043                              Store->getMemOperand()->getFlags());
27044   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
27045 }
27046 
27047 /// Scalarize a vector store, bitcasting to TargetVT to determine the scalar
27048 /// type.
27049 static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT,
27050                                     SelectionDAG &DAG) {
27051   SDValue StoredVal = Store->getValue();
27052   assert(StoreVT.is128BitVector() &&
27053          StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op");
27054   StoredVal = DAG.getBitcast(StoreVT, StoredVal);
27055 
27056   // Splitting volatile memory ops is not allowed unless the operation was not
27057   // legal to begin with. We are assuming the input op is legal (this transform
27058   // is only used for targets with AVX).
27059   if (!Store->isSimple())
27060     return SDValue();
27061 
27062   MVT StoreSVT = StoreVT.getScalarType();
27063   unsigned NumElems = StoreVT.getVectorNumElements();
27064   unsigned ScalarSize = StoreSVT.getStoreSize();
27065 
27066   SDLoc DL(Store);
27067   SmallVector<SDValue, 4> Stores;
27068   for (unsigned i = 0; i != NumElems; ++i) {
27069     unsigned Offset = i * ScalarSize;
27070     SDValue Ptr = DAG.getMemBasePlusOffset(Store->getBasePtr(),
27071                                            TypeSize::Fixed(Offset), DL);
27072     SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreSVT, StoredVal,
27073                               DAG.getIntPtrConstant(i, DL));
27074     SDValue Ch = DAG.getStore(Store->getChain(), DL, Scl, Ptr,
27075                               Store->getPointerInfo().getWithOffset(Offset),
27076                               Store->getOriginalAlign(),
27077                               Store->getMemOperand()->getFlags());
27078     Stores.push_back(Ch);
27079   }
27080   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
27081 }
27082 
27083 static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
27084                           SelectionDAG &DAG) {
27085   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
27086   SDLoc dl(St);
27087   SDValue StoredVal = St->getValue();
27088 
27089   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
27090   if (StoredVal.getValueType().isVector() &&
27091       StoredVal.getValueType().getVectorElementType() == MVT::i1) {
27092     unsigned NumElts = StoredVal.getValueType().getVectorNumElements();
27093     assert(NumElts <= 8 && "Unexpected VT");
27094     assert(!St->isTruncatingStore() && "Expected non-truncating store");
27095     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
27096            "Expected AVX512F without AVX512DQI");
27097 
27098     // We must pad with zeros to ensure we store zeroes to any unused bits.
27099     StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
27100                             DAG.getUNDEF(MVT::v16i1), StoredVal,
27101                             DAG.getIntPtrConstant(0, dl));
27102     StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
27103     StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
27104     // Make sure we store zeros in the extra bits.
27105     if (NumElts < 8)
27106       StoredVal = DAG.getZeroExtendInReg(
27107           StoredVal, dl, EVT::getIntegerVT(*DAG.getContext(), NumElts));
27108 
27109     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
27110                         St->getPointerInfo(), St->getOriginalAlign(),
27111                         St->getMemOperand()->getFlags());
27112   }
27113 
27114   if (St->isTruncatingStore())
27115     return SDValue();
27116 
27117   // If this is a 256-bit store of concatenated ops, we are better off splitting
27118   // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
27119   // and each half can execute independently. Some cores would split the op into
27120   // halves anyway, so the concat (vinsertf128) is purely an extra op.
27121   MVT StoreVT = StoredVal.getSimpleValueType();
27122   if (StoreVT.is256BitVector() ||
27123       ((StoreVT == MVT::v32i16 || StoreVT == MVT::v64i8) &&
27124        !Subtarget.hasBWI())) {
27125     if (StoredVal.hasOneUse() && isFreeToSplitVector(StoredVal.getNode(), DAG))
27126       return splitVectorStore(St, DAG);
27127     return SDValue();
27128   }
27129 
27130   if (StoreVT.is32BitVector())
27131     return SDValue();
27132 
27133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27134   assert(StoreVT.is64BitVector() && "Unexpected VT");
27135   assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==
27136              TargetLowering::TypeWidenVector &&
27137          "Unexpected type action!");
27138 
27139   EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
27140   StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
27141                           DAG.getUNDEF(StoreVT));
27142 
27143   if (Subtarget.hasSSE2()) {
27144     // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
27145     // and store it.
27146     MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
27147     MVT CastVT = MVT::getVectorVT(StVT, 2);
27148     StoredVal = DAG.getBitcast(CastVT, StoredVal);
27149     StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
27150                             DAG.getIntPtrConstant(0, dl));
27151 
27152     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
27153                         St->getPointerInfo(), St->getOriginalAlign(),
27154                         St->getMemOperand()->getFlags());
27155   }
27156   assert(Subtarget.hasSSE1() && "Expected SSE");
27157   SDVTList Tys = DAG.getVTList(MVT::Other);
27158   SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
27159   return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
27160                                  St->getMemOperand());
27161 }
27162 
27163 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
27164 // may emit an illegal shuffle but the expansion is still better than scalar
27165 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
27166 // we'll emit a shuffle and a arithmetic shift.
27167 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
27168 // TODO: It is possible to support ZExt by zeroing the undef values during
27169 // the shuffle phase or after the shuffle.
27170 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
27171                                  SelectionDAG &DAG) {
27172   MVT RegVT = Op.getSimpleValueType();
27173   assert(RegVT.isVector() && "We only custom lower vector loads.");
27174   assert(RegVT.isInteger() &&
27175          "We only custom lower integer vector loads.");
27176 
27177   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
27178   SDLoc dl(Ld);
27179 
27180   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
27181   if (RegVT.getVectorElementType() == MVT::i1) {
27182     assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load");
27183     assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
27184     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
27185            "Expected AVX512F without AVX512DQI");
27186 
27187     SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
27188                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
27189                                 Ld->getMemOperand()->getFlags());
27190 
27191     // Replace chain users with the new chain.
27192     assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
27193 
27194     SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
27195     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
27196                       DAG.getBitcast(MVT::v16i1, Val),
27197                       DAG.getIntPtrConstant(0, dl));
27198     return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
27199   }
27200 
27201   return SDValue();
27202 }
27203 
27204 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
27205 /// each of which has no other use apart from the AND / OR.
27206 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
27207   Opc = Op.getOpcode();
27208   if (Opc != ISD::OR && Opc != ISD::AND)
27209     return false;
27210   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
27211           Op.getOperand(0).hasOneUse() &&
27212           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
27213           Op.getOperand(1).hasOneUse());
27214 }
27215 
27216 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
27217   SDValue Chain = Op.getOperand(0);
27218   SDValue Cond  = Op.getOperand(1);
27219   SDValue Dest  = Op.getOperand(2);
27220   SDLoc dl(Op);
27221 
27222   // Bail out when we don't have native compare instructions.
27223   if (Cond.getOpcode() == ISD::SETCC &&
27224       Cond.getOperand(0).getValueType() != MVT::f128 &&
27225       !isSoftF16(Cond.getOperand(0).getValueType(), Subtarget)) {
27226     SDValue LHS = Cond.getOperand(0);
27227     SDValue RHS = Cond.getOperand(1);
27228     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
27229 
27230     // Special case for
27231     // setcc([su]{add,sub,mul}o == 0)
27232     // setcc([su]{add,sub,mul}o != 1)
27233     if (ISD::isOverflowIntrOpRes(LHS) &&
27234         (CC == ISD::SETEQ || CC == ISD::SETNE) &&
27235         (isNullConstant(RHS) || isOneConstant(RHS))) {
27236       SDValue Value, Overflow;
27237       X86::CondCode X86Cond;
27238       std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, LHS.getValue(0), DAG);
27239 
27240       if ((CC == ISD::SETEQ) == isNullConstant(RHS))
27241         X86Cond = X86::GetOppositeBranchCondition(X86Cond);
27242 
27243       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
27244       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
27245                          Overflow);
27246     }
27247 
27248     if (LHS.getSimpleValueType().isInteger()) {
27249       SDValue CCVal;
27250       SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, CC, SDLoc(Cond), DAG, CCVal);
27251       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
27252                          EFLAGS);
27253     }
27254 
27255     if (CC == ISD::SETOEQ) {
27256       // For FCMP_OEQ, we can emit
27257       // two branches instead of an explicit AND instruction with a
27258       // separate test. However, we only do this if this block doesn't
27259       // have a fall-through edge, because this requires an explicit
27260       // jmp when the condition is false.
27261       if (Op.getNode()->hasOneUse()) {
27262         SDNode *User = *Op.getNode()->use_begin();
27263         // Look for an unconditional branch following this conditional branch.
27264         // We need this because we need to reverse the successors in order
27265         // to implement FCMP_OEQ.
27266         if (User->getOpcode() == ISD::BR) {
27267           SDValue FalseBB = User->getOperand(1);
27268           SDNode *NewBR =
27269             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
27270           assert(NewBR == User);
27271           (void)NewBR;
27272           Dest = FalseBB;
27273 
27274           SDValue Cmp =
27275               DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
27276           SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
27277           Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest,
27278                               CCVal, Cmp);
27279           CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
27280           return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
27281                              Cmp);
27282         }
27283       }
27284     } else if (CC == ISD::SETUNE) {
27285       // For FCMP_UNE, we can emit
27286       // two branches instead of an explicit OR instruction with a
27287       // separate test.
27288       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
27289       SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
27290       Chain =
27291           DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Cmp);
27292       CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
27293       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
27294                          Cmp);
27295     } else {
27296       X86::CondCode X86Cond =
27297           TranslateX86CC(CC, dl, /*IsFP*/ true, LHS, RHS, DAG);
27298       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
27299       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
27300       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
27301                          Cmp);
27302     }
27303   }
27304 
27305   if (ISD::isOverflowIntrOpRes(Cond)) {
27306     SDValue Value, Overflow;
27307     X86::CondCode X86Cond;
27308     std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
27309 
27310     SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
27311     return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
27312                        Overflow);
27313   }
27314 
27315   // Look past the truncate if the high bits are known zero.
27316   if (isTruncWithZeroHighBitsInput(Cond, DAG))
27317     Cond = Cond.getOperand(0);
27318 
27319   EVT CondVT = Cond.getValueType();
27320 
27321   // Add an AND with 1 if we don't already have one.
27322   if (!(Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1))))
27323     Cond =
27324         DAG.getNode(ISD::AND, dl, CondVT, Cond, DAG.getConstant(1, dl, CondVT));
27325 
27326   SDValue LHS = Cond;
27327   SDValue RHS = DAG.getConstant(0, dl, CondVT);
27328 
27329   SDValue CCVal;
27330   SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, ISD::SETNE, dl, DAG, CCVal);
27331   return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
27332                      EFLAGS);
27333 }
27334 
27335 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
27336 // Calls to _alloca are needed to probe the stack when allocating more than 4k
27337 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
27338 // that the guard pages used by the OS virtual memory manager are allocated in
27339 // correct sequence.
27340 SDValue
27341 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
27342                                            SelectionDAG &DAG) const {
27343   MachineFunction &MF = DAG.getMachineFunction();
27344   bool SplitStack = MF.shouldSplitStack();
27345   bool EmitStackProbeCall = hasStackProbeSymbol(MF);
27346   bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
27347                SplitStack || EmitStackProbeCall;
27348   SDLoc dl(Op);
27349 
27350   // Get the inputs.
27351   SDNode *Node = Op.getNode();
27352   SDValue Chain = Op.getOperand(0);
27353   SDValue Size  = Op.getOperand(1);
27354   MaybeAlign Alignment(Op.getConstantOperandVal(2));
27355   EVT VT = Node->getValueType(0);
27356 
27357   // Chain the dynamic stack allocation so that it doesn't modify the stack
27358   // pointer when other instructions are using the stack.
27359   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
27360 
27361   bool Is64Bit = Subtarget.is64Bit();
27362   MVT SPTy = getPointerTy(DAG.getDataLayout());
27363 
27364   SDValue Result;
27365   if (!Lower) {
27366     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27367     Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
27368     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
27369                     " not tell us which reg is the stack pointer!");
27370 
27371     const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
27372     const Align StackAlign = TFI.getStackAlign();
27373     if (hasInlineStackProbe(MF)) {
27374       MachineRegisterInfo &MRI = MF.getRegInfo();
27375 
27376       const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
27377       Register Vreg = MRI.createVirtualRegister(AddrRegClass);
27378       Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
27379       Result = DAG.getNode(X86ISD::PROBED_ALLOCA, dl, SPTy, Chain,
27380                            DAG.getRegister(Vreg, SPTy));
27381     } else {
27382       SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
27383       Chain = SP.getValue(1);
27384       Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
27385     }
27386     if (Alignment && *Alignment > StackAlign)
27387       Result =
27388           DAG.getNode(ISD::AND, dl, VT, Result,
27389                       DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
27390     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
27391   } else if (SplitStack) {
27392     MachineRegisterInfo &MRI = MF.getRegInfo();
27393 
27394     if (Is64Bit) {
27395       // The 64 bit implementation of segmented stacks needs to clobber both r10
27396       // r11. This makes it impossible to use it along with nested parameters.
27397       const Function &F = MF.getFunction();
27398       for (const auto &A : F.args()) {
27399         if (A.hasNestAttr())
27400           report_fatal_error("Cannot use segmented stacks with functions that "
27401                              "have nested arguments.");
27402       }
27403     }
27404 
27405     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
27406     Register Vreg = MRI.createVirtualRegister(AddrRegClass);
27407     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
27408     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
27409                                 DAG.getRegister(Vreg, SPTy));
27410   } else {
27411     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
27412     Chain = DAG.getNode(X86ISD::DYN_ALLOCA, dl, NodeTys, Chain, Size);
27413     MF.getInfo<X86MachineFunctionInfo>()->setHasDynAlloca(true);
27414 
27415     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27416     Register SPReg = RegInfo->getStackRegister();
27417     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
27418     Chain = SP.getValue(1);
27419 
27420     if (Alignment) {
27421       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
27422                        DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
27423       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
27424     }
27425 
27426     Result = SP;
27427   }
27428 
27429   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
27430 
27431   SDValue Ops[2] = {Result, Chain};
27432   return DAG.getMergeValues(Ops, dl);
27433 }
27434 
27435 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
27436   MachineFunction &MF = DAG.getMachineFunction();
27437   auto PtrVT = getPointerTy(MF.getDataLayout());
27438   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
27439 
27440   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
27441   SDLoc DL(Op);
27442 
27443   if (!Subtarget.is64Bit() ||
27444       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
27445     // vastart just stores the address of the VarArgsFrameIndex slot into the
27446     // memory location argument.
27447     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
27448     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
27449                         MachinePointerInfo(SV));
27450   }
27451 
27452   // __va_list_tag:
27453   //   gp_offset         (0 - 6 * 8)
27454   //   fp_offset         (48 - 48 + 8 * 16)
27455   //   overflow_arg_area (point to parameters coming in memory).
27456   //   reg_save_area
27457   SmallVector<SDValue, 8> MemOps;
27458   SDValue FIN = Op.getOperand(1);
27459   // Store gp_offset
27460   SDValue Store = DAG.getStore(
27461       Op.getOperand(0), DL,
27462       DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
27463       MachinePointerInfo(SV));
27464   MemOps.push_back(Store);
27465 
27466   // Store fp_offset
27467   FIN = DAG.getMemBasePlusOffset(FIN, TypeSize::Fixed(4), DL);
27468   Store = DAG.getStore(
27469       Op.getOperand(0), DL,
27470       DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
27471       MachinePointerInfo(SV, 4));
27472   MemOps.push_back(Store);
27473 
27474   // Store ptr to overflow_arg_area
27475   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
27476   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
27477   Store =
27478       DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
27479   MemOps.push_back(Store);
27480 
27481   // Store ptr to reg_save_area.
27482   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
27483       Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
27484   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
27485   Store = DAG.getStore(
27486       Op.getOperand(0), DL, RSFIN, FIN,
27487       MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
27488   MemOps.push_back(Store);
27489   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
27490 }
27491 
27492 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
27493   assert(Subtarget.is64Bit() &&
27494          "LowerVAARG only handles 64-bit va_arg!");
27495   assert(Op.getNumOperands() == 4);
27496 
27497   MachineFunction &MF = DAG.getMachineFunction();
27498   if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
27499     // The Win64 ABI uses char* instead of a structure.
27500     return DAG.expandVAArg(Op.getNode());
27501 
27502   SDValue Chain = Op.getOperand(0);
27503   SDValue SrcPtr = Op.getOperand(1);
27504   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
27505   unsigned Align = Op.getConstantOperandVal(3);
27506   SDLoc dl(Op);
27507 
27508   EVT ArgVT = Op.getNode()->getValueType(0);
27509   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
27510   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
27511   uint8_t ArgMode;
27512 
27513   // Decide which area this value should be read from.
27514   // TODO: Implement the AMD64 ABI in its entirety. This simple
27515   // selection mechanism works only for the basic types.
27516   assert(ArgVT != MVT::f80 && "va_arg for f80 not yet implemented");
27517   if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
27518     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
27519   } else {
27520     assert(ArgVT.isInteger() && ArgSize <= 32 /*bytes*/ &&
27521            "Unhandled argument type in LowerVAARG");
27522     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
27523   }
27524 
27525   if (ArgMode == 2) {
27526     // Make sure using fp_offset makes sense.
27527     assert(!Subtarget.useSoftFloat() &&
27528            !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
27529            Subtarget.hasSSE1());
27530   }
27531 
27532   // Insert VAARG node into the DAG
27533   // VAARG returns two values: Variable Argument Address, Chain
27534   SDValue InstOps[] = {Chain, SrcPtr,
27535                        DAG.getTargetConstant(ArgSize, dl, MVT::i32),
27536                        DAG.getTargetConstant(ArgMode, dl, MVT::i8),
27537                        DAG.getTargetConstant(Align, dl, MVT::i32)};
27538   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
27539   SDValue VAARG = DAG.getMemIntrinsicNode(
27540       Subtarget.isTarget64BitLP64() ? X86ISD::VAARG_64 : X86ISD::VAARG_X32, dl,
27541       VTs, InstOps, MVT::i64, MachinePointerInfo(SV),
27542       /*Alignment=*/std::nullopt,
27543       MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
27544   Chain = VAARG.getValue(1);
27545 
27546   // Load the next argument and return it
27547   return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
27548 }
27549 
27550 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
27551                            SelectionDAG &DAG) {
27552   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
27553   // where a va_list is still an i8*.
27554   assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
27555   if (Subtarget.isCallingConvWin64(
27556         DAG.getMachineFunction().getFunction().getCallingConv()))
27557     // Probably a Win64 va_copy.
27558     return DAG.expandVACopy(Op.getNode());
27559 
27560   SDValue Chain = Op.getOperand(0);
27561   SDValue DstPtr = Op.getOperand(1);
27562   SDValue SrcPtr = Op.getOperand(2);
27563   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
27564   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
27565   SDLoc DL(Op);
27566 
27567   return DAG.getMemcpy(
27568       Chain, DL, DstPtr, SrcPtr,
27569       DAG.getIntPtrConstant(Subtarget.isTarget64BitLP64() ? 24 : 16, DL),
27570       Align(Subtarget.isTarget64BitLP64() ? 8 : 4), /*isVolatile*/ false, false,
27571       false, MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
27572 }
27573 
27574 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
27575 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
27576   switch (Opc) {
27577   case ISD::SHL:
27578   case X86ISD::VSHL:
27579   case X86ISD::VSHLI:
27580     return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
27581   case ISD::SRL:
27582   case X86ISD::VSRL:
27583   case X86ISD::VSRLI:
27584     return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
27585   case ISD::SRA:
27586   case X86ISD::VSRA:
27587   case X86ISD::VSRAI:
27588     return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
27589   }
27590   llvm_unreachable("Unknown target vector shift node");
27591 }
27592 
27593 /// Handle vector element shifts where the shift amount is a constant.
27594 /// Takes immediate version of shift as input.
27595 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
27596                                           SDValue SrcOp, uint64_t ShiftAmt,
27597                                           SelectionDAG &DAG) {
27598   MVT ElementType = VT.getVectorElementType();
27599 
27600   // Bitcast the source vector to the output type, this is mainly necessary for
27601   // vXi8/vXi64 shifts.
27602   if (VT != SrcOp.getSimpleValueType())
27603     SrcOp = DAG.getBitcast(VT, SrcOp);
27604 
27605   // Fold this packed shift into its first operand if ShiftAmt is 0.
27606   if (ShiftAmt == 0)
27607     return SrcOp;
27608 
27609   // Check for ShiftAmt >= element width
27610   if (ShiftAmt >= ElementType.getSizeInBits()) {
27611     if (Opc == X86ISD::VSRAI)
27612       ShiftAmt = ElementType.getSizeInBits() - 1;
27613     else
27614       return DAG.getConstant(0, dl, VT);
27615   }
27616 
27617   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
27618          && "Unknown target vector shift-by-constant node");
27619 
27620   // Fold this packed vector shift into a build vector if SrcOp is a
27621   // vector of Constants or UNDEFs.
27622   if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
27623     unsigned ShiftOpc;
27624     switch (Opc) {
27625     default: llvm_unreachable("Unknown opcode!");
27626     case X86ISD::VSHLI:
27627       ShiftOpc = ISD::SHL;
27628       break;
27629     case X86ISD::VSRLI:
27630       ShiftOpc = ISD::SRL;
27631       break;
27632     case X86ISD::VSRAI:
27633       ShiftOpc = ISD::SRA;
27634       break;
27635     }
27636 
27637     SDValue Amt = DAG.getConstant(ShiftAmt, dl, VT);
27638     if (SDValue C = DAG.FoldConstantArithmetic(ShiftOpc, dl, VT, {SrcOp, Amt}))
27639       return C;
27640   }
27641 
27642   return DAG.getNode(Opc, dl, VT, SrcOp,
27643                      DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
27644 }
27645 
27646 /// Handle vector element shifts by a splat shift amount
27647 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
27648                                    SDValue SrcOp, SDValue ShAmt, int ShAmtIdx,
27649                                    const X86Subtarget &Subtarget,
27650                                    SelectionDAG &DAG) {
27651   MVT AmtVT = ShAmt.getSimpleValueType();
27652   assert(AmtVT.isVector() && "Vector shift type mismatch");
27653   assert(0 <= ShAmtIdx && ShAmtIdx < (int)AmtVT.getVectorNumElements() &&
27654          "Illegal vector splat index");
27655 
27656   // Move the splat element to the bottom element.
27657   if (ShAmtIdx != 0) {
27658     SmallVector<int> Mask(AmtVT.getVectorNumElements(), -1);
27659     Mask[0] = ShAmtIdx;
27660     ShAmt = DAG.getVectorShuffle(AmtVT, dl, ShAmt, DAG.getUNDEF(AmtVT), Mask);
27661   }
27662 
27663   // Peek through any zext node if we can get back to a 128-bit source.
27664   if (AmtVT.getScalarSizeInBits() == 64 &&
27665       (ShAmt.getOpcode() == ISD::ZERO_EXTEND ||
27666        ShAmt.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
27667       ShAmt.getOperand(0).getValueType().isSimple() &&
27668       ShAmt.getOperand(0).getValueType().is128BitVector()) {
27669     ShAmt = ShAmt.getOperand(0);
27670     AmtVT = ShAmt.getSimpleValueType();
27671   }
27672 
27673   // See if we can mask off the upper elements using the existing source node.
27674   // The shift uses the entire lower 64-bits of the amount vector, so no need to
27675   // do this for vXi64 types.
27676   bool IsMasked = false;
27677   if (AmtVT.getScalarSizeInBits() < 64) {
27678     if (ShAmt.getOpcode() == ISD::BUILD_VECTOR ||
27679         ShAmt.getOpcode() == ISD::SCALAR_TO_VECTOR) {
27680       // If the shift amount has come from a scalar, then zero-extend the scalar
27681       // before moving to the vector.
27682       ShAmt = DAG.getZExtOrTrunc(ShAmt.getOperand(0), dl, MVT::i32);
27683       ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
27684       ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, ShAmt);
27685       AmtVT = MVT::v4i32;
27686       IsMasked = true;
27687     } else if (ShAmt.getOpcode() == ISD::AND) {
27688       // See if the shift amount is already masked (e.g. for rotation modulo),
27689       // then we can zero-extend it by setting all the other mask elements to
27690       // zero.
27691       SmallVector<SDValue> MaskElts(
27692           AmtVT.getVectorNumElements(),
27693           DAG.getConstant(0, dl, AmtVT.getScalarType()));
27694       MaskElts[0] = DAG.getAllOnesConstant(dl, AmtVT.getScalarType());
27695       SDValue Mask = DAG.getBuildVector(AmtVT, dl, MaskElts);
27696       if ((Mask = DAG.FoldConstantArithmetic(ISD::AND, dl, AmtVT,
27697                                              {ShAmt.getOperand(1), Mask}))) {
27698         ShAmt = DAG.getNode(ISD::AND, dl, AmtVT, ShAmt.getOperand(0), Mask);
27699         IsMasked = true;
27700       }
27701     }
27702   }
27703 
27704   // Extract if the shift amount vector is larger than 128-bits.
27705   if (AmtVT.getSizeInBits() > 128) {
27706     ShAmt = extract128BitVector(ShAmt, 0, DAG, dl);
27707     AmtVT = ShAmt.getSimpleValueType();
27708   }
27709 
27710   // Zero-extend bottom element to v2i64 vector type, either by extension or
27711   // shuffle masking.
27712   if (!IsMasked && AmtVT.getScalarSizeInBits() < 64) {
27713     if (AmtVT == MVT::v4i32 && (ShAmt.getOpcode() == X86ISD::VBROADCAST ||
27714                                 ShAmt.getOpcode() == X86ISD::VBROADCAST_LOAD)) {
27715       ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, SDLoc(ShAmt), MVT::v4i32, ShAmt);
27716     } else if (Subtarget.hasSSE41()) {
27717       ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
27718                           MVT::v2i64, ShAmt);
27719     } else {
27720       SDValue ByteShift = DAG.getTargetConstant(
27721           (128 - AmtVT.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
27722       ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
27723       ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
27724                           ByteShift);
27725       ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
27726                           ByteShift);
27727     }
27728   }
27729 
27730   // Change opcode to non-immediate version.
27731   Opc = getTargetVShiftUniformOpcode(Opc, true);
27732 
27733   // The return type has to be a 128-bit type with the same element
27734   // type as the input type.
27735   MVT EltVT = VT.getVectorElementType();
27736   MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
27737 
27738   ShAmt = DAG.getBitcast(ShVT, ShAmt);
27739   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
27740 }
27741 
27742 /// Return Mask with the necessary casting or extending
27743 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
27744 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
27745                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
27746                            const SDLoc &dl) {
27747 
27748   if (isAllOnesConstant(Mask))
27749     return DAG.getConstant(1, dl, MaskVT);
27750   if (X86::isZeroNode(Mask))
27751     return DAG.getConstant(0, dl, MaskVT);
27752 
27753   assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
27754 
27755   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
27756     assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
27757     assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
27758     // In case 32bit mode, bitcast i64 is illegal, extend/split it.
27759     SDValue Lo, Hi;
27760     std::tie(Lo, Hi) = DAG.SplitScalar(Mask, dl, MVT::i32, MVT::i32);
27761     Lo = DAG.getBitcast(MVT::v32i1, Lo);
27762     Hi = DAG.getBitcast(MVT::v32i1, Hi);
27763     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
27764   } else {
27765     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
27766                                      Mask.getSimpleValueType().getSizeInBits());
27767     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
27768     // are extracted by EXTRACT_SUBVECTOR.
27769     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
27770                        DAG.getBitcast(BitcastVT, Mask),
27771                        DAG.getIntPtrConstant(0, dl));
27772   }
27773 }
27774 
27775 /// Return (and \p Op, \p Mask) for compare instructions or
27776 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
27777 /// necessary casting or extending for \p Mask when lowering masking intrinsics
27778 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
27779                                     SDValue PreservedSrc,
27780                                     const X86Subtarget &Subtarget,
27781                                     SelectionDAG &DAG) {
27782   MVT VT = Op.getSimpleValueType();
27783   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
27784   unsigned OpcodeSelect = ISD::VSELECT;
27785   SDLoc dl(Op);
27786 
27787   if (isAllOnesConstant(Mask))
27788     return Op;
27789 
27790   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27791 
27792   if (PreservedSrc.isUndef())
27793     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
27794   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
27795 }
27796 
27797 /// Creates an SDNode for a predicated scalar operation.
27798 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
27799 /// The mask is coming as MVT::i8 and it should be transformed
27800 /// to MVT::v1i1 while lowering masking intrinsics.
27801 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
27802 /// "X86select" instead of "vselect". We just can't create the "vselect" node
27803 /// for a scalar instruction.
27804 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
27805                                     SDValue PreservedSrc,
27806                                     const X86Subtarget &Subtarget,
27807                                     SelectionDAG &DAG) {
27808 
27809   if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
27810     if (MaskConst->getZExtValue() & 0x1)
27811       return Op;
27812 
27813   MVT VT = Op.getSimpleValueType();
27814   SDLoc dl(Op);
27815 
27816   assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
27817   SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
27818                               DAG.getBitcast(MVT::v8i1, Mask),
27819                               DAG.getIntPtrConstant(0, dl));
27820   if (Op.getOpcode() == X86ISD::FSETCCM ||
27821       Op.getOpcode() == X86ISD::FSETCCM_SAE ||
27822       Op.getOpcode() == X86ISD::VFPCLASSS)
27823     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
27824 
27825   if (PreservedSrc.isUndef())
27826     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
27827   return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
27828 }
27829 
27830 static int getSEHRegistrationNodeSize(const Function *Fn) {
27831   if (!Fn->hasPersonalityFn())
27832     report_fatal_error(
27833         "querying registration node size for function without personality");
27834   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
27835   // WinEHStatePass for the full struct definition.
27836   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
27837   case EHPersonality::MSVC_X86SEH: return 24;
27838   case EHPersonality::MSVC_CXX: return 16;
27839   default: break;
27840   }
27841   report_fatal_error(
27842       "can only recover FP for 32-bit MSVC EH personality functions");
27843 }
27844 
27845 /// When the MSVC runtime transfers control to us, either to an outlined
27846 /// function or when returning to a parent frame after catching an exception, we
27847 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
27848 /// Here's the math:
27849 ///   RegNodeBase = EntryEBP - RegNodeSize
27850 ///   ParentFP = RegNodeBase - ParentFrameOffset
27851 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
27852 /// subtracting the offset (negative on x86) takes us back to the parent FP.
27853 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
27854                                    SDValue EntryEBP) {
27855   MachineFunction &MF = DAG.getMachineFunction();
27856   SDLoc dl;
27857 
27858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27859   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
27860 
27861   // It's possible that the parent function no longer has a personality function
27862   // if the exceptional code was optimized away, in which case we just return
27863   // the incoming EBP.
27864   if (!Fn->hasPersonalityFn())
27865     return EntryEBP;
27866 
27867   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
27868   // registration, or the .set_setframe offset.
27869   MCSymbol *OffsetSym =
27870       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
27871           GlobalValue::dropLLVMManglingEscape(Fn->getName()));
27872   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
27873   SDValue ParentFrameOffset =
27874       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
27875 
27876   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
27877   // prologue to RBP in the parent function.
27878   const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
27879   if (Subtarget.is64Bit())
27880     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
27881 
27882   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
27883   // RegNodeBase = EntryEBP - RegNodeSize
27884   // ParentFP = RegNodeBase - ParentFrameOffset
27885   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
27886                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
27887   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
27888 }
27889 
27890 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
27891                                                    SelectionDAG &DAG) const {
27892   // Helper to detect if the operand is CUR_DIRECTION rounding mode.
27893   auto isRoundModeCurDirection = [](SDValue Rnd) {
27894     if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
27895       return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
27896 
27897     return false;
27898   };
27899   auto isRoundModeSAE = [](SDValue Rnd) {
27900     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
27901       unsigned RC = C->getZExtValue();
27902       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
27903         // Clear the NO_EXC bit and check remaining bits.
27904         RC ^= X86::STATIC_ROUNDING::NO_EXC;
27905         // As a convenience we allow no other bits or explicitly
27906         // current direction.
27907         return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
27908       }
27909     }
27910 
27911     return false;
27912   };
27913   auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
27914     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
27915       RC = C->getZExtValue();
27916       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
27917         // Clear the NO_EXC bit and check remaining bits.
27918         RC ^= X86::STATIC_ROUNDING::NO_EXC;
27919         return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
27920                RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
27921                RC == X86::STATIC_ROUNDING::TO_POS_INF ||
27922                RC == X86::STATIC_ROUNDING::TO_ZERO;
27923       }
27924     }
27925 
27926     return false;
27927   };
27928 
27929   SDLoc dl(Op);
27930   unsigned IntNo = Op.getConstantOperandVal(0);
27931   MVT VT = Op.getSimpleValueType();
27932   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
27933 
27934   // Propagate flags from original node to transformed node(s).
27935   SelectionDAG::FlagInserter FlagsInserter(DAG, Op->getFlags());
27936 
27937   if (IntrData) {
27938     switch(IntrData->Type) {
27939     case INTR_TYPE_1OP: {
27940       // We specify 2 possible opcodes for intrinsics with rounding modes.
27941       // First, we check if the intrinsic may have non-default rounding mode,
27942       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
27943       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
27944       if (IntrWithRoundingModeOpcode != 0) {
27945         SDValue Rnd = Op.getOperand(2);
27946         unsigned RC = 0;
27947         if (isRoundModeSAEToX(Rnd, RC))
27948           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
27949                              Op.getOperand(1),
27950                              DAG.getTargetConstant(RC, dl, MVT::i32));
27951         if (!isRoundModeCurDirection(Rnd))
27952           return SDValue();
27953       }
27954       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
27955                          Op.getOperand(1));
27956     }
27957     case INTR_TYPE_1OP_SAE: {
27958       SDValue Sae = Op.getOperand(2);
27959 
27960       unsigned Opc;
27961       if (isRoundModeCurDirection(Sae))
27962         Opc = IntrData->Opc0;
27963       else if (isRoundModeSAE(Sae))
27964         Opc = IntrData->Opc1;
27965       else
27966         return SDValue();
27967 
27968       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
27969     }
27970     case INTR_TYPE_2OP: {
27971       SDValue Src2 = Op.getOperand(2);
27972 
27973       // We specify 2 possible opcodes for intrinsics with rounding modes.
27974       // First, we check if the intrinsic may have non-default rounding mode,
27975       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
27976       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
27977       if (IntrWithRoundingModeOpcode != 0) {
27978         SDValue Rnd = Op.getOperand(3);
27979         unsigned RC = 0;
27980         if (isRoundModeSAEToX(Rnd, RC))
27981           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
27982                              Op.getOperand(1), Src2,
27983                              DAG.getTargetConstant(RC, dl, MVT::i32));
27984         if (!isRoundModeCurDirection(Rnd))
27985           return SDValue();
27986       }
27987 
27988       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
27989                          Op.getOperand(1), Src2);
27990     }
27991     case INTR_TYPE_2OP_SAE: {
27992       SDValue Sae = Op.getOperand(3);
27993 
27994       unsigned Opc;
27995       if (isRoundModeCurDirection(Sae))
27996         Opc = IntrData->Opc0;
27997       else if (isRoundModeSAE(Sae))
27998         Opc = IntrData->Opc1;
27999       else
28000         return SDValue();
28001 
28002       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
28003                          Op.getOperand(2));
28004     }
28005     case INTR_TYPE_3OP:
28006     case INTR_TYPE_3OP_IMM8: {
28007       SDValue Src1 = Op.getOperand(1);
28008       SDValue Src2 = Op.getOperand(2);
28009       SDValue Src3 = Op.getOperand(3);
28010 
28011       if (IntrData->Type == INTR_TYPE_3OP_IMM8 &&
28012           Src3.getValueType() != MVT::i8) {
28013         Src3 = DAG.getTargetConstant(
28014             cast<ConstantSDNode>(Src3)->getZExtValue() & 0xff, dl, MVT::i8);
28015       }
28016 
28017       // We specify 2 possible opcodes for intrinsics with rounding modes.
28018       // First, we check if the intrinsic may have non-default rounding mode,
28019       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
28020       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
28021       if (IntrWithRoundingModeOpcode != 0) {
28022         SDValue Rnd = Op.getOperand(4);
28023         unsigned RC = 0;
28024         if (isRoundModeSAEToX(Rnd, RC))
28025           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
28026                              Src1, Src2, Src3,
28027                              DAG.getTargetConstant(RC, dl, MVT::i32));
28028         if (!isRoundModeCurDirection(Rnd))
28029           return SDValue();
28030       }
28031 
28032       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
28033                          {Src1, Src2, Src3});
28034     }
28035     case INTR_TYPE_4OP_IMM8: {
28036       assert(Op.getOperand(4)->getOpcode() == ISD::TargetConstant);
28037       SDValue Src4 = Op.getOperand(4);
28038       if (Src4.getValueType() != MVT::i8) {
28039         Src4 = DAG.getTargetConstant(
28040             cast<ConstantSDNode>(Src4)->getZExtValue() & 0xff, dl, MVT::i8);
28041       }
28042 
28043       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
28044                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
28045                          Src4);
28046     }
28047     case INTR_TYPE_1OP_MASK: {
28048       SDValue Src = Op.getOperand(1);
28049       SDValue PassThru = Op.getOperand(2);
28050       SDValue Mask = Op.getOperand(3);
28051       // We add rounding mode to the Node when
28052       //   - RC Opcode is specified and
28053       //   - RC is not "current direction".
28054       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
28055       if (IntrWithRoundingModeOpcode != 0) {
28056         SDValue Rnd = Op.getOperand(4);
28057         unsigned RC = 0;
28058         if (isRoundModeSAEToX(Rnd, RC))
28059           return getVectorMaskingNode(
28060               DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
28061                           Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
28062               Mask, PassThru, Subtarget, DAG);
28063         if (!isRoundModeCurDirection(Rnd))
28064           return SDValue();
28065       }
28066       return getVectorMaskingNode(
28067           DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
28068           Subtarget, DAG);
28069     }
28070     case INTR_TYPE_1OP_MASK_SAE: {
28071       SDValue Src = Op.getOperand(1);
28072       SDValue PassThru = Op.getOperand(2);
28073       SDValue Mask = Op.getOperand(3);
28074       SDValue Rnd = Op.getOperand(4);
28075 
28076       unsigned Opc;
28077       if (isRoundModeCurDirection(Rnd))
28078         Opc = IntrData->Opc0;
28079       else if (isRoundModeSAE(Rnd))
28080         Opc = IntrData->Opc1;
28081       else
28082         return SDValue();
28083 
28084       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
28085                                   Subtarget, DAG);
28086     }
28087     case INTR_TYPE_SCALAR_MASK: {
28088       SDValue Src1 = Op.getOperand(1);
28089       SDValue Src2 = Op.getOperand(2);
28090       SDValue passThru = Op.getOperand(3);
28091       SDValue Mask = Op.getOperand(4);
28092       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
28093       // There are 2 kinds of intrinsics in this group:
28094       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
28095       // (2) With rounding mode and sae - 7 operands.
28096       bool HasRounding = IntrWithRoundingModeOpcode != 0;
28097       if (Op.getNumOperands() == (5U + HasRounding)) {
28098         if (HasRounding) {
28099           SDValue Rnd = Op.getOperand(5);
28100           unsigned RC = 0;
28101           if (isRoundModeSAEToX(Rnd, RC))
28102             return getScalarMaskingNode(
28103                 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
28104                             DAG.getTargetConstant(RC, dl, MVT::i32)),
28105                 Mask, passThru, Subtarget, DAG);
28106           if (!isRoundModeCurDirection(Rnd))
28107             return SDValue();
28108         }
28109         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
28110                                                 Src2),
28111                                     Mask, passThru, Subtarget, DAG);
28112       }
28113 
28114       assert(Op.getNumOperands() == (6U + HasRounding) &&
28115              "Unexpected intrinsic form");
28116       SDValue RoundingMode = Op.getOperand(5);
28117       unsigned Opc = IntrData->Opc0;
28118       if (HasRounding) {
28119         SDValue Sae = Op.getOperand(6);
28120         if (isRoundModeSAE(Sae))
28121           Opc = IntrWithRoundingModeOpcode;
28122         else if (!isRoundModeCurDirection(Sae))
28123           return SDValue();
28124       }
28125       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
28126                                               Src2, RoundingMode),
28127                                   Mask, passThru, Subtarget, DAG);
28128     }
28129     case INTR_TYPE_SCALAR_MASK_RND: {
28130       SDValue Src1 = Op.getOperand(1);
28131       SDValue Src2 = Op.getOperand(2);
28132       SDValue passThru = Op.getOperand(3);
28133       SDValue Mask = Op.getOperand(4);
28134       SDValue Rnd = Op.getOperand(5);
28135 
28136       SDValue NewOp;
28137       unsigned RC = 0;
28138       if (isRoundModeCurDirection(Rnd))
28139         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
28140       else if (isRoundModeSAEToX(Rnd, RC))
28141         NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
28142                             DAG.getTargetConstant(RC, dl, MVT::i32));
28143       else
28144         return SDValue();
28145 
28146       return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
28147     }
28148     case INTR_TYPE_SCALAR_MASK_SAE: {
28149       SDValue Src1 = Op.getOperand(1);
28150       SDValue Src2 = Op.getOperand(2);
28151       SDValue passThru = Op.getOperand(3);
28152       SDValue Mask = Op.getOperand(4);
28153       SDValue Sae = Op.getOperand(5);
28154       unsigned Opc;
28155       if (isRoundModeCurDirection(Sae))
28156         Opc = IntrData->Opc0;
28157       else if (isRoundModeSAE(Sae))
28158         Opc = IntrData->Opc1;
28159       else
28160         return SDValue();
28161 
28162       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
28163                                   Mask, passThru, Subtarget, DAG);
28164     }
28165     case INTR_TYPE_2OP_MASK: {
28166       SDValue Src1 = Op.getOperand(1);
28167       SDValue Src2 = Op.getOperand(2);
28168       SDValue PassThru = Op.getOperand(3);
28169       SDValue Mask = Op.getOperand(4);
28170       SDValue NewOp;
28171       if (IntrData->Opc1 != 0) {
28172         SDValue Rnd = Op.getOperand(5);
28173         unsigned RC = 0;
28174         if (isRoundModeSAEToX(Rnd, RC))
28175           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
28176                               DAG.getTargetConstant(RC, dl, MVT::i32));
28177         else if (!isRoundModeCurDirection(Rnd))
28178           return SDValue();
28179       }
28180       if (!NewOp)
28181         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
28182       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
28183     }
28184     case INTR_TYPE_2OP_MASK_SAE: {
28185       SDValue Src1 = Op.getOperand(1);
28186       SDValue Src2 = Op.getOperand(2);
28187       SDValue PassThru = Op.getOperand(3);
28188       SDValue Mask = Op.getOperand(4);
28189 
28190       unsigned Opc = IntrData->Opc0;
28191       if (IntrData->Opc1 != 0) {
28192         SDValue Sae = Op.getOperand(5);
28193         if (isRoundModeSAE(Sae))
28194           Opc = IntrData->Opc1;
28195         else if (!isRoundModeCurDirection(Sae))
28196           return SDValue();
28197       }
28198 
28199       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
28200                                   Mask, PassThru, Subtarget, DAG);
28201     }
28202     case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
28203       SDValue Src1 = Op.getOperand(1);
28204       SDValue Src2 = Op.getOperand(2);
28205       SDValue Src3 = Op.getOperand(3);
28206       SDValue PassThru = Op.getOperand(4);
28207       SDValue Mask = Op.getOperand(5);
28208       SDValue Sae = Op.getOperand(6);
28209       unsigned Opc;
28210       if (isRoundModeCurDirection(Sae))
28211         Opc = IntrData->Opc0;
28212       else if (isRoundModeSAE(Sae))
28213         Opc = IntrData->Opc1;
28214       else
28215         return SDValue();
28216 
28217       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
28218                                   Mask, PassThru, Subtarget, DAG);
28219     }
28220     case INTR_TYPE_3OP_MASK_SAE: {
28221       SDValue Src1 = Op.getOperand(1);
28222       SDValue Src2 = Op.getOperand(2);
28223       SDValue Src3 = Op.getOperand(3);
28224       SDValue PassThru = Op.getOperand(4);
28225       SDValue Mask = Op.getOperand(5);
28226 
28227       unsigned Opc = IntrData->Opc0;
28228       if (IntrData->Opc1 != 0) {
28229         SDValue Sae = Op.getOperand(6);
28230         if (isRoundModeSAE(Sae))
28231           Opc = IntrData->Opc1;
28232         else if (!isRoundModeCurDirection(Sae))
28233           return SDValue();
28234       }
28235       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
28236                                   Mask, PassThru, Subtarget, DAG);
28237     }
28238     case BLENDV: {
28239       SDValue Src1 = Op.getOperand(1);
28240       SDValue Src2 = Op.getOperand(2);
28241       SDValue Src3 = Op.getOperand(3);
28242 
28243       EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
28244       Src3 = DAG.getBitcast(MaskVT, Src3);
28245 
28246       // Reverse the operands to match VSELECT order.
28247       return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
28248     }
28249     case VPERM_2OP : {
28250       SDValue Src1 = Op.getOperand(1);
28251       SDValue Src2 = Op.getOperand(2);
28252 
28253       // Swap Src1 and Src2 in the node creation
28254       return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
28255     }
28256     case CFMA_OP_MASKZ:
28257     case CFMA_OP_MASK: {
28258       SDValue Src1 = Op.getOperand(1);
28259       SDValue Src2 = Op.getOperand(2);
28260       SDValue Src3 = Op.getOperand(3);
28261       SDValue Mask = Op.getOperand(4);
28262       MVT VT = Op.getSimpleValueType();
28263 
28264       SDValue PassThru = Src3;
28265       if (IntrData->Type == CFMA_OP_MASKZ)
28266         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
28267 
28268       // We add rounding mode to the Node when
28269       //   - RC Opcode is specified and
28270       //   - RC is not "current direction".
28271       SDValue NewOp;
28272       if (IntrData->Opc1 != 0) {
28273         SDValue Rnd = Op.getOperand(5);
28274         unsigned RC = 0;
28275         if (isRoundModeSAEToX(Rnd, RC))
28276           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2, Src3,
28277                               DAG.getTargetConstant(RC, dl, MVT::i32));
28278         else if (!isRoundModeCurDirection(Rnd))
28279           return SDValue();
28280       }
28281       if (!NewOp)
28282         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2, Src3);
28283       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
28284     }
28285     case IFMA_OP:
28286       // NOTE: We need to swizzle the operands to pass the multiply operands
28287       // first.
28288       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
28289                          Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
28290     case FPCLASSS: {
28291       SDValue Src1 = Op.getOperand(1);
28292       SDValue Imm = Op.getOperand(2);
28293       SDValue Mask = Op.getOperand(3);
28294       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
28295       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
28296                                                  Subtarget, DAG);
28297       // Need to fill with zeros to ensure the bitcast will produce zeroes
28298       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
28299       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
28300                                 DAG.getConstant(0, dl, MVT::v8i1),
28301                                 FPclassMask, DAG.getIntPtrConstant(0, dl));
28302       return DAG.getBitcast(MVT::i8, Ins);
28303     }
28304 
28305     case CMP_MASK_CC: {
28306       MVT MaskVT = Op.getSimpleValueType();
28307       SDValue CC = Op.getOperand(3);
28308       SDValue Mask = Op.getOperand(4);
28309       // We specify 2 possible opcodes for intrinsics with rounding modes.
28310       // First, we check if the intrinsic may have non-default rounding mode,
28311       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
28312       if (IntrData->Opc1 != 0) {
28313         SDValue Sae = Op.getOperand(5);
28314         if (isRoundModeSAE(Sae))
28315           return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
28316                              Op.getOperand(2), CC, Mask, Sae);
28317         if (!isRoundModeCurDirection(Sae))
28318           return SDValue();
28319       }
28320       //default rounding mode
28321       return DAG.getNode(IntrData->Opc0, dl, MaskVT,
28322                          {Op.getOperand(1), Op.getOperand(2), CC, Mask});
28323     }
28324     case CMP_MASK_SCALAR_CC: {
28325       SDValue Src1 = Op.getOperand(1);
28326       SDValue Src2 = Op.getOperand(2);
28327       SDValue CC = Op.getOperand(3);
28328       SDValue Mask = Op.getOperand(4);
28329 
28330       SDValue Cmp;
28331       if (IntrData->Opc1 != 0) {
28332         SDValue Sae = Op.getOperand(5);
28333         if (isRoundModeSAE(Sae))
28334           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
28335         else if (!isRoundModeCurDirection(Sae))
28336           return SDValue();
28337       }
28338       //default rounding mode
28339       if (!Cmp.getNode())
28340         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
28341 
28342       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
28343                                              Subtarget, DAG);
28344       // Need to fill with zeros to ensure the bitcast will produce zeroes
28345       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
28346       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
28347                                 DAG.getConstant(0, dl, MVT::v8i1),
28348                                 CmpMask, DAG.getIntPtrConstant(0, dl));
28349       return DAG.getBitcast(MVT::i8, Ins);
28350     }
28351     case COMI: { // Comparison intrinsics
28352       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
28353       SDValue LHS = Op.getOperand(1);
28354       SDValue RHS = Op.getOperand(2);
28355       // Some conditions require the operands to be swapped.
28356       if (CC == ISD::SETLT || CC == ISD::SETLE)
28357         std::swap(LHS, RHS);
28358 
28359       SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
28360       SDValue SetCC;
28361       switch (CC) {
28362       case ISD::SETEQ: { // (ZF = 0 and PF = 0)
28363         SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
28364         SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
28365         SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
28366         break;
28367       }
28368       case ISD::SETNE: { // (ZF = 1 or PF = 1)
28369         SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
28370         SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
28371         SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
28372         break;
28373       }
28374       case ISD::SETGT: // (CF = 0 and ZF = 0)
28375       case ISD::SETLT: { // Condition opposite to GT. Operands swapped above.
28376         SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
28377         break;
28378       }
28379       case ISD::SETGE: // CF = 0
28380       case ISD::SETLE: // Condition opposite to GE. Operands swapped above.
28381         SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
28382         break;
28383       default:
28384         llvm_unreachable("Unexpected illegal condition!");
28385       }
28386       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
28387     }
28388     case COMI_RM: { // Comparison intrinsics with Sae
28389       SDValue LHS = Op.getOperand(1);
28390       SDValue RHS = Op.getOperand(2);
28391       unsigned CondVal = Op.getConstantOperandVal(3);
28392       SDValue Sae = Op.getOperand(4);
28393 
28394       SDValue FCmp;
28395       if (isRoundModeCurDirection(Sae))
28396         FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
28397                            DAG.getTargetConstant(CondVal, dl, MVT::i8));
28398       else if (isRoundModeSAE(Sae))
28399         FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
28400                            DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
28401       else
28402         return SDValue();
28403       // Need to fill with zeros to ensure the bitcast will produce zeroes
28404       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
28405       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
28406                                 DAG.getConstant(0, dl, MVT::v16i1),
28407                                 FCmp, DAG.getIntPtrConstant(0, dl));
28408       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
28409                          DAG.getBitcast(MVT::i16, Ins));
28410     }
28411     case VSHIFT: {
28412       SDValue SrcOp = Op.getOperand(1);
28413       SDValue ShAmt = Op.getOperand(2);
28414       assert(ShAmt.getValueType() == MVT::i32 &&
28415              "Unexpected VSHIFT amount type");
28416 
28417       // Catch shift-by-constant.
28418       if (auto *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
28419         return getTargetVShiftByConstNode(IntrData->Opc0, dl,
28420                                           Op.getSimpleValueType(), SrcOp,
28421                                           CShAmt->getZExtValue(), DAG);
28422 
28423       ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
28424       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
28425                                  SrcOp, ShAmt, 0, Subtarget, DAG);
28426     }
28427     case COMPRESS_EXPAND_IN_REG: {
28428       SDValue Mask = Op.getOperand(3);
28429       SDValue DataToCompress = Op.getOperand(1);
28430       SDValue PassThru = Op.getOperand(2);
28431       if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
28432         return Op.getOperand(1);
28433 
28434       // Avoid false dependency.
28435       if (PassThru.isUndef())
28436         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
28437 
28438       return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
28439                          Mask);
28440     }
28441     case FIXUPIMM:
28442     case FIXUPIMM_MASKZ: {
28443       SDValue Src1 = Op.getOperand(1);
28444       SDValue Src2 = Op.getOperand(2);
28445       SDValue Src3 = Op.getOperand(3);
28446       SDValue Imm = Op.getOperand(4);
28447       SDValue Mask = Op.getOperand(5);
28448       SDValue Passthru = (IntrData->Type == FIXUPIMM)
28449                              ? Src1
28450                              : getZeroVector(VT, Subtarget, DAG, dl);
28451 
28452       unsigned Opc = IntrData->Opc0;
28453       if (IntrData->Opc1 != 0) {
28454         SDValue Sae = Op.getOperand(6);
28455         if (isRoundModeSAE(Sae))
28456           Opc = IntrData->Opc1;
28457         else if (!isRoundModeCurDirection(Sae))
28458           return SDValue();
28459       }
28460 
28461       SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
28462 
28463       if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
28464         return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
28465 
28466       return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
28467     }
28468     case ROUNDP: {
28469       assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
28470       // Clear the upper bits of the rounding immediate so that the legacy
28471       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
28472       auto Round = cast<ConstantSDNode>(Op.getOperand(2));
28473       SDValue RoundingMode =
28474           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
28475       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
28476                          Op.getOperand(1), RoundingMode);
28477     }
28478     case ROUNDS: {
28479       assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
28480       // Clear the upper bits of the rounding immediate so that the legacy
28481       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
28482       auto Round = cast<ConstantSDNode>(Op.getOperand(3));
28483       SDValue RoundingMode =
28484           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
28485       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
28486                          Op.getOperand(1), Op.getOperand(2), RoundingMode);
28487     }
28488     case BEXTRI: {
28489       assert(IntrData->Opc0 == X86ISD::BEXTRI && "Unexpected opcode");
28490 
28491       uint64_t Imm = Op.getConstantOperandVal(2);
28492       SDValue Control = DAG.getTargetConstant(Imm & 0xffff, dl,
28493                                               Op.getValueType());
28494       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
28495                          Op.getOperand(1), Control);
28496     }
28497     // ADC/ADCX/SBB
28498     case ADX: {
28499       SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
28500       SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
28501 
28502       SDValue Res;
28503       // If the carry in is zero, then we should just use ADD/SUB instead of
28504       // ADC/SBB.
28505       if (isNullConstant(Op.getOperand(1))) {
28506         Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
28507                           Op.getOperand(3));
28508       } else {
28509         SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
28510                                     DAG.getConstant(-1, dl, MVT::i8));
28511         Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
28512                           Op.getOperand(3), GenCF.getValue(1));
28513       }
28514       SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
28515       SDValue Results[] = { SetCC, Res };
28516       return DAG.getMergeValues(Results, dl);
28517     }
28518     case CVTPD2PS_MASK:
28519     case CVTPD2DQ_MASK:
28520     case CVTQQ2PS_MASK:
28521     case TRUNCATE_TO_REG: {
28522       SDValue Src = Op.getOperand(1);
28523       SDValue PassThru = Op.getOperand(2);
28524       SDValue Mask = Op.getOperand(3);
28525 
28526       if (isAllOnesConstant(Mask))
28527         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
28528 
28529       MVT SrcVT = Src.getSimpleValueType();
28530       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
28531       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
28532       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
28533                          {Src, PassThru, Mask});
28534     }
28535     case CVTPS2PH_MASK: {
28536       SDValue Src = Op.getOperand(1);
28537       SDValue Rnd = Op.getOperand(2);
28538       SDValue PassThru = Op.getOperand(3);
28539       SDValue Mask = Op.getOperand(4);
28540 
28541       unsigned RC = 0;
28542       unsigned Opc = IntrData->Opc0;
28543       bool SAE = Src.getValueType().is512BitVector() &&
28544                  (isRoundModeSAEToX(Rnd, RC) || isRoundModeSAE(Rnd));
28545       if (SAE) {
28546         Opc = X86ISD::CVTPS2PH_SAE;
28547         Rnd = DAG.getTargetConstant(RC, dl, MVT::i32);
28548       }
28549 
28550       if (isAllOnesConstant(Mask))
28551         return DAG.getNode(Opc, dl, Op.getValueType(), Src, Rnd);
28552 
28553       if (SAE)
28554         Opc = X86ISD::MCVTPS2PH_SAE;
28555       else
28556         Opc = IntrData->Opc1;
28557       MVT SrcVT = Src.getSimpleValueType();
28558       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
28559       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
28560       return DAG.getNode(Opc, dl, Op.getValueType(), Src, Rnd, PassThru, Mask);
28561     }
28562     case CVTNEPS2BF16_MASK: {
28563       SDValue Src = Op.getOperand(1);
28564       SDValue PassThru = Op.getOperand(2);
28565       SDValue Mask = Op.getOperand(3);
28566 
28567       if (ISD::isBuildVectorAllOnes(Mask.getNode()))
28568         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
28569 
28570       // Break false dependency.
28571       if (PassThru.isUndef())
28572         PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
28573 
28574       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
28575                          Mask);
28576     }
28577     default:
28578       break;
28579     }
28580   }
28581 
28582   switch (IntNo) {
28583   default: return SDValue();    // Don't custom lower most intrinsics.
28584 
28585   // ptest and testp intrinsics. The intrinsic these come from are designed to
28586   // return an integer value, not just an instruction so lower it to the ptest
28587   // or testp pattern and a setcc for the result.
28588   case Intrinsic::x86_avx512_ktestc_b:
28589   case Intrinsic::x86_avx512_ktestc_w:
28590   case Intrinsic::x86_avx512_ktestc_d:
28591   case Intrinsic::x86_avx512_ktestc_q:
28592   case Intrinsic::x86_avx512_ktestz_b:
28593   case Intrinsic::x86_avx512_ktestz_w:
28594   case Intrinsic::x86_avx512_ktestz_d:
28595   case Intrinsic::x86_avx512_ktestz_q:
28596   case Intrinsic::x86_sse41_ptestz:
28597   case Intrinsic::x86_sse41_ptestc:
28598   case Intrinsic::x86_sse41_ptestnzc:
28599   case Intrinsic::x86_avx_ptestz_256:
28600   case Intrinsic::x86_avx_ptestc_256:
28601   case Intrinsic::x86_avx_ptestnzc_256:
28602   case Intrinsic::x86_avx_vtestz_ps:
28603   case Intrinsic::x86_avx_vtestc_ps:
28604   case Intrinsic::x86_avx_vtestnzc_ps:
28605   case Intrinsic::x86_avx_vtestz_pd:
28606   case Intrinsic::x86_avx_vtestc_pd:
28607   case Intrinsic::x86_avx_vtestnzc_pd:
28608   case Intrinsic::x86_avx_vtestz_ps_256:
28609   case Intrinsic::x86_avx_vtestc_ps_256:
28610   case Intrinsic::x86_avx_vtestnzc_ps_256:
28611   case Intrinsic::x86_avx_vtestz_pd_256:
28612   case Intrinsic::x86_avx_vtestc_pd_256:
28613   case Intrinsic::x86_avx_vtestnzc_pd_256: {
28614     unsigned TestOpc = X86ISD::PTEST;
28615     X86::CondCode X86CC;
28616     switch (IntNo) {
28617     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
28618     case Intrinsic::x86_avx512_ktestc_b:
28619     case Intrinsic::x86_avx512_ktestc_w:
28620     case Intrinsic::x86_avx512_ktestc_d:
28621     case Intrinsic::x86_avx512_ktestc_q:
28622       // CF = 1
28623       TestOpc = X86ISD::KTEST;
28624       X86CC = X86::COND_B;
28625       break;
28626     case Intrinsic::x86_avx512_ktestz_b:
28627     case Intrinsic::x86_avx512_ktestz_w:
28628     case Intrinsic::x86_avx512_ktestz_d:
28629     case Intrinsic::x86_avx512_ktestz_q:
28630       TestOpc = X86ISD::KTEST;
28631       X86CC = X86::COND_E;
28632       break;
28633     case Intrinsic::x86_avx_vtestz_ps:
28634     case Intrinsic::x86_avx_vtestz_pd:
28635     case Intrinsic::x86_avx_vtestz_ps_256:
28636     case Intrinsic::x86_avx_vtestz_pd_256:
28637       TestOpc = X86ISD::TESTP;
28638       [[fallthrough]];
28639     case Intrinsic::x86_sse41_ptestz:
28640     case Intrinsic::x86_avx_ptestz_256:
28641       // ZF = 1
28642       X86CC = X86::COND_E;
28643       break;
28644     case Intrinsic::x86_avx_vtestc_ps:
28645     case Intrinsic::x86_avx_vtestc_pd:
28646     case Intrinsic::x86_avx_vtestc_ps_256:
28647     case Intrinsic::x86_avx_vtestc_pd_256:
28648       TestOpc = X86ISD::TESTP;
28649       [[fallthrough]];
28650     case Intrinsic::x86_sse41_ptestc:
28651     case Intrinsic::x86_avx_ptestc_256:
28652       // CF = 1
28653       X86CC = X86::COND_B;
28654       break;
28655     case Intrinsic::x86_avx_vtestnzc_ps:
28656     case Intrinsic::x86_avx_vtestnzc_pd:
28657     case Intrinsic::x86_avx_vtestnzc_ps_256:
28658     case Intrinsic::x86_avx_vtestnzc_pd_256:
28659       TestOpc = X86ISD::TESTP;
28660       [[fallthrough]];
28661     case Intrinsic::x86_sse41_ptestnzc:
28662     case Intrinsic::x86_avx_ptestnzc_256:
28663       // ZF and CF = 0
28664       X86CC = X86::COND_A;
28665       break;
28666     }
28667 
28668     SDValue LHS = Op.getOperand(1);
28669     SDValue RHS = Op.getOperand(2);
28670     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
28671     SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
28672     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
28673   }
28674 
28675   case Intrinsic::x86_sse42_pcmpistria128:
28676   case Intrinsic::x86_sse42_pcmpestria128:
28677   case Intrinsic::x86_sse42_pcmpistric128:
28678   case Intrinsic::x86_sse42_pcmpestric128:
28679   case Intrinsic::x86_sse42_pcmpistrio128:
28680   case Intrinsic::x86_sse42_pcmpestrio128:
28681   case Intrinsic::x86_sse42_pcmpistris128:
28682   case Intrinsic::x86_sse42_pcmpestris128:
28683   case Intrinsic::x86_sse42_pcmpistriz128:
28684   case Intrinsic::x86_sse42_pcmpestriz128: {
28685     unsigned Opcode;
28686     X86::CondCode X86CC;
28687     switch (IntNo) {
28688     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
28689     case Intrinsic::x86_sse42_pcmpistria128:
28690       Opcode = X86ISD::PCMPISTR;
28691       X86CC = X86::COND_A;
28692       break;
28693     case Intrinsic::x86_sse42_pcmpestria128:
28694       Opcode = X86ISD::PCMPESTR;
28695       X86CC = X86::COND_A;
28696       break;
28697     case Intrinsic::x86_sse42_pcmpistric128:
28698       Opcode = X86ISD::PCMPISTR;
28699       X86CC = X86::COND_B;
28700       break;
28701     case Intrinsic::x86_sse42_pcmpestric128:
28702       Opcode = X86ISD::PCMPESTR;
28703       X86CC = X86::COND_B;
28704       break;
28705     case Intrinsic::x86_sse42_pcmpistrio128:
28706       Opcode = X86ISD::PCMPISTR;
28707       X86CC = X86::COND_O;
28708       break;
28709     case Intrinsic::x86_sse42_pcmpestrio128:
28710       Opcode = X86ISD::PCMPESTR;
28711       X86CC = X86::COND_O;
28712       break;
28713     case Intrinsic::x86_sse42_pcmpistris128:
28714       Opcode = X86ISD::PCMPISTR;
28715       X86CC = X86::COND_S;
28716       break;
28717     case Intrinsic::x86_sse42_pcmpestris128:
28718       Opcode = X86ISD::PCMPESTR;
28719       X86CC = X86::COND_S;
28720       break;
28721     case Intrinsic::x86_sse42_pcmpistriz128:
28722       Opcode = X86ISD::PCMPISTR;
28723       X86CC = X86::COND_E;
28724       break;
28725     case Intrinsic::x86_sse42_pcmpestriz128:
28726       Opcode = X86ISD::PCMPESTR;
28727       X86CC = X86::COND_E;
28728       break;
28729     }
28730     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
28731     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
28732     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
28733     SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
28734     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
28735   }
28736 
28737   case Intrinsic::x86_sse42_pcmpistri128:
28738   case Intrinsic::x86_sse42_pcmpestri128: {
28739     unsigned Opcode;
28740     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
28741       Opcode = X86ISD::PCMPISTR;
28742     else
28743       Opcode = X86ISD::PCMPESTR;
28744 
28745     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
28746     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
28747     return DAG.getNode(Opcode, dl, VTs, NewOps);
28748   }
28749 
28750   case Intrinsic::x86_sse42_pcmpistrm128:
28751   case Intrinsic::x86_sse42_pcmpestrm128: {
28752     unsigned Opcode;
28753     if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
28754       Opcode = X86ISD::PCMPISTR;
28755     else
28756       Opcode = X86ISD::PCMPESTR;
28757 
28758     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
28759     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
28760     return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
28761   }
28762 
28763   case Intrinsic::eh_sjlj_lsda: {
28764     MachineFunction &MF = DAG.getMachineFunction();
28765     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28766     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
28767     auto &Context = MF.getMMI().getContext();
28768     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
28769                                             Twine(MF.getFunctionNumber()));
28770     return DAG.getNode(getGlobalWrapperKind(), dl, VT,
28771                        DAG.getMCSymbol(S, PtrVT));
28772   }
28773 
28774   case Intrinsic::x86_seh_lsda: {
28775     // Compute the symbol for the LSDA. We know it'll get emitted later.
28776     MachineFunction &MF = DAG.getMachineFunction();
28777     SDValue Op1 = Op.getOperand(1);
28778     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
28779     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
28780         GlobalValue::dropLLVMManglingEscape(Fn->getName()));
28781 
28782     // Generate a simple absolute symbol reference. This intrinsic is only
28783     // supported on 32-bit Windows, which isn't PIC.
28784     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
28785     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
28786   }
28787 
28788   case Intrinsic::eh_recoverfp: {
28789     SDValue FnOp = Op.getOperand(1);
28790     SDValue IncomingFPOp = Op.getOperand(2);
28791     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
28792     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
28793     if (!Fn)
28794       report_fatal_error(
28795           "llvm.eh.recoverfp must take a function as the first argument");
28796     return recoverFramePointer(DAG, Fn, IncomingFPOp);
28797   }
28798 
28799   case Intrinsic::localaddress: {
28800     // Returns one of the stack, base, or frame pointer registers, depending on
28801     // which is used to reference local variables.
28802     MachineFunction &MF = DAG.getMachineFunction();
28803     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
28804     unsigned Reg;
28805     if (RegInfo->hasBasePointer(MF))
28806       Reg = RegInfo->getBaseRegister();
28807     else { // Handles the SP or FP case.
28808       bool CantUseFP = RegInfo->hasStackRealignment(MF);
28809       if (CantUseFP)
28810         Reg = RegInfo->getPtrSizedStackRegister(MF);
28811       else
28812         Reg = RegInfo->getPtrSizedFrameRegister(MF);
28813     }
28814     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
28815   }
28816   case Intrinsic::x86_avx512_vp2intersect_q_512:
28817   case Intrinsic::x86_avx512_vp2intersect_q_256:
28818   case Intrinsic::x86_avx512_vp2intersect_q_128:
28819   case Intrinsic::x86_avx512_vp2intersect_d_512:
28820   case Intrinsic::x86_avx512_vp2intersect_d_256:
28821   case Intrinsic::x86_avx512_vp2intersect_d_128: {
28822     MVT MaskVT = Op.getSimpleValueType();
28823 
28824     SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
28825     SDLoc DL(Op);
28826 
28827     SDValue Operation =
28828         DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
28829                     Op->getOperand(1), Op->getOperand(2));
28830 
28831     SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
28832                                                  MaskVT, Operation);
28833     SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
28834                                                  MaskVT, Operation);
28835     return DAG.getMergeValues({Result0, Result1}, DL);
28836   }
28837   case Intrinsic::x86_mmx_pslli_w:
28838   case Intrinsic::x86_mmx_pslli_d:
28839   case Intrinsic::x86_mmx_pslli_q:
28840   case Intrinsic::x86_mmx_psrli_w:
28841   case Intrinsic::x86_mmx_psrli_d:
28842   case Intrinsic::x86_mmx_psrli_q:
28843   case Intrinsic::x86_mmx_psrai_w:
28844   case Intrinsic::x86_mmx_psrai_d: {
28845     SDLoc DL(Op);
28846     SDValue ShAmt = Op.getOperand(2);
28847     // If the argument is a constant, convert it to a target constant.
28848     if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
28849       // Clamp out of bounds shift amounts since they will otherwise be masked
28850       // to 8-bits which may make it no longer out of bounds.
28851       unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
28852       if (ShiftAmount == 0)
28853         return Op.getOperand(1);
28854 
28855       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
28856                          Op.getOperand(0), Op.getOperand(1),
28857                          DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
28858     }
28859 
28860     unsigned NewIntrinsic;
28861     switch (IntNo) {
28862     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
28863     case Intrinsic::x86_mmx_pslli_w:
28864       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
28865       break;
28866     case Intrinsic::x86_mmx_pslli_d:
28867       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
28868       break;
28869     case Intrinsic::x86_mmx_pslli_q:
28870       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
28871       break;
28872     case Intrinsic::x86_mmx_psrli_w:
28873       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
28874       break;
28875     case Intrinsic::x86_mmx_psrli_d:
28876       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
28877       break;
28878     case Intrinsic::x86_mmx_psrli_q:
28879       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
28880       break;
28881     case Intrinsic::x86_mmx_psrai_w:
28882       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
28883       break;
28884     case Intrinsic::x86_mmx_psrai_d:
28885       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
28886       break;
28887     }
28888 
28889     // The vector shift intrinsics with scalars uses 32b shift amounts but
28890     // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
28891     // MMX register.
28892     ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
28893     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
28894                        DAG.getTargetConstant(NewIntrinsic, DL,
28895                                              getPointerTy(DAG.getDataLayout())),
28896                        Op.getOperand(1), ShAmt);
28897   }
28898   case Intrinsic::thread_pointer: {
28899     if (Subtarget.isTargetELF()) {
28900       SDLoc dl(Op);
28901       EVT PtrVT = getPointerTy(DAG.getDataLayout());
28902       // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
28903       Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(
28904           *DAG.getContext(), Subtarget.is64Bit() ? X86AS::FS : X86AS::GS));
28905       return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
28906                          DAG.getIntPtrConstant(0, dl), MachinePointerInfo(Ptr));
28907     }
28908     report_fatal_error(
28909         "Target OS doesn't support __builtin_thread_pointer() yet.");
28910   }
28911   }
28912 }
28913 
28914 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
28915                                  SDValue Src, SDValue Mask, SDValue Base,
28916                                  SDValue Index, SDValue ScaleOp, SDValue Chain,
28917                                  const X86Subtarget &Subtarget) {
28918   SDLoc dl(Op);
28919   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
28920   // Scale must be constant.
28921   if (!C)
28922     return SDValue();
28923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28924   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
28925                                         TLI.getPointerTy(DAG.getDataLayout()));
28926   EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
28927   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
28928   // If source is undef or we know it won't be used, use a zero vector
28929   // to break register dependency.
28930   // TODO: use undef instead and let BreakFalseDeps deal with it?
28931   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
28932     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
28933 
28934   // Cast mask to an integer type.
28935   Mask = DAG.getBitcast(MaskVT, Mask);
28936 
28937   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
28938 
28939   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
28940   SDValue Res =
28941       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
28942                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
28943   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
28944 }
28945 
28946 static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
28947                              SDValue Src, SDValue Mask, SDValue Base,
28948                              SDValue Index, SDValue ScaleOp, SDValue Chain,
28949                              const X86Subtarget &Subtarget) {
28950   MVT VT = Op.getSimpleValueType();
28951   SDLoc dl(Op);
28952   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
28953   // Scale must be constant.
28954   if (!C)
28955     return SDValue();
28956   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28957   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
28958                                         TLI.getPointerTy(DAG.getDataLayout()));
28959   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
28960                               VT.getVectorNumElements());
28961   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
28962 
28963   // We support two versions of the gather intrinsics. One with scalar mask and
28964   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
28965   if (Mask.getValueType() != MaskVT)
28966     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
28967 
28968   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
28969   // If source is undef or we know it won't be used, use a zero vector
28970   // to break register dependency.
28971   // TODO: use undef instead and let BreakFalseDeps deal with it?
28972   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
28973     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
28974 
28975   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
28976 
28977   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
28978   SDValue Res =
28979       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
28980                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
28981   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
28982 }
28983 
28984 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
28985                                SDValue Src, SDValue Mask, SDValue Base,
28986                                SDValue Index, SDValue ScaleOp, SDValue Chain,
28987                                const X86Subtarget &Subtarget) {
28988   SDLoc dl(Op);
28989   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
28990   // Scale must be constant.
28991   if (!C)
28992     return SDValue();
28993   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28994   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
28995                                         TLI.getPointerTy(DAG.getDataLayout()));
28996   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
28997                               Src.getSimpleValueType().getVectorNumElements());
28998   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
28999 
29000   // We support two versions of the scatter intrinsics. One with scalar mask and
29001   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
29002   if (Mask.getValueType() != MaskVT)
29003     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
29004 
29005   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
29006 
29007   SDVTList VTs = DAG.getVTList(MVT::Other);
29008   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
29009   SDValue Res =
29010       DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
29011                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
29012   return Res;
29013 }
29014 
29015 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
29016                                SDValue Mask, SDValue Base, SDValue Index,
29017                                SDValue ScaleOp, SDValue Chain,
29018                                const X86Subtarget &Subtarget) {
29019   SDLoc dl(Op);
29020   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
29021   // Scale must be constant.
29022   if (!C)
29023     return SDValue();
29024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29025   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
29026                                         TLI.getPointerTy(DAG.getDataLayout()));
29027   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
29028   SDValue Segment = DAG.getRegister(0, MVT::i32);
29029   MVT MaskVT =
29030     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
29031   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
29032   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
29033   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
29034   return SDValue(Res, 0);
29035 }
29036 
29037 /// Handles the lowering of builtin intrinsics with chain that return their
29038 /// value into registers EDX:EAX.
29039 /// If operand ScrReg is a valid register identifier, then operand 2 of N is
29040 /// copied to SrcReg. The assumption is that SrcReg is an implicit input to
29041 /// TargetOpcode.
29042 /// Returns a Glue value which can be used to add extra copy-from-reg if the
29043 /// expanded intrinsics implicitly defines extra registers (i.e. not just
29044 /// EDX:EAX).
29045 static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
29046                                         SelectionDAG &DAG,
29047                                         unsigned TargetOpcode,
29048                                         unsigned SrcReg,
29049                                         const X86Subtarget &Subtarget,
29050                                         SmallVectorImpl<SDValue> &Results) {
29051   SDValue Chain = N->getOperand(0);
29052   SDValue Glue;
29053 
29054   if (SrcReg) {
29055     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
29056     Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
29057     Glue = Chain.getValue(1);
29058   }
29059 
29060   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
29061   SDValue N1Ops[] = {Chain, Glue};
29062   SDNode *N1 = DAG.getMachineNode(
29063       TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
29064   Chain = SDValue(N1, 0);
29065 
29066   // Reads the content of XCR and returns it in registers EDX:EAX.
29067   SDValue LO, HI;
29068   if (Subtarget.is64Bit()) {
29069     LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
29070     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
29071                             LO.getValue(2));
29072   } else {
29073     LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
29074     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
29075                             LO.getValue(2));
29076   }
29077   Chain = HI.getValue(1);
29078   Glue = HI.getValue(2);
29079 
29080   if (Subtarget.is64Bit()) {
29081     // Merge the two 32-bit values into a 64-bit one.
29082     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
29083                               DAG.getConstant(32, DL, MVT::i8));
29084     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
29085     Results.push_back(Chain);
29086     return Glue;
29087   }
29088 
29089   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
29090   SDValue Ops[] = { LO, HI };
29091   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
29092   Results.push_back(Pair);
29093   Results.push_back(Chain);
29094   return Glue;
29095 }
29096 
29097 /// Handles the lowering of builtin intrinsics that read the time stamp counter
29098 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
29099 /// READCYCLECOUNTER nodes.
29100 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
29101                                     SelectionDAG &DAG,
29102                                     const X86Subtarget &Subtarget,
29103                                     SmallVectorImpl<SDValue> &Results) {
29104   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
29105   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
29106   // and the EAX register is loaded with the low-order 32 bits.
29107   SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
29108                                              /* NoRegister */0, Subtarget,
29109                                              Results);
29110   if (Opcode != X86::RDTSCP)
29111     return;
29112 
29113   SDValue Chain = Results[1];
29114   // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
29115   // the ECX register. Add 'ecx' explicitly to the chain.
29116   SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
29117   Results[1] = ecx;
29118   Results.push_back(ecx.getValue(1));
29119 }
29120 
29121 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
29122                                      SelectionDAG &DAG) {
29123   SmallVector<SDValue, 3> Results;
29124   SDLoc DL(Op);
29125   getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
29126                           Results);
29127   return DAG.getMergeValues(Results, DL);
29128 }
29129 
29130 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
29131   MachineFunction &MF = DAG.getMachineFunction();
29132   SDValue Chain = Op.getOperand(0);
29133   SDValue RegNode = Op.getOperand(2);
29134   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
29135   if (!EHInfo)
29136     report_fatal_error("EH registrations only live in functions using WinEH");
29137 
29138   // Cast the operand to an alloca, and remember the frame index.
29139   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
29140   if (!FINode)
29141     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
29142   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
29143 
29144   // Return the chain operand without making any DAG nodes.
29145   return Chain;
29146 }
29147 
29148 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
29149   MachineFunction &MF = DAG.getMachineFunction();
29150   SDValue Chain = Op.getOperand(0);
29151   SDValue EHGuard = Op.getOperand(2);
29152   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
29153   if (!EHInfo)
29154     report_fatal_error("EHGuard only live in functions using WinEH");
29155 
29156   // Cast the operand to an alloca, and remember the frame index.
29157   auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
29158   if (!FINode)
29159     report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
29160   EHInfo->EHGuardFrameIndex = FINode->getIndex();
29161 
29162   // Return the chain operand without making any DAG nodes.
29163   return Chain;
29164 }
29165 
29166 /// Emit Truncating Store with signed or unsigned saturation.
29167 static SDValue
29168 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &DL, SDValue Val,
29169                 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
29170                 SelectionDAG &DAG) {
29171   SDVTList VTs = DAG.getVTList(MVT::Other);
29172   SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
29173   SDValue Ops[] = { Chain, Val, Ptr, Undef };
29174   unsigned Opc = SignedSat ? X86ISD::VTRUNCSTORES : X86ISD::VTRUNCSTOREUS;
29175   return DAG.getMemIntrinsicNode(Opc, DL, VTs, Ops, MemVT, MMO);
29176 }
29177 
29178 /// Emit Masked Truncating Store with signed or unsigned saturation.
29179 static SDValue EmitMaskedTruncSStore(bool SignedSat, SDValue Chain,
29180                                      const SDLoc &DL,
29181                       SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
29182                       MachineMemOperand *MMO, SelectionDAG &DAG) {
29183   SDVTList VTs = DAG.getVTList(MVT::Other);
29184   SDValue Ops[] = { Chain, Val, Ptr, Mask };
29185   unsigned Opc = SignedSat ? X86ISD::VMTRUNCSTORES : X86ISD::VMTRUNCSTOREUS;
29186   return DAG.getMemIntrinsicNode(Opc, DL, VTs, Ops, MemVT, MMO);
29187 }
29188 
29189 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
29190                                       SelectionDAG &DAG) {
29191   unsigned IntNo = Op.getConstantOperandVal(1);
29192   const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
29193   if (!IntrData) {
29194     switch (IntNo) {
29195 
29196     case Intrinsic::swift_async_context_addr: {
29197       SDLoc dl(Op);
29198       auto &MF = DAG.getMachineFunction();
29199       auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
29200       if (Subtarget.is64Bit()) {
29201         MF.getFrameInfo().setFrameAddressIsTaken(true);
29202         X86FI->setHasSwiftAsyncContext(true);
29203         SDValue Chain = Op->getOperand(0);
29204         SDValue CopyRBP = DAG.getCopyFromReg(Chain, dl, X86::RBP, MVT::i64);
29205         SDValue Result =
29206             SDValue(DAG.getMachineNode(X86::SUB64ri32, dl, MVT::i64, CopyRBP,
29207                                        DAG.getTargetConstant(8, dl, MVT::i32)),
29208                     0);
29209         // Return { result, chain }.
29210         return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
29211                            CopyRBP.getValue(1));
29212       } else {
29213         // 32-bit so no special extended frame, create or reuse an existing
29214         // stack slot.
29215         if (!X86FI->getSwiftAsyncContextFrameIdx())
29216           X86FI->setSwiftAsyncContextFrameIdx(
29217               MF.getFrameInfo().CreateStackObject(4, Align(4), false));
29218         SDValue Result =
29219             DAG.getFrameIndex(*X86FI->getSwiftAsyncContextFrameIdx(), MVT::i32);
29220         // Return { result, chain }.
29221         return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
29222                            Op->getOperand(0));
29223       }
29224     }
29225 
29226     case llvm::Intrinsic::x86_seh_ehregnode:
29227       return MarkEHRegistrationNode(Op, DAG);
29228     case llvm::Intrinsic::x86_seh_ehguard:
29229       return MarkEHGuard(Op, DAG);
29230     case llvm::Intrinsic::x86_rdpkru: {
29231       SDLoc dl(Op);
29232       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
29233       // Create a RDPKRU node and pass 0 to the ECX parameter.
29234       return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
29235                          DAG.getConstant(0, dl, MVT::i32));
29236     }
29237     case llvm::Intrinsic::x86_wrpkru: {
29238       SDLoc dl(Op);
29239       // Create a WRPKRU node, pass the input to the EAX parameter,  and pass 0
29240       // to the EDX and ECX parameters.
29241       return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
29242                          Op.getOperand(0), Op.getOperand(2),
29243                          DAG.getConstant(0, dl, MVT::i32),
29244                          DAG.getConstant(0, dl, MVT::i32));
29245     }
29246     case llvm::Intrinsic::asan_check_memaccess: {
29247       // Mark this as adjustsStack because it will be lowered to a call.
29248       DAG.getMachineFunction().getFrameInfo().setAdjustsStack(true);
29249       // Don't do anything here, we will expand these intrinsics out later.
29250       return Op;
29251     }
29252     case llvm::Intrinsic::x86_flags_read_u32:
29253     case llvm::Intrinsic::x86_flags_read_u64:
29254     case llvm::Intrinsic::x86_flags_write_u32:
29255     case llvm::Intrinsic::x86_flags_write_u64: {
29256       // We need a frame pointer because this will get lowered to a PUSH/POP
29257       // sequence.
29258       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
29259       MFI.setHasCopyImplyingStackAdjustment(true);
29260       // Don't do anything here, we will expand these intrinsics out later
29261       // during FinalizeISel in EmitInstrWithCustomInserter.
29262       return Op;
29263     }
29264     case Intrinsic::x86_lwpins32:
29265     case Intrinsic::x86_lwpins64:
29266     case Intrinsic::x86_umwait:
29267     case Intrinsic::x86_tpause: {
29268       SDLoc dl(Op);
29269       SDValue Chain = Op->getOperand(0);
29270       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
29271       unsigned Opcode;
29272 
29273       switch (IntNo) {
29274       default: llvm_unreachable("Impossible intrinsic");
29275       case Intrinsic::x86_umwait:
29276         Opcode = X86ISD::UMWAIT;
29277         break;
29278       case Intrinsic::x86_tpause:
29279         Opcode = X86ISD::TPAUSE;
29280         break;
29281       case Intrinsic::x86_lwpins32:
29282       case Intrinsic::x86_lwpins64:
29283         Opcode = X86ISD::LWPINS;
29284         break;
29285       }
29286 
29287       SDValue Operation =
29288           DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
29289                       Op->getOperand(3), Op->getOperand(4));
29290       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
29291       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
29292                          Operation.getValue(1));
29293     }
29294     case Intrinsic::x86_enqcmd:
29295     case Intrinsic::x86_enqcmds: {
29296       SDLoc dl(Op);
29297       SDValue Chain = Op.getOperand(0);
29298       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
29299       unsigned Opcode;
29300       switch (IntNo) {
29301       default: llvm_unreachable("Impossible intrinsic!");
29302       case Intrinsic::x86_enqcmd:
29303         Opcode = X86ISD::ENQCMD;
29304         break;
29305       case Intrinsic::x86_enqcmds:
29306         Opcode = X86ISD::ENQCMDS;
29307         break;
29308       }
29309       SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
29310                                       Op.getOperand(3));
29311       SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
29312       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
29313                          Operation.getValue(1));
29314     }
29315     case Intrinsic::x86_aesenc128kl:
29316     case Intrinsic::x86_aesdec128kl:
29317     case Intrinsic::x86_aesenc256kl:
29318     case Intrinsic::x86_aesdec256kl: {
29319       SDLoc DL(Op);
29320       SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
29321       SDValue Chain = Op.getOperand(0);
29322       unsigned Opcode;
29323 
29324       switch (IntNo) {
29325       default: llvm_unreachable("Impossible intrinsic");
29326       case Intrinsic::x86_aesenc128kl:
29327         Opcode = X86ISD::AESENC128KL;
29328         break;
29329       case Intrinsic::x86_aesdec128kl:
29330         Opcode = X86ISD::AESDEC128KL;
29331         break;
29332       case Intrinsic::x86_aesenc256kl:
29333         Opcode = X86ISD::AESENC256KL;
29334         break;
29335       case Intrinsic::x86_aesdec256kl:
29336         Opcode = X86ISD::AESDEC256KL;
29337         break;
29338       }
29339 
29340       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
29341       MachineMemOperand *MMO = MemIntr->getMemOperand();
29342       EVT MemVT = MemIntr->getMemoryVT();
29343       SDValue Operation = DAG.getMemIntrinsicNode(
29344           Opcode, DL, VTs, {Chain, Op.getOperand(2), Op.getOperand(3)}, MemVT,
29345           MMO);
29346       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(1), DL, DAG);
29347 
29348       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
29349                          {ZF, Operation.getValue(0), Operation.getValue(2)});
29350     }
29351     case Intrinsic::x86_aesencwide128kl:
29352     case Intrinsic::x86_aesdecwide128kl:
29353     case Intrinsic::x86_aesencwide256kl:
29354     case Intrinsic::x86_aesdecwide256kl: {
29355       SDLoc DL(Op);
29356       SDVTList VTs = DAG.getVTList(
29357           {MVT::i32, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64,
29358            MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::Other});
29359       SDValue Chain = Op.getOperand(0);
29360       unsigned Opcode;
29361 
29362       switch (IntNo) {
29363       default: llvm_unreachable("Impossible intrinsic");
29364       case Intrinsic::x86_aesencwide128kl:
29365         Opcode = X86ISD::AESENCWIDE128KL;
29366         break;
29367       case Intrinsic::x86_aesdecwide128kl:
29368         Opcode = X86ISD::AESDECWIDE128KL;
29369         break;
29370       case Intrinsic::x86_aesencwide256kl:
29371         Opcode = X86ISD::AESENCWIDE256KL;
29372         break;
29373       case Intrinsic::x86_aesdecwide256kl:
29374         Opcode = X86ISD::AESDECWIDE256KL;
29375         break;
29376       }
29377 
29378       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
29379       MachineMemOperand *MMO = MemIntr->getMemOperand();
29380       EVT MemVT = MemIntr->getMemoryVT();
29381       SDValue Operation = DAG.getMemIntrinsicNode(
29382           Opcode, DL, VTs,
29383           {Chain, Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
29384            Op.getOperand(5), Op.getOperand(6), Op.getOperand(7),
29385            Op.getOperand(8), Op.getOperand(9), Op.getOperand(10)},
29386           MemVT, MMO);
29387       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(0), DL, DAG);
29388 
29389       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
29390                          {ZF, Operation.getValue(1), Operation.getValue(2),
29391                           Operation.getValue(3), Operation.getValue(4),
29392                           Operation.getValue(5), Operation.getValue(6),
29393                           Operation.getValue(7), Operation.getValue(8),
29394                           Operation.getValue(9)});
29395     }
29396     case Intrinsic::x86_testui: {
29397       SDLoc dl(Op);
29398       SDValue Chain = Op.getOperand(0);
29399       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
29400       SDValue Operation = DAG.getNode(X86ISD::TESTUI, dl, VTs, Chain);
29401       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
29402       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
29403                          Operation.getValue(1));
29404     }
29405     case Intrinsic::x86_atomic_bts_rm:
29406     case Intrinsic::x86_atomic_btc_rm:
29407     case Intrinsic::x86_atomic_btr_rm: {
29408       SDLoc DL(Op);
29409       MVT VT = Op.getSimpleValueType();
29410       SDValue Chain = Op.getOperand(0);
29411       SDValue Op1 = Op.getOperand(2);
29412       SDValue Op2 = Op.getOperand(3);
29413       unsigned Opc = IntNo == Intrinsic::x86_atomic_bts_rm   ? X86ISD::LBTS_RM
29414                      : IntNo == Intrinsic::x86_atomic_btc_rm ? X86ISD::LBTC_RM
29415                                                              : X86ISD::LBTR_RM;
29416       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
29417       SDValue Res =
29418           DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
29419                                   {Chain, Op1, Op2}, VT, MMO);
29420       Chain = Res.getValue(1);
29421       Res = DAG.getZExtOrTrunc(getSETCC(X86::COND_B, Res, DL, DAG), DL, VT);
29422       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Res, Chain);
29423     }
29424     case Intrinsic::x86_atomic_bts:
29425     case Intrinsic::x86_atomic_btc:
29426     case Intrinsic::x86_atomic_btr: {
29427       SDLoc DL(Op);
29428       MVT VT = Op.getSimpleValueType();
29429       SDValue Chain = Op.getOperand(0);
29430       SDValue Op1 = Op.getOperand(2);
29431       SDValue Op2 = Op.getOperand(3);
29432       unsigned Opc = IntNo == Intrinsic::x86_atomic_bts   ? X86ISD::LBTS
29433                      : IntNo == Intrinsic::x86_atomic_btc ? X86ISD::LBTC
29434                                                           : X86ISD::LBTR;
29435       SDValue Size = DAG.getConstant(VT.getScalarSizeInBits(), DL, MVT::i32);
29436       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
29437       SDValue Res =
29438           DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
29439                                   {Chain, Op1, Op2, Size}, VT, MMO);
29440       Chain = Res.getValue(1);
29441       Res = DAG.getZExtOrTrunc(getSETCC(X86::COND_B, Res, DL, DAG), DL, VT);
29442       unsigned Imm = cast<ConstantSDNode>(Op2)->getZExtValue();
29443       if (Imm)
29444         Res = DAG.getNode(ISD::SHL, DL, VT, Res,
29445                           DAG.getShiftAmountConstant(Imm, VT, DL));
29446       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Res, Chain);
29447     }
29448     case Intrinsic::x86_cmpccxadd32:
29449     case Intrinsic::x86_cmpccxadd64: {
29450       SDLoc DL(Op);
29451       SDValue Chain = Op.getOperand(0);
29452       SDValue Addr = Op.getOperand(2);
29453       SDValue Src1 = Op.getOperand(3);
29454       SDValue Src2 = Op.getOperand(4);
29455       SDValue CC = Op.getOperand(5);
29456       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
29457       SDValue Operation = DAG.getMemIntrinsicNode(
29458           X86ISD::CMPCCXADD, DL, Op->getVTList(), {Chain, Addr, Src1, Src2, CC},
29459           MVT::i32, MMO);
29460       return Operation;
29461     }
29462     case Intrinsic::x86_aadd32:
29463     case Intrinsic::x86_aadd64:
29464     case Intrinsic::x86_aand32:
29465     case Intrinsic::x86_aand64:
29466     case Intrinsic::x86_aor32:
29467     case Intrinsic::x86_aor64:
29468     case Intrinsic::x86_axor32:
29469     case Intrinsic::x86_axor64: {
29470       SDLoc DL(Op);
29471       SDValue Chain = Op.getOperand(0);
29472       SDValue Op1 = Op.getOperand(2);
29473       SDValue Op2 = Op.getOperand(3);
29474       MVT VT = Op2.getSimpleValueType();
29475       unsigned Opc = 0;
29476       switch (IntNo) {
29477       default:
29478         llvm_unreachable("Unknown Intrinsic");
29479       case Intrinsic::x86_aadd32:
29480       case Intrinsic::x86_aadd64:
29481         Opc = X86ISD::AADD;
29482         break;
29483       case Intrinsic::x86_aand32:
29484       case Intrinsic::x86_aand64:
29485         Opc = X86ISD::AAND;
29486         break;
29487       case Intrinsic::x86_aor32:
29488       case Intrinsic::x86_aor64:
29489         Opc = X86ISD::AOR;
29490         break;
29491       case Intrinsic::x86_axor32:
29492       case Intrinsic::x86_axor64:
29493         Opc = X86ISD::AXOR;
29494         break;
29495       }
29496       MachineMemOperand *MMO = cast<MemSDNode>(Op)->getMemOperand();
29497       return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(),
29498                                      {Chain, Op1, Op2}, VT, MMO);
29499     }
29500     case Intrinsic::x86_atomic_add_cc:
29501     case Intrinsic::x86_atomic_sub_cc:
29502     case Intrinsic::x86_atomic_or_cc:
29503     case Intrinsic::x86_atomic_and_cc:
29504     case Intrinsic::x86_atomic_xor_cc: {
29505       SDLoc DL(Op);
29506       SDValue Chain = Op.getOperand(0);
29507       SDValue Op1 = Op.getOperand(2);
29508       SDValue Op2 = Op.getOperand(3);
29509       X86::CondCode CC = (X86::CondCode)Op.getConstantOperandVal(4);
29510       MVT VT = Op2.getSimpleValueType();
29511       unsigned Opc = 0;
29512       switch (IntNo) {
29513       default:
29514         llvm_unreachable("Unknown Intrinsic");
29515       case Intrinsic::x86_atomic_add_cc:
29516         Opc = X86ISD::LADD;
29517         break;
29518       case Intrinsic::x86_atomic_sub_cc:
29519         Opc = X86ISD::LSUB;
29520         break;
29521       case Intrinsic::x86_atomic_or_cc:
29522         Opc = X86ISD::LOR;
29523         break;
29524       case Intrinsic::x86_atomic_and_cc:
29525         Opc = X86ISD::LAND;
29526         break;
29527       case Intrinsic::x86_atomic_xor_cc:
29528         Opc = X86ISD::LXOR;
29529         break;
29530       }
29531       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
29532       SDValue LockArith =
29533           DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
29534                                   {Chain, Op1, Op2}, VT, MMO);
29535       Chain = LockArith.getValue(1);
29536       return DAG.getMergeValues({getSETCC(CC, LockArith, DL, DAG), Chain}, DL);
29537     }
29538     }
29539     return SDValue();
29540   }
29541 
29542   SDLoc dl(Op);
29543   switch(IntrData->Type) {
29544   default: llvm_unreachable("Unknown Intrinsic Type");
29545   case RDSEED:
29546   case RDRAND: {
29547     // Emit the node with the right value type.
29548     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
29549     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
29550 
29551     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
29552     // Otherwise return the value from Rand, which is always 0, casted to i32.
29553     SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
29554                      DAG.getConstant(1, dl, Op->getValueType(1)),
29555                      DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
29556                      SDValue(Result.getNode(), 1)};
29557     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
29558 
29559     // Return { result, isValid, chain }.
29560     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
29561                        SDValue(Result.getNode(), 2));
29562   }
29563   case GATHER_AVX2: {
29564     SDValue Chain = Op.getOperand(0);
29565     SDValue Src   = Op.getOperand(2);
29566     SDValue Base  = Op.getOperand(3);
29567     SDValue Index = Op.getOperand(4);
29568     SDValue Mask  = Op.getOperand(5);
29569     SDValue Scale = Op.getOperand(6);
29570     return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
29571                              Scale, Chain, Subtarget);
29572   }
29573   case GATHER: {
29574   //gather(v1, mask, index, base, scale);
29575     SDValue Chain = Op.getOperand(0);
29576     SDValue Src   = Op.getOperand(2);
29577     SDValue Base  = Op.getOperand(3);
29578     SDValue Index = Op.getOperand(4);
29579     SDValue Mask  = Op.getOperand(5);
29580     SDValue Scale = Op.getOperand(6);
29581     return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
29582                          Chain, Subtarget);
29583   }
29584   case SCATTER: {
29585   //scatter(base, mask, index, v1, scale);
29586     SDValue Chain = Op.getOperand(0);
29587     SDValue Base  = Op.getOperand(2);
29588     SDValue Mask  = Op.getOperand(3);
29589     SDValue Index = Op.getOperand(4);
29590     SDValue Src   = Op.getOperand(5);
29591     SDValue Scale = Op.getOperand(6);
29592     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
29593                           Scale, Chain, Subtarget);
29594   }
29595   case PREFETCH: {
29596     const APInt &HintVal = Op.getConstantOperandAPInt(6);
29597     assert((HintVal == 2 || HintVal == 3) &&
29598            "Wrong prefetch hint in intrinsic: should be 2 or 3");
29599     unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
29600     SDValue Chain = Op.getOperand(0);
29601     SDValue Mask  = Op.getOperand(2);
29602     SDValue Index = Op.getOperand(3);
29603     SDValue Base  = Op.getOperand(4);
29604     SDValue Scale = Op.getOperand(5);
29605     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
29606                            Subtarget);
29607   }
29608   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
29609   case RDTSC: {
29610     SmallVector<SDValue, 2> Results;
29611     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
29612                             Results);
29613     return DAG.getMergeValues(Results, dl);
29614   }
29615   // Read Performance Monitoring Counters.
29616   case RDPMC:
29617   // Read Processor Register.
29618   case RDPRU:
29619   // GetExtended Control Register.
29620   case XGETBV: {
29621     SmallVector<SDValue, 2> Results;
29622 
29623     // RDPMC uses ECX to select the index of the performance counter to read.
29624     // RDPRU uses ECX to select the processor register to read.
29625     // XGETBV uses ECX to select the index of the XCR register to return.
29626     // The result is stored into registers EDX:EAX.
29627     expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
29628                                 Subtarget, Results);
29629     return DAG.getMergeValues(Results, dl);
29630   }
29631   // XTEST intrinsics.
29632   case XTEST: {
29633     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
29634     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
29635 
29636     SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
29637     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
29638     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
29639                        Ret, SDValue(InTrans.getNode(), 1));
29640   }
29641   case TRUNCATE_TO_MEM_VI8:
29642   case TRUNCATE_TO_MEM_VI16:
29643   case TRUNCATE_TO_MEM_VI32: {
29644     SDValue Mask = Op.getOperand(4);
29645     SDValue DataToTruncate = Op.getOperand(3);
29646     SDValue Addr = Op.getOperand(2);
29647     SDValue Chain = Op.getOperand(0);
29648 
29649     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
29650     assert(MemIntr && "Expected MemIntrinsicSDNode!");
29651 
29652     EVT MemVT  = MemIntr->getMemoryVT();
29653 
29654     uint16_t TruncationOp = IntrData->Opc0;
29655     switch (TruncationOp) {
29656     case X86ISD::VTRUNC: {
29657       if (isAllOnesConstant(Mask)) // return just a truncate store
29658         return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
29659                                  MemIntr->getMemOperand());
29660 
29661       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
29662       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
29663       SDValue Offset = DAG.getUNDEF(VMask.getValueType());
29664 
29665       return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
29666                                 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
29667                                 true /* truncating */);
29668     }
29669     case X86ISD::VTRUNCUS:
29670     case X86ISD::VTRUNCS: {
29671       bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
29672       if (isAllOnesConstant(Mask))
29673         return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
29674                                MemIntr->getMemOperand(), DAG);
29675 
29676       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
29677       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
29678 
29679       return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
29680                                    VMask, MemVT, MemIntr->getMemOperand(), DAG);
29681     }
29682     default:
29683       llvm_unreachable("Unsupported truncstore intrinsic");
29684     }
29685   }
29686   }
29687 }
29688 
29689 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
29690                                            SelectionDAG &DAG) const {
29691   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
29692   MFI.setReturnAddressIsTaken(true);
29693 
29694   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
29695     return SDValue();
29696 
29697   unsigned Depth = Op.getConstantOperandVal(0);
29698   SDLoc dl(Op);
29699   EVT PtrVT = getPointerTy(DAG.getDataLayout());
29700 
29701   if (Depth > 0) {
29702     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
29703     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
29704     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
29705     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
29706                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
29707                        MachinePointerInfo());
29708   }
29709 
29710   // Just load the return address.
29711   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
29712   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
29713                      MachinePointerInfo());
29714 }
29715 
29716 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
29717                                                  SelectionDAG &DAG) const {
29718   DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
29719   return getReturnAddressFrameIndex(DAG);
29720 }
29721 
29722 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
29723   MachineFunction &MF = DAG.getMachineFunction();
29724   MachineFrameInfo &MFI = MF.getFrameInfo();
29725   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
29726   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
29727   EVT VT = Op.getValueType();
29728 
29729   MFI.setFrameAddressIsTaken(true);
29730 
29731   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
29732     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
29733     // is not possible to crawl up the stack without looking at the unwind codes
29734     // simultaneously.
29735     int FrameAddrIndex = FuncInfo->getFAIndex();
29736     if (!FrameAddrIndex) {
29737       // Set up a frame object for the return address.
29738       unsigned SlotSize = RegInfo->getSlotSize();
29739       FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
29740           SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
29741       FuncInfo->setFAIndex(FrameAddrIndex);
29742     }
29743     return DAG.getFrameIndex(FrameAddrIndex, VT);
29744   }
29745 
29746   unsigned FrameReg =
29747       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
29748   SDLoc dl(Op);  // FIXME probably not meaningful
29749   unsigned Depth = Op.getConstantOperandVal(0);
29750   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
29751           (FrameReg == X86::EBP && VT == MVT::i32)) &&
29752          "Invalid Frame Register!");
29753   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
29754   while (Depth--)
29755     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
29756                             MachinePointerInfo());
29757   return FrameAddr;
29758 }
29759 
29760 // FIXME? Maybe this could be a TableGen attribute on some registers and
29761 // this table could be generated automatically from RegInfo.
29762 Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
29763                                               const MachineFunction &MF) const {
29764   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
29765 
29766   Register Reg = StringSwitch<unsigned>(RegName)
29767                        .Case("esp", X86::ESP)
29768                        .Case("rsp", X86::RSP)
29769                        .Case("ebp", X86::EBP)
29770                        .Case("rbp", X86::RBP)
29771                        .Default(0);
29772 
29773   if (Reg == X86::EBP || Reg == X86::RBP) {
29774     if (!TFI.hasFP(MF))
29775       report_fatal_error("register " + StringRef(RegName) +
29776                          " is allocatable: function has no frame pointer");
29777 #ifndef NDEBUG
29778     else {
29779       const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
29780       Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
29781       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
29782              "Invalid Frame Register!");
29783     }
29784 #endif
29785   }
29786 
29787   if (Reg)
29788     return Reg;
29789 
29790   report_fatal_error("Invalid register name global variable");
29791 }
29792 
29793 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
29794                                                      SelectionDAG &DAG) const {
29795   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
29796   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
29797 }
29798 
29799 Register X86TargetLowering::getExceptionPointerRegister(
29800     const Constant *PersonalityFn) const {
29801   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
29802     return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
29803 
29804   return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
29805 }
29806 
29807 Register X86TargetLowering::getExceptionSelectorRegister(
29808     const Constant *PersonalityFn) const {
29809   // Funclet personalities don't use selectors (the runtime does the selection).
29810   if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
29811     return X86::NoRegister;
29812   return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
29813 }
29814 
29815 bool X86TargetLowering::needsFixedCatchObjects() const {
29816   return Subtarget.isTargetWin64();
29817 }
29818 
29819 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
29820   SDValue Chain     = Op.getOperand(0);
29821   SDValue Offset    = Op.getOperand(1);
29822   SDValue Handler   = Op.getOperand(2);
29823   SDLoc dl      (Op);
29824 
29825   EVT PtrVT = getPointerTy(DAG.getDataLayout());
29826   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
29827   Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
29828   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
29829           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
29830          "Invalid Frame Register!");
29831   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
29832   Register StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
29833 
29834   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
29835                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
29836                                                        dl));
29837   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
29838   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
29839   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
29840 
29841   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
29842                      DAG.getRegister(StoreAddrReg, PtrVT));
29843 }
29844 
29845 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
29846                                                SelectionDAG &DAG) const {
29847   SDLoc DL(Op);
29848   // If the subtarget is not 64bit, we may need the global base reg
29849   // after isel expand pseudo, i.e., after CGBR pass ran.
29850   // Therefore, ask for the GlobalBaseReg now, so that the pass
29851   // inserts the code for us in case we need it.
29852   // Otherwise, we will end up in a situation where we will
29853   // reference a virtual register that is not defined!
29854   if (!Subtarget.is64Bit()) {
29855     const X86InstrInfo *TII = Subtarget.getInstrInfo();
29856     (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
29857   }
29858   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
29859                      DAG.getVTList(MVT::i32, MVT::Other),
29860                      Op.getOperand(0), Op.getOperand(1));
29861 }
29862 
29863 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
29864                                                 SelectionDAG &DAG) const {
29865   SDLoc DL(Op);
29866   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
29867                      Op.getOperand(0), Op.getOperand(1));
29868 }
29869 
29870 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
29871                                                        SelectionDAG &DAG) const {
29872   SDLoc DL(Op);
29873   return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
29874                      Op.getOperand(0));
29875 }
29876 
29877 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
29878   return Op.getOperand(0);
29879 }
29880 
29881 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
29882                                                 SelectionDAG &DAG) const {
29883   SDValue Root = Op.getOperand(0);
29884   SDValue Trmp = Op.getOperand(1); // trampoline
29885   SDValue FPtr = Op.getOperand(2); // nested function
29886   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
29887   SDLoc dl (Op);
29888 
29889   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
29890   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
29891 
29892   if (Subtarget.is64Bit()) {
29893     SDValue OutChains[6];
29894 
29895     // Large code-model.
29896     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
29897     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
29898 
29899     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
29900     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
29901 
29902     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
29903 
29904     // Load the pointer to the nested function into R11.
29905     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
29906     SDValue Addr = Trmp;
29907     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
29908                                 Addr, MachinePointerInfo(TrmpAddr));
29909 
29910     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
29911                        DAG.getConstant(2, dl, MVT::i64));
29912     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
29913                                 MachinePointerInfo(TrmpAddr, 2), Align(2));
29914 
29915     // Load the 'nest' parameter value into R10.
29916     // R10 is specified in X86CallingConv.td
29917     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
29918     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
29919                        DAG.getConstant(10, dl, MVT::i64));
29920     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
29921                                 Addr, MachinePointerInfo(TrmpAddr, 10));
29922 
29923     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
29924                        DAG.getConstant(12, dl, MVT::i64));
29925     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
29926                                 MachinePointerInfo(TrmpAddr, 12), Align(2));
29927 
29928     // Jump to the nested function.
29929     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
29930     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
29931                        DAG.getConstant(20, dl, MVT::i64));
29932     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
29933                                 Addr, MachinePointerInfo(TrmpAddr, 20));
29934 
29935     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
29936     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
29937                        DAG.getConstant(22, dl, MVT::i64));
29938     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
29939                                 Addr, MachinePointerInfo(TrmpAddr, 22));
29940 
29941     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
29942   } else {
29943     const Function *Func =
29944       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
29945     CallingConv::ID CC = Func->getCallingConv();
29946     unsigned NestReg;
29947 
29948     switch (CC) {
29949     default:
29950       llvm_unreachable("Unsupported calling convention");
29951     case CallingConv::C:
29952     case CallingConv::X86_StdCall: {
29953       // Pass 'nest' parameter in ECX.
29954       // Must be kept in sync with X86CallingConv.td
29955       NestReg = X86::ECX;
29956 
29957       // Check that ECX wasn't needed by an 'inreg' parameter.
29958       FunctionType *FTy = Func->getFunctionType();
29959       const AttributeList &Attrs = Func->getAttributes();
29960 
29961       if (!Attrs.isEmpty() && !Func->isVarArg()) {
29962         unsigned InRegCount = 0;
29963         unsigned Idx = 0;
29964 
29965         for (FunctionType::param_iterator I = FTy->param_begin(),
29966              E = FTy->param_end(); I != E; ++I, ++Idx)
29967           if (Attrs.hasParamAttr(Idx, Attribute::InReg)) {
29968             const DataLayout &DL = DAG.getDataLayout();
29969             // FIXME: should only count parameters that are lowered to integers.
29970             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
29971           }
29972 
29973         if (InRegCount > 2) {
29974           report_fatal_error("Nest register in use - reduce number of inreg"
29975                              " parameters!");
29976         }
29977       }
29978       break;
29979     }
29980     case CallingConv::X86_FastCall:
29981     case CallingConv::X86_ThisCall:
29982     case CallingConv::Fast:
29983     case CallingConv::Tail:
29984     case CallingConv::SwiftTail:
29985       // Pass 'nest' parameter in EAX.
29986       // Must be kept in sync with X86CallingConv.td
29987       NestReg = X86::EAX;
29988       break;
29989     }
29990 
29991     SDValue OutChains[4];
29992     SDValue Addr, Disp;
29993 
29994     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
29995                        DAG.getConstant(10, dl, MVT::i32));
29996     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
29997 
29998     // This is storing the opcode for MOV32ri.
29999     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
30000     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
30001     OutChains[0] =
30002         DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
30003                      Trmp, MachinePointerInfo(TrmpAddr));
30004 
30005     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
30006                        DAG.getConstant(1, dl, MVT::i32));
30007     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
30008                                 MachinePointerInfo(TrmpAddr, 1), Align(1));
30009 
30010     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
30011     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
30012                        DAG.getConstant(5, dl, MVT::i32));
30013     OutChains[2] =
30014         DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8), Addr,
30015                      MachinePointerInfo(TrmpAddr, 5), Align(1));
30016 
30017     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
30018                        DAG.getConstant(6, dl, MVT::i32));
30019     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
30020                                 MachinePointerInfo(TrmpAddr, 6), Align(1));
30021 
30022     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
30023   }
30024 }
30025 
30026 SDValue X86TargetLowering::LowerGET_ROUNDING(SDValue Op,
30027                                              SelectionDAG &DAG) const {
30028   /*
30029    The rounding mode is in bits 11:10 of FPSR, and has the following
30030    settings:
30031      00 Round to nearest
30032      01 Round to -inf
30033      10 Round to +inf
30034      11 Round to 0
30035 
30036   GET_ROUNDING, on the other hand, expects the following:
30037     -1 Undefined
30038      0 Round to 0
30039      1 Round to nearest
30040      2 Round to +inf
30041      3 Round to -inf
30042 
30043   To perform the conversion, we use a packed lookup table of the four 2-bit
30044   values that we can index by FPSP[11:10]
30045     0x2d --> (0b00,10,11,01) --> (0,2,3,1) >> FPSR[11:10]
30046 
30047     (0x2d >> ((FPSR & 0xc00) >> 9)) & 3
30048   */
30049 
30050   MachineFunction &MF = DAG.getMachineFunction();
30051   MVT VT = Op.getSimpleValueType();
30052   SDLoc DL(Op);
30053 
30054   // Save FP Control Word to stack slot
30055   int SSFI = MF.getFrameInfo().CreateStackObject(2, Align(2), false);
30056   SDValue StackSlot =
30057       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
30058 
30059   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
30060 
30061   SDValue Chain = Op.getOperand(0);
30062   SDValue Ops[] = {Chain, StackSlot};
30063   Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
30064                                   DAG.getVTList(MVT::Other), Ops, MVT::i16, MPI,
30065                                   Align(2), MachineMemOperand::MOStore);
30066 
30067   // Load FP Control Word from stack slot
30068   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI, Align(2));
30069   Chain = CWD.getValue(1);
30070 
30071   // Mask and turn the control bits into a shift for the lookup table.
30072   SDValue Shift =
30073     DAG.getNode(ISD::SRL, DL, MVT::i16,
30074                 DAG.getNode(ISD::AND, DL, MVT::i16,
30075                             CWD, DAG.getConstant(0xc00, DL, MVT::i16)),
30076                 DAG.getConstant(9, DL, MVT::i8));
30077   Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Shift);
30078 
30079   SDValue LUT = DAG.getConstant(0x2d, DL, MVT::i32);
30080   SDValue RetVal =
30081     DAG.getNode(ISD::AND, DL, MVT::i32,
30082                 DAG.getNode(ISD::SRL, DL, MVT::i32, LUT, Shift),
30083                 DAG.getConstant(3, DL, MVT::i32));
30084 
30085   RetVal = DAG.getZExtOrTrunc(RetVal, DL, VT);
30086 
30087   return DAG.getMergeValues({RetVal, Chain}, DL);
30088 }
30089 
30090 SDValue X86TargetLowering::LowerSET_ROUNDING(SDValue Op,
30091                                              SelectionDAG &DAG) const {
30092   MachineFunction &MF = DAG.getMachineFunction();
30093   SDLoc DL(Op);
30094   SDValue Chain = Op.getNode()->getOperand(0);
30095 
30096   // FP control word may be set only from data in memory. So we need to allocate
30097   // stack space to save/load FP control word.
30098   int OldCWFrameIdx = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
30099   SDValue StackSlot =
30100       DAG.getFrameIndex(OldCWFrameIdx, getPointerTy(DAG.getDataLayout()));
30101   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, OldCWFrameIdx);
30102   MachineMemOperand *MMO =
30103       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 2, Align(2));
30104 
30105   // Store FP control word into memory.
30106   SDValue Ops[] = {Chain, StackSlot};
30107   Chain = DAG.getMemIntrinsicNode(
30108       X86ISD::FNSTCW16m, DL, DAG.getVTList(MVT::Other), Ops, MVT::i16, MMO);
30109 
30110   // Load FP Control Word from stack slot and clear RM field (bits 11:10).
30111   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI);
30112   Chain = CWD.getValue(1);
30113   CWD = DAG.getNode(ISD::AND, DL, MVT::i16, CWD.getValue(0),
30114                     DAG.getConstant(0xf3ff, DL, MVT::i16));
30115 
30116   // Calculate new rounding mode.
30117   SDValue NewRM = Op.getNode()->getOperand(1);
30118   SDValue RMBits;
30119   if (auto *CVal = dyn_cast<ConstantSDNode>(NewRM)) {
30120     uint64_t RM = CVal->getZExtValue();
30121     int FieldVal;
30122     switch (static_cast<RoundingMode>(RM)) {
30123     case RoundingMode::NearestTiesToEven: FieldVal = X86::rmToNearest; break;
30124     case RoundingMode::TowardNegative:    FieldVal = X86::rmDownward; break;
30125     case RoundingMode::TowardPositive:    FieldVal = X86::rmUpward; break;
30126     case RoundingMode::TowardZero:        FieldVal = X86::rmTowardZero; break;
30127     default:
30128       llvm_unreachable("rounding mode is not supported by X86 hardware");
30129     }
30130     RMBits = DAG.getConstant(FieldVal, DL, MVT::i16);
30131   } else {
30132     // Need to convert argument into bits of control word:
30133     //    0 Round to 0       -> 11
30134     //    1 Round to nearest -> 00
30135     //    2 Round to +inf    -> 10
30136     //    3 Round to -inf    -> 01
30137     // The 2-bit value needs then to be shifted so that it occupies bits 11:10.
30138     // To make the conversion, put all these values into a value 0xc9 and shift
30139     // it left depending on the rounding mode:
30140     //    (0xc9 << 4) & 0xc00 = X86::rmTowardZero
30141     //    (0xc9 << 6) & 0xc00 = X86::rmToNearest
30142     //    ...
30143     // (0xc9 << (2 * NewRM + 4)) & 0xc00
30144     SDValue ShiftValue =
30145         DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
30146                     DAG.getNode(ISD::ADD, DL, MVT::i32,
30147                                 DAG.getNode(ISD::SHL, DL, MVT::i32, NewRM,
30148                                             DAG.getConstant(1, DL, MVT::i8)),
30149                                 DAG.getConstant(4, DL, MVT::i32)));
30150     SDValue Shifted =
30151         DAG.getNode(ISD::SHL, DL, MVT::i16, DAG.getConstant(0xc9, DL, MVT::i16),
30152                     ShiftValue);
30153     RMBits = DAG.getNode(ISD::AND, DL, MVT::i16, Shifted,
30154                          DAG.getConstant(0xc00, DL, MVT::i16));
30155   }
30156 
30157   // Update rounding mode bits and store the new FP Control Word into stack.
30158   CWD = DAG.getNode(ISD::OR, DL, MVT::i16, CWD, RMBits);
30159   Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, Align(2));
30160 
30161   // Load FP control word from the slot.
30162   SDValue OpsLD[] = {Chain, StackSlot};
30163   MachineMemOperand *MMOL =
30164       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 2, Align(2));
30165   Chain = DAG.getMemIntrinsicNode(
30166       X86ISD::FLDCW16m, DL, DAG.getVTList(MVT::Other), OpsLD, MVT::i16, MMOL);
30167 
30168   // If target supports SSE, set MXCSR as well. Rounding mode is encoded in the
30169   // same way but in bits 14:13.
30170   if (Subtarget.hasSSE1()) {
30171     // Store MXCSR into memory.
30172     Chain = DAG.getNode(
30173         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
30174         DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
30175         StackSlot);
30176 
30177     // Load MXCSR from stack slot and clear RM field (bits 14:13).
30178     SDValue CWD = DAG.getLoad(MVT::i32, DL, Chain, StackSlot, MPI);
30179     Chain = CWD.getValue(1);
30180     CWD = DAG.getNode(ISD::AND, DL, MVT::i32, CWD.getValue(0),
30181                       DAG.getConstant(0xffff9fff, DL, MVT::i32));
30182 
30183     // Shift X87 RM bits from 11:10 to 14:13.
30184     RMBits = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, RMBits);
30185     RMBits = DAG.getNode(ISD::SHL, DL, MVT::i32, RMBits,
30186                          DAG.getConstant(3, DL, MVT::i8));
30187 
30188     // Update rounding mode bits and store the new FP Control Word into stack.
30189     CWD = DAG.getNode(ISD::OR, DL, MVT::i32, CWD, RMBits);
30190     Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, Align(4));
30191 
30192     // Load MXCSR from the slot.
30193     Chain = DAG.getNode(
30194         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
30195         DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
30196         StackSlot);
30197   }
30198 
30199   return Chain;
30200 }
30201 
30202 const unsigned X87StateSize = 28;
30203 const unsigned FPStateSize = 32;
30204 [[maybe_unused]] const unsigned FPStateSizeInBits = FPStateSize * 8;
30205 
30206 SDValue X86TargetLowering::LowerGET_FPENV_MEM(SDValue Op,
30207                                               SelectionDAG &DAG) const {
30208   MachineFunction &MF = DAG.getMachineFunction();
30209   SDLoc DL(Op);
30210   SDValue Chain = Op->getOperand(0);
30211   SDValue Ptr = Op->getOperand(1);
30212   auto *Node = cast<FPStateAccessSDNode>(Op);
30213   EVT MemVT = Node->getMemoryVT();
30214   assert(MemVT.getSizeInBits() == FPStateSizeInBits);
30215   MachineMemOperand *MMO = cast<FPStateAccessSDNode>(Op)->getMemOperand();
30216 
30217   // Get x87 state, if it presents.
30218   if (Subtarget.hasX87()) {
30219     Chain =
30220         DAG.getMemIntrinsicNode(X86ISD::FNSTENVm, DL, DAG.getVTList(MVT::Other),
30221                                 {Chain, Ptr}, MemVT, MMO);
30222 
30223     // FNSTENV changes the exception mask, so load back the stored environment.
30224     MachineMemOperand::Flags NewFlags =
30225         MachineMemOperand::MOLoad |
30226         (MMO->getFlags() & ~MachineMemOperand::MOStore);
30227     MMO = MF.getMachineMemOperand(MMO, NewFlags);
30228     Chain =
30229         DAG.getMemIntrinsicNode(X86ISD::FLDENVm, DL, DAG.getVTList(MVT::Other),
30230                                 {Chain, Ptr}, MemVT, MMO);
30231   }
30232 
30233   // If target supports SSE, get MXCSR as well.
30234   if (Subtarget.hasSSE1()) {
30235     // Get pointer to the MXCSR location in memory.
30236     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
30237     SDValue MXCSRAddr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr,
30238                                     DAG.getConstant(X87StateSize, DL, PtrVT));
30239     // Store MXCSR into memory.
30240     Chain = DAG.getNode(
30241         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
30242         DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
30243         MXCSRAddr);
30244   }
30245 
30246   return Chain;
30247 }
30248 
30249 static SDValue createSetFPEnvNodes(SDValue Ptr, SDValue Chain, SDLoc DL,
30250                                    EVT MemVT, MachineMemOperand *MMO,
30251                                    SelectionDAG &DAG,
30252                                    const X86Subtarget &Subtarget) {
30253   // Set x87 state, if it presents.
30254   if (Subtarget.hasX87())
30255     Chain =
30256         DAG.getMemIntrinsicNode(X86ISD::FLDENVm, DL, DAG.getVTList(MVT::Other),
30257                                 {Chain, Ptr}, MemVT, MMO);
30258   // If target supports SSE, set MXCSR as well.
30259   if (Subtarget.hasSSE1()) {
30260     // Get pointer to the MXCSR location in memory.
30261     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
30262     SDValue MXCSRAddr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr,
30263                                     DAG.getConstant(X87StateSize, DL, PtrVT));
30264     // Load MXCSR from memory.
30265     Chain = DAG.getNode(
30266         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
30267         DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
30268         MXCSRAddr);
30269   }
30270   return Chain;
30271 }
30272 
30273 SDValue X86TargetLowering::LowerSET_FPENV_MEM(SDValue Op,
30274                                               SelectionDAG &DAG) const {
30275   SDLoc DL(Op);
30276   SDValue Chain = Op->getOperand(0);
30277   SDValue Ptr = Op->getOperand(1);
30278   auto *Node = cast<FPStateAccessSDNode>(Op);
30279   EVT MemVT = Node->getMemoryVT();
30280   assert(MemVT.getSizeInBits() == FPStateSizeInBits);
30281   MachineMemOperand *MMO = cast<FPStateAccessSDNode>(Op)->getMemOperand();
30282   return createSetFPEnvNodes(Ptr, Chain, DL, MemVT, MMO, DAG, Subtarget);
30283 }
30284 
30285 SDValue X86TargetLowering::LowerRESET_FPENV(SDValue Op,
30286                                             SelectionDAG &DAG) const {
30287   MachineFunction &MF = DAG.getMachineFunction();
30288   SDLoc DL(Op);
30289   SDValue Chain = Op.getNode()->getOperand(0);
30290 
30291   IntegerType *ItemTy = Type::getInt32Ty(*DAG.getContext());
30292   ArrayType *FPEnvTy = ArrayType::get(ItemTy, 8);
30293   SmallVector<Constant *, 8> FPEnvVals;
30294 
30295   // x87 FPU Control Word: mask all floating-point exceptions, sets rounding to
30296   // nearest. FPU precision is set to 53 bits on Windows and 64 bits otherwise
30297   // for compatibility with glibc.
30298   unsigned X87CW = Subtarget.isTargetWindowsMSVC() ? 0x27F : 0x37F;
30299   FPEnvVals.push_back(ConstantInt::get(ItemTy, X87CW));
30300   Constant *Zero = ConstantInt::get(ItemTy, 0);
30301   for (unsigned I = 0; I < 6; ++I)
30302     FPEnvVals.push_back(Zero);
30303 
30304   // MXCSR: mask all floating-point exceptions, sets rounding to nearest, clear
30305   // all exceptions, sets DAZ and FTZ to 0.
30306   FPEnvVals.push_back(ConstantInt::get(ItemTy, 0x1F80));
30307   Constant *FPEnvBits = ConstantArray::get(FPEnvTy, FPEnvVals);
30308   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
30309   SDValue Env = DAG.getConstantPool(FPEnvBits, PtrVT);
30310   MachinePointerInfo MPI =
30311       MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
30312   MachineMemOperand *MMO = MF.getMachineMemOperand(
30313       MPI, MachineMemOperand::MOStore, X87StateSize, Align(4));
30314 
30315   return createSetFPEnvNodes(Env, Chain, DL, MVT::i32, MMO, DAG, Subtarget);
30316 }
30317 
30318 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
30319 //
30320 // i8/i16 vector implemented using dword LZCNT vector instruction
30321 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
30322 // split the vector, perform operation on it's Lo a Hi part and
30323 // concatenate the results.
30324 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
30325                                          const X86Subtarget &Subtarget) {
30326   assert(Op.getOpcode() == ISD::CTLZ);
30327   SDLoc dl(Op);
30328   MVT VT = Op.getSimpleValueType();
30329   MVT EltVT = VT.getVectorElementType();
30330   unsigned NumElems = VT.getVectorNumElements();
30331 
30332   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
30333           "Unsupported element type");
30334 
30335   // Split vector, it's Lo and Hi parts will be handled in next iteration.
30336   if (NumElems > 16 ||
30337       (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
30338     return splitVectorIntUnary(Op, DAG);
30339 
30340   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
30341   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
30342           "Unsupported value type for operation");
30343 
30344   // Use native supported vector instruction vplzcntd.
30345   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
30346   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
30347   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
30348   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
30349 
30350   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
30351 }
30352 
30353 // Lower CTLZ using a PSHUFB lookup table implementation.
30354 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
30355                                        const X86Subtarget &Subtarget,
30356                                        SelectionDAG &DAG) {
30357   MVT VT = Op.getSimpleValueType();
30358   int NumElts = VT.getVectorNumElements();
30359   int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
30360   MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
30361 
30362   // Per-nibble leading zero PSHUFB lookup table.
30363   const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
30364                        /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
30365                        /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
30366                        /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
30367 
30368   SmallVector<SDValue, 64> LUTVec;
30369   for (int i = 0; i < NumBytes; ++i)
30370     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
30371   SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
30372 
30373   // Begin by bitcasting the input to byte vector, then split those bytes
30374   // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
30375   // If the hi input nibble is zero then we add both results together, otherwise
30376   // we just take the hi result (by masking the lo result to zero before the
30377   // add).
30378   SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
30379   SDValue Zero = DAG.getConstant(0, DL, CurrVT);
30380 
30381   SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
30382   SDValue Lo = Op0;
30383   SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
30384   SDValue HiZ;
30385   if (CurrVT.is512BitVector()) {
30386     MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
30387     HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
30388     HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
30389   } else {
30390     HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
30391   }
30392 
30393   Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
30394   Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
30395   Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
30396   SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
30397 
30398   // Merge result back from vXi8 back to VT, working on the lo/hi halves
30399   // of the current vector width in the same way we did for the nibbles.
30400   // If the upper half of the input element is zero then add the halves'
30401   // leading zero counts together, otherwise just use the upper half's.
30402   // Double the width of the result until we are at target width.
30403   while (CurrVT != VT) {
30404     int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
30405     int CurrNumElts = CurrVT.getVectorNumElements();
30406     MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
30407     MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
30408     SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
30409 
30410     // Check if the upper half of the input element is zero.
30411     if (CurrVT.is512BitVector()) {
30412       MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
30413       HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
30414                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
30415       HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
30416     } else {
30417       HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
30418                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
30419     }
30420     HiZ = DAG.getBitcast(NextVT, HiZ);
30421 
30422     // Move the upper/lower halves to the lower bits as we'll be extending to
30423     // NextVT. Mask the lower result to zero if HiZ is true and add the results
30424     // together.
30425     SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
30426     SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
30427     SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
30428     R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
30429     Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
30430     CurrVT = NextVT;
30431   }
30432 
30433   return Res;
30434 }
30435 
30436 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
30437                                const X86Subtarget &Subtarget,
30438                                SelectionDAG &DAG) {
30439   MVT VT = Op.getSimpleValueType();
30440 
30441   if (Subtarget.hasCDI() &&
30442       // vXi8 vectors need to be promoted to 512-bits for vXi32.
30443       (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
30444     return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
30445 
30446   // Decompose 256-bit ops into smaller 128-bit ops.
30447   if (VT.is256BitVector() && !Subtarget.hasInt256())
30448     return splitVectorIntUnary(Op, DAG);
30449 
30450   // Decompose 512-bit ops into smaller 256-bit ops.
30451   if (VT.is512BitVector() && !Subtarget.hasBWI())
30452     return splitVectorIntUnary(Op, DAG);
30453 
30454   assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
30455   return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
30456 }
30457 
30458 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
30459                          SelectionDAG &DAG) {
30460   MVT VT = Op.getSimpleValueType();
30461   MVT OpVT = VT;
30462   unsigned NumBits = VT.getSizeInBits();
30463   SDLoc dl(Op);
30464   unsigned Opc = Op.getOpcode();
30465 
30466   if (VT.isVector())
30467     return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
30468 
30469   Op = Op.getOperand(0);
30470   if (VT == MVT::i8) {
30471     // Zero extend to i32 since there is not an i8 bsr.
30472     OpVT = MVT::i32;
30473     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
30474   }
30475 
30476   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
30477   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
30478   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
30479 
30480   if (Opc == ISD::CTLZ) {
30481     // If src is zero (i.e. bsr sets ZF), returns NumBits.
30482     SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
30483                      DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
30484                      Op.getValue(1)};
30485     Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
30486   }
30487 
30488   // Finally xor with NumBits-1.
30489   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
30490                    DAG.getConstant(NumBits - 1, dl, OpVT));
30491 
30492   if (VT == MVT::i8)
30493     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
30494   return Op;
30495 }
30496 
30497 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
30498                          SelectionDAG &DAG) {
30499   MVT VT = Op.getSimpleValueType();
30500   unsigned NumBits = VT.getScalarSizeInBits();
30501   SDValue N0 = Op.getOperand(0);
30502   SDLoc dl(Op);
30503 
30504   assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
30505          "Only scalar CTTZ requires custom lowering");
30506 
30507   // Issue a bsf (scan bits forward) which also sets EFLAGS.
30508   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
30509   Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
30510 
30511   // If src is known never zero we can skip the CMOV.
30512   if (DAG.isKnownNeverZero(N0))
30513     return Op;
30514 
30515   // If src is zero (i.e. bsf sets ZF), returns NumBits.
30516   SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
30517                    DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
30518                    Op.getValue(1)};
30519   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
30520 }
30521 
30522 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
30523                            const X86Subtarget &Subtarget) {
30524   MVT VT = Op.getSimpleValueType();
30525   if (VT == MVT::i16 || VT == MVT::i32)
30526     return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
30527 
30528   if (VT == MVT::v32i16 || VT == MVT::v64i8)
30529     return splitVectorIntBinary(Op, DAG);
30530 
30531   assert(Op.getSimpleValueType().is256BitVector() &&
30532          Op.getSimpleValueType().isInteger() &&
30533          "Only handle AVX 256-bit vector integer operation");
30534   return splitVectorIntBinary(Op, DAG);
30535 }
30536 
30537 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
30538                                   const X86Subtarget &Subtarget) {
30539   MVT VT = Op.getSimpleValueType();
30540   SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
30541   unsigned Opcode = Op.getOpcode();
30542   SDLoc DL(Op);
30543 
30544   if (VT == MVT::v32i16 || VT == MVT::v64i8 ||
30545       (VT.is256BitVector() && !Subtarget.hasInt256())) {
30546     assert(Op.getSimpleValueType().isInteger() &&
30547            "Only handle AVX vector integer operation");
30548     return splitVectorIntBinary(Op, DAG);
30549   }
30550 
30551   // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
30552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
30553   EVT SetCCResultType =
30554       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
30555 
30556   unsigned BitWidth = VT.getScalarSizeInBits();
30557   if (Opcode == ISD::USUBSAT) {
30558     if (!TLI.isOperationLegal(ISD::UMAX, VT) || useVPTERNLOG(Subtarget, VT)) {
30559       // Handle a special-case with a bit-hack instead of cmp+select:
30560       // usubsat X, SMIN --> (X ^ SMIN) & (X s>> BW-1)
30561       // If the target can use VPTERNLOG, DAGToDAG will match this as
30562       // "vpsra + vpternlog" which is better than "vpmax + vpsub" with a
30563       // "broadcast" constant load.
30564       ConstantSDNode *C = isConstOrConstSplat(Y, true);
30565       if (C && C->getAPIntValue().isSignMask()) {
30566         SDValue SignMask = DAG.getConstant(C->getAPIntValue(), DL, VT);
30567         SDValue ShiftAmt = DAG.getConstant(BitWidth - 1, DL, VT);
30568         SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, SignMask);
30569         SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShiftAmt);
30570         return DAG.getNode(ISD::AND, DL, VT, Xor, Sra);
30571       }
30572     }
30573     if (!TLI.isOperationLegal(ISD::UMAX, VT)) {
30574       // usubsat X, Y --> (X >u Y) ? X - Y : 0
30575       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
30576       SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
30577       // TODO: Move this to DAGCombiner?
30578       if (SetCCResultType == VT &&
30579           DAG.ComputeNumSignBits(Cmp) == VT.getScalarSizeInBits())
30580         return DAG.getNode(ISD::AND, DL, VT, Cmp, Sub);
30581       return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
30582     }
30583   }
30584 
30585   if ((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
30586       (!VT.isVector() || VT == MVT::v2i64)) {
30587     APInt MinVal = APInt::getSignedMinValue(BitWidth);
30588     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
30589     SDValue Zero = DAG.getConstant(0, DL, VT);
30590     SDValue Result =
30591         DAG.getNode(Opcode == ISD::SADDSAT ? ISD::SADDO : ISD::SSUBO, DL,
30592                     DAG.getVTList(VT, SetCCResultType), X, Y);
30593     SDValue SumDiff = Result.getValue(0);
30594     SDValue Overflow = Result.getValue(1);
30595     SDValue SatMin = DAG.getConstant(MinVal, DL, VT);
30596     SDValue SatMax = DAG.getConstant(MaxVal, DL, VT);
30597     SDValue SumNeg =
30598         DAG.getSetCC(DL, SetCCResultType, SumDiff, Zero, ISD::SETLT);
30599     Result = DAG.getSelect(DL, VT, SumNeg, SatMax, SatMin);
30600     return DAG.getSelect(DL, VT, Overflow, Result, SumDiff);
30601   }
30602 
30603   // Use default expansion.
30604   return SDValue();
30605 }
30606 
30607 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
30608                         SelectionDAG &DAG) {
30609   MVT VT = Op.getSimpleValueType();
30610   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
30611     // Since X86 does not have CMOV for 8-bit integer, we don't convert
30612     // 8-bit integer abs to NEG and CMOV.
30613     SDLoc DL(Op);
30614     SDValue N0 = Op.getOperand(0);
30615     SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
30616                               DAG.getConstant(0, DL, VT), N0);
30617     SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_NS, DL, MVT::i8),
30618                      SDValue(Neg.getNode(), 1)};
30619     return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
30620   }
30621 
30622   // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
30623   if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
30624     SDLoc DL(Op);
30625     SDValue Src = Op.getOperand(0);
30626     SDValue Sub =
30627         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
30628     return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
30629   }
30630 
30631   if (VT.is256BitVector() && !Subtarget.hasInt256()) {
30632     assert(VT.isInteger() &&
30633            "Only handle AVX 256-bit vector integer operation");
30634     return splitVectorIntUnary(Op, DAG);
30635   }
30636 
30637   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
30638     return splitVectorIntUnary(Op, DAG);
30639 
30640   // Default to expand.
30641   return SDValue();
30642 }
30643 
30644 static SDValue LowerAVG(SDValue Op, const X86Subtarget &Subtarget,
30645                         SelectionDAG &DAG) {
30646   MVT VT = Op.getSimpleValueType();
30647 
30648   // For AVX1 cases, split to use legal ops.
30649   if (VT.is256BitVector() && !Subtarget.hasInt256())
30650     return splitVectorIntBinary(Op, DAG);
30651 
30652   if (VT == MVT::v32i16 || VT == MVT::v64i8)
30653     return splitVectorIntBinary(Op, DAG);
30654 
30655   // Default to expand.
30656   return SDValue();
30657 }
30658 
30659 static SDValue LowerMINMAX(SDValue Op, const X86Subtarget &Subtarget,
30660                            SelectionDAG &DAG) {
30661   MVT VT = Op.getSimpleValueType();
30662 
30663   // For AVX1 cases, split to use legal ops.
30664   if (VT.is256BitVector() && !Subtarget.hasInt256())
30665     return splitVectorIntBinary(Op, DAG);
30666 
30667   if (VT == MVT::v32i16 || VT == MVT::v64i8)
30668     return splitVectorIntBinary(Op, DAG);
30669 
30670   // Default to expand.
30671   return SDValue();
30672 }
30673 
30674 static SDValue LowerFMINIMUM_FMAXIMUM(SDValue Op, const X86Subtarget &Subtarget,
30675                                       SelectionDAG &DAG) {
30676   assert((Op.getOpcode() == ISD::FMAXIMUM || Op.getOpcode() == ISD::FMINIMUM) &&
30677          "Expected FMAXIMUM or FMINIMUM opcode");
30678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
30679   EVT VT = Op.getValueType();
30680   SDValue X = Op.getOperand(0);
30681   SDValue Y = Op.getOperand(1);
30682   SDLoc DL(Op);
30683   uint64_t SizeInBits = VT.getScalarSizeInBits();
30684   APInt PreferredZero = APInt::getZero(SizeInBits);
30685   APInt OppositeZero = PreferredZero;
30686   EVT IVT = VT.changeTypeToInteger();
30687   X86ISD::NodeType MinMaxOp;
30688   if (Op.getOpcode() == ISD::FMAXIMUM) {
30689     MinMaxOp = X86ISD::FMAX;
30690     OppositeZero.setSignBit();
30691   } else {
30692     PreferredZero.setSignBit();
30693     MinMaxOp = X86ISD::FMIN;
30694   }
30695   EVT SetCCType =
30696       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
30697 
30698   // The tables below show the expected result of Max in cases of NaN and
30699   // signed zeros.
30700   //
30701   //                 Y                       Y
30702   //             Num   xNaN              +0     -0
30703   //          ---------------         ---------------
30704   //     Num  |  Max |   Y  |     +0  |  +0  |  +0  |
30705   // X        ---------------  X      ---------------
30706   //    xNaN  |   X  |  X/Y |     -0  |  +0  |  -0  |
30707   //          ---------------         ---------------
30708   //
30709   // It is achieved by means of FMAX/FMIN with preliminary checks and operand
30710   // reordering.
30711   //
30712   // We check if any of operands is NaN and return NaN. Then we check if any of
30713   // operands is zero or negative zero (for fmaximum and fminimum respectively)
30714   // to ensure the correct zero is returned.
30715   auto MatchesZero = [](SDValue Op, APInt Zero) {
30716     Op = peekThroughBitcasts(Op);
30717     if (auto *CstOp = dyn_cast<ConstantFPSDNode>(Op))
30718       return CstOp->getValueAPF().bitcastToAPInt() == Zero;
30719     if (auto *CstOp = dyn_cast<ConstantSDNode>(Op))
30720       return CstOp->getAPIntValue() == Zero;
30721     if (Op->getOpcode() == ISD::BUILD_VECTOR ||
30722         Op->getOpcode() == ISD::SPLAT_VECTOR) {
30723       for (const SDValue &OpVal : Op->op_values()) {
30724         if (OpVal.isUndef())
30725           continue;
30726         auto *CstOp = dyn_cast<ConstantFPSDNode>(OpVal);
30727         if (!CstOp)
30728           return false;
30729         if (!CstOp->getValueAPF().isZero())
30730           continue;
30731         if (CstOp->getValueAPF().bitcastToAPInt() != Zero)
30732           return false;
30733       }
30734       return true;
30735     }
30736     return false;
30737   };
30738 
30739   bool IsXNeverNaN = DAG.isKnownNeverNaN(X);
30740   bool IsYNeverNaN = DAG.isKnownNeverNaN(Y);
30741   bool IgnoreSignedZero = DAG.getTarget().Options.NoSignedZerosFPMath ||
30742                           Op->getFlags().hasNoSignedZeros() ||
30743                           DAG.isKnownNeverZeroFloat(X) ||
30744                           DAG.isKnownNeverZeroFloat(Y);
30745   SDValue NewX, NewY;
30746   if (IgnoreSignedZero || MatchesZero(Y, PreferredZero) ||
30747       MatchesZero(X, OppositeZero)) {
30748     // Operands are already in right order or order does not matter.
30749     NewX = X;
30750     NewY = Y;
30751   } else if (MatchesZero(X, PreferredZero) || MatchesZero(Y, OppositeZero)) {
30752     NewX = Y;
30753     NewY = X;
30754   } else if (!VT.isVector() && (VT == MVT::f16 || Subtarget.hasDQI()) &&
30755              (Op->getFlags().hasNoNaNs() || IsXNeverNaN || IsYNeverNaN)) {
30756     if (IsXNeverNaN)
30757       std::swap(X, Y);
30758     // VFPCLASSS consumes a vector type. So provide a minimal one corresponded
30759     // xmm register.
30760     MVT VectorType = MVT::getVectorVT(VT.getSimpleVT(), 128 / SizeInBits);
30761     SDValue VX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorType, X);
30762     // Bits of classes:
30763     // Bits  Imm8[0] Imm8[1] Imm8[2] Imm8[3] Imm8[4]  Imm8[5]  Imm8[6] Imm8[7]
30764     // Class    QNAN PosZero NegZero  PosINF  NegINF Denormal Negative    SNAN
30765     SDValue Imm = DAG.getTargetConstant(MinMaxOp == X86ISD::FMAX ? 0b11 : 0b101,
30766                                         DL, MVT::i32);
30767     SDValue IsNanZero = DAG.getNode(X86ISD::VFPCLASSS, DL, MVT::v1i1, VX, Imm);
30768     SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
30769                               DAG.getConstant(0, DL, MVT::v8i1), IsNanZero,
30770                               DAG.getIntPtrConstant(0, DL));
30771     SDValue NeedSwap = DAG.getBitcast(MVT::i8, Ins);
30772     NewX = DAG.getSelect(DL, VT, NeedSwap, Y, X);
30773     NewY = DAG.getSelect(DL, VT, NeedSwap, X, Y);
30774     return DAG.getNode(MinMaxOp, DL, VT, NewX, NewY, Op->getFlags());
30775   } else {
30776     SDValue IsXSigned;
30777     if (Subtarget.is64Bit() || VT != MVT::f64) {
30778       SDValue XInt = DAG.getNode(ISD::BITCAST, DL, IVT, X);
30779       SDValue ZeroCst = DAG.getConstant(0, DL, IVT);
30780       IsXSigned = DAG.getSetCC(DL, SetCCType, XInt, ZeroCst, ISD::SETLT);
30781     } else {
30782       assert(VT == MVT::f64);
30783       SDValue Ins = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v2f64,
30784                                 DAG.getConstantFP(0, DL, MVT::v2f64), X,
30785                                 DAG.getIntPtrConstant(0, DL));
30786       SDValue VX = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, Ins);
30787       SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VX,
30788                                DAG.getIntPtrConstant(1, DL));
30789       Hi = DAG.getBitcast(MVT::i32, Hi);
30790       SDValue ZeroCst = DAG.getConstant(0, DL, MVT::i32);
30791       EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(),
30792                                              *DAG.getContext(), MVT::i32);
30793       IsXSigned = DAG.getSetCC(DL, SetCCType, Hi, ZeroCst, ISD::SETLT);
30794     }
30795     if (MinMaxOp == X86ISD::FMAX) {
30796       NewX = DAG.getSelect(DL, VT, IsXSigned, X, Y);
30797       NewY = DAG.getSelect(DL, VT, IsXSigned, Y, X);
30798     } else {
30799       NewX = DAG.getSelect(DL, VT, IsXSigned, Y, X);
30800       NewY = DAG.getSelect(DL, VT, IsXSigned, X, Y);
30801     }
30802   }
30803 
30804   bool IgnoreNaN = DAG.getTarget().Options.NoNaNsFPMath ||
30805                    Op->getFlags().hasNoNaNs() || (IsXNeverNaN && IsYNeverNaN);
30806 
30807   // If we did no ordering operands for signed zero handling and we need
30808   // to process NaN and we know that the second operand is not NaN then put
30809   // it in first operand and we will not need to post handle NaN after max/min.
30810   if (IgnoreSignedZero && !IgnoreNaN && DAG.isKnownNeverNaN(NewY))
30811     std::swap(NewX, NewY);
30812 
30813   SDValue MinMax = DAG.getNode(MinMaxOp, DL, VT, NewX, NewY, Op->getFlags());
30814 
30815   if (IgnoreNaN || DAG.isKnownNeverNaN(NewX))
30816     return MinMax;
30817 
30818   SDValue IsNaN = DAG.getSetCC(DL, SetCCType, NewX, NewX, ISD::SETUO);
30819   return DAG.getSelect(DL, VT, IsNaN, NewX, MinMax);
30820 }
30821 
30822 static SDValue LowerABD(SDValue Op, const X86Subtarget &Subtarget,
30823                         SelectionDAG &DAG) {
30824   MVT VT = Op.getSimpleValueType();
30825 
30826   // For AVX1 cases, split to use legal ops.
30827   if (VT.is256BitVector() && !Subtarget.hasInt256())
30828     return splitVectorIntBinary(Op, DAG);
30829 
30830   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.useBWIRegs())
30831     return splitVectorIntBinary(Op, DAG);
30832 
30833   SDLoc dl(Op);
30834   bool IsSigned = Op.getOpcode() == ISD::ABDS;
30835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
30836 
30837   // TODO: Move to TargetLowering expandABD() once we have ABD promotion.
30838   if (VT.isScalarInteger()) {
30839     unsigned WideBits = std::max<unsigned>(2 * VT.getScalarSizeInBits(), 32u);
30840     MVT WideVT = MVT::getIntegerVT(WideBits);
30841     if (TLI.isTypeLegal(WideVT)) {
30842       // abds(lhs, rhs) -> trunc(abs(sub(sext(lhs), sext(rhs))))
30843       // abdu(lhs, rhs) -> trunc(abs(sub(zext(lhs), zext(rhs))))
30844       unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
30845       SDValue LHS = DAG.getFreeze(Op.getOperand(0));
30846       SDValue RHS = DAG.getFreeze(Op.getOperand(1));
30847       LHS = DAG.getNode(ExtOpc, dl, WideVT, LHS);
30848       RHS = DAG.getNode(ExtOpc, dl, WideVT, RHS);
30849       SDValue Diff = DAG.getNode(ISD::SUB, dl, WideVT, LHS, RHS);
30850       SDValue AbsDiff = DAG.getNode(ISD::ABS, dl, WideVT, Diff);
30851       return DAG.getNode(ISD::TRUNCATE, dl, VT, AbsDiff);
30852     }
30853   }
30854 
30855   // TODO: Move to TargetLowering expandABD().
30856   if (!Subtarget.hasSSE41() &&
30857       ((IsSigned && VT == MVT::v16i8) || VT == MVT::v4i32)) {
30858     SDValue LHS = DAG.getFreeze(Op.getOperand(0));
30859     SDValue RHS = DAG.getFreeze(Op.getOperand(1));
30860     ISD::CondCode CC = IsSigned ? ISD::CondCode::SETGT : ISD::CondCode::SETUGT;
30861     SDValue Cmp = DAG.getSetCC(dl, VT, LHS, RHS, CC);
30862     SDValue Diff0 = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
30863     SDValue Diff1 = DAG.getNode(ISD::SUB, dl, VT, RHS, LHS);
30864     return getBitSelect(dl, VT, Diff0, Diff1, Cmp, DAG);
30865   }
30866 
30867   // Default to expand.
30868   return SDValue();
30869 }
30870 
30871 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
30872                         SelectionDAG &DAG) {
30873   SDLoc dl(Op);
30874   MVT VT = Op.getSimpleValueType();
30875 
30876   // Decompose 256-bit ops into 128-bit ops.
30877   if (VT.is256BitVector() && !Subtarget.hasInt256())
30878     return splitVectorIntBinary(Op, DAG);
30879 
30880   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
30881     return splitVectorIntBinary(Op, DAG);
30882 
30883   SDValue A = Op.getOperand(0);
30884   SDValue B = Op.getOperand(1);
30885 
30886   // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
30887   // vector pairs, multiply and truncate.
30888   if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
30889     unsigned NumElts = VT.getVectorNumElements();
30890 
30891     if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
30892         (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
30893       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
30894       return DAG.getNode(
30895           ISD::TRUNCATE, dl, VT,
30896           DAG.getNode(ISD::MUL, dl, ExVT,
30897                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
30898                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
30899     }
30900 
30901     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
30902 
30903     // Extract the lo/hi parts to any extend to i16.
30904     // We're going to mask off the low byte of each result element of the
30905     // pmullw, so it doesn't matter what's in the high byte of each 16-bit
30906     // element.
30907     SDValue Undef = DAG.getUNDEF(VT);
30908     SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
30909     SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
30910 
30911     SDValue BLo, BHi;
30912     if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
30913       // If the RHS is a constant, manually unpackl/unpackh.
30914       SmallVector<SDValue, 16> LoOps, HiOps;
30915       for (unsigned i = 0; i != NumElts; i += 16) {
30916         for (unsigned j = 0; j != 8; ++j) {
30917           LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
30918                                                MVT::i16));
30919           HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
30920                                                MVT::i16));
30921         }
30922       }
30923 
30924       BLo = DAG.getBuildVector(ExVT, dl, LoOps);
30925       BHi = DAG.getBuildVector(ExVT, dl, HiOps);
30926     } else {
30927       BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
30928       BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
30929     }
30930 
30931     // Multiply, mask the lower 8bits of the lo/hi results and pack.
30932     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
30933     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
30934     return getPack(DAG, Subtarget, dl, VT, RLo, RHi);
30935   }
30936 
30937   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
30938   if (VT == MVT::v4i32) {
30939     assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
30940            "Should not custom lower when pmulld is available!");
30941 
30942     // Extract the odd parts.
30943     static const int UnpackMask[] = { 1, -1, 3, -1 };
30944     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
30945     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
30946 
30947     // Multiply the even parts.
30948     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
30949                                 DAG.getBitcast(MVT::v2i64, A),
30950                                 DAG.getBitcast(MVT::v2i64, B));
30951     // Now multiply odd parts.
30952     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
30953                                DAG.getBitcast(MVT::v2i64, Aodds),
30954                                DAG.getBitcast(MVT::v2i64, Bodds));
30955 
30956     Evens = DAG.getBitcast(VT, Evens);
30957     Odds = DAG.getBitcast(VT, Odds);
30958 
30959     // Merge the two vectors back together with a shuffle. This expands into 2
30960     // shuffles.
30961     static const int ShufMask[] = { 0, 4, 2, 6 };
30962     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
30963   }
30964 
30965   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
30966          "Only know how to lower V2I64/V4I64/V8I64 multiply");
30967   assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
30968 
30969   //  Ahi = psrlqi(a, 32);
30970   //  Bhi = psrlqi(b, 32);
30971   //
30972   //  AloBlo = pmuludq(a, b);
30973   //  AloBhi = pmuludq(a, Bhi);
30974   //  AhiBlo = pmuludq(Ahi, b);
30975   //
30976   //  Hi = psllqi(AloBhi + AhiBlo, 32);
30977   //  return AloBlo + Hi;
30978   KnownBits AKnown = DAG.computeKnownBits(A);
30979   KnownBits BKnown = DAG.computeKnownBits(B);
30980 
30981   APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
30982   bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
30983   bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
30984 
30985   APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
30986   bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
30987   bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
30988 
30989   SDValue Zero = DAG.getConstant(0, dl, VT);
30990 
30991   // Only multiply lo/hi halves that aren't known to be zero.
30992   SDValue AloBlo = Zero;
30993   if (!ALoIsZero && !BLoIsZero)
30994     AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
30995 
30996   SDValue AloBhi = Zero;
30997   if (!ALoIsZero && !BHiIsZero) {
30998     SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
30999     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
31000   }
31001 
31002   SDValue AhiBlo = Zero;
31003   if (!AHiIsZero && !BLoIsZero) {
31004     SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
31005     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
31006   }
31007 
31008   SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
31009   Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
31010 
31011   return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
31012 }
31013 
31014 static SDValue LowervXi8MulWithUNPCK(SDValue A, SDValue B, const SDLoc &dl,
31015                                      MVT VT, bool IsSigned,
31016                                      const X86Subtarget &Subtarget,
31017                                      SelectionDAG &DAG,
31018                                      SDValue *Low = nullptr) {
31019   unsigned NumElts = VT.getVectorNumElements();
31020 
31021   // For vXi8 we will unpack the low and high half of each 128 bit lane to widen
31022   // to a vXi16 type. Do the multiplies, shift the results and pack the half
31023   // lane results back together.
31024 
31025   // We'll take different approaches for signed and unsigned.
31026   // For unsigned we'll use punpcklbw/punpckhbw to put zero extend the bytes
31027   // and use pmullw to calculate the full 16-bit product.
31028   // For signed we'll use punpcklbw/punpckbw to extend the bytes to words and
31029   // shift them left into the upper byte of each word. This allows us to use
31030   // pmulhw to calculate the full 16-bit product. This trick means we don't
31031   // need to sign extend the bytes to use pmullw.
31032 
31033   MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
31034   SDValue Zero = DAG.getConstant(0, dl, VT);
31035 
31036   SDValue ALo, AHi;
31037   if (IsSigned) {
31038     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, A));
31039     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, A));
31040   } else {
31041     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Zero));
31042     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Zero));
31043   }
31044 
31045   SDValue BLo, BHi;
31046   if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
31047     // If the RHS is a constant, manually unpackl/unpackh and extend.
31048     SmallVector<SDValue, 16> LoOps, HiOps;
31049     for (unsigned i = 0; i != NumElts; i += 16) {
31050       for (unsigned j = 0; j != 8; ++j) {
31051         SDValue LoOp = B.getOperand(i + j);
31052         SDValue HiOp = B.getOperand(i + j + 8);
31053 
31054         if (IsSigned) {
31055           LoOp = DAG.getAnyExtOrTrunc(LoOp, dl, MVT::i16);
31056           HiOp = DAG.getAnyExtOrTrunc(HiOp, dl, MVT::i16);
31057           LoOp = DAG.getNode(ISD::SHL, dl, MVT::i16, LoOp,
31058                              DAG.getConstant(8, dl, MVT::i16));
31059           HiOp = DAG.getNode(ISD::SHL, dl, MVT::i16, HiOp,
31060                              DAG.getConstant(8, dl, MVT::i16));
31061         } else {
31062           LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
31063           HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
31064         }
31065 
31066         LoOps.push_back(LoOp);
31067         HiOps.push_back(HiOp);
31068       }
31069     }
31070 
31071     BLo = DAG.getBuildVector(ExVT, dl, LoOps);
31072     BHi = DAG.getBuildVector(ExVT, dl, HiOps);
31073   } else if (IsSigned) {
31074     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, B));
31075     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, B));
31076   } else {
31077     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Zero));
31078     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Zero));
31079   }
31080 
31081   // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
31082   // pack back to vXi8.
31083   unsigned MulOpc = IsSigned ? ISD::MULHS : ISD::MUL;
31084   SDValue RLo = DAG.getNode(MulOpc, dl, ExVT, ALo, BLo);
31085   SDValue RHi = DAG.getNode(MulOpc, dl, ExVT, AHi, BHi);
31086 
31087   if (Low)
31088     *Low = getPack(DAG, Subtarget, dl, VT, RLo, RHi);
31089 
31090   return getPack(DAG, Subtarget, dl, VT, RLo, RHi, /*PackHiHalf*/ true);
31091 }
31092 
31093 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
31094                          SelectionDAG &DAG) {
31095   SDLoc dl(Op);
31096   MVT VT = Op.getSimpleValueType();
31097   bool IsSigned = Op->getOpcode() == ISD::MULHS;
31098   unsigned NumElts = VT.getVectorNumElements();
31099   SDValue A = Op.getOperand(0);
31100   SDValue B = Op.getOperand(1);
31101 
31102   // Decompose 256-bit ops into 128-bit ops.
31103   if (VT.is256BitVector() && !Subtarget.hasInt256())
31104     return splitVectorIntBinary(Op, DAG);
31105 
31106   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
31107     return splitVectorIntBinary(Op, DAG);
31108 
31109   if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
31110     assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
31111            (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
31112            (VT == MVT::v16i32 && Subtarget.hasAVX512()));
31113 
31114     // PMULxD operations multiply each even value (starting at 0) of LHS with
31115     // the related value of RHS and produce a widen result.
31116     // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
31117     // => <2 x i64> <ae|cg>
31118     //
31119     // In other word, to have all the results, we need to perform two PMULxD:
31120     // 1. one with the even values.
31121     // 2. one with the odd values.
31122     // To achieve #2, with need to place the odd values at an even position.
31123     //
31124     // Place the odd value at an even position (basically, shift all values 1
31125     // step to the left):
31126     const int Mask[] = {1, -1,  3, -1,  5, -1,  7, -1,
31127                         9, -1, 11, -1, 13, -1, 15, -1};
31128     // <a|b|c|d> => <b|undef|d|undef>
31129     SDValue Odd0 =
31130         DAG.getVectorShuffle(VT, dl, A, A, ArrayRef(&Mask[0], NumElts));
31131     // <e|f|g|h> => <f|undef|h|undef>
31132     SDValue Odd1 =
31133         DAG.getVectorShuffle(VT, dl, B, B, ArrayRef(&Mask[0], NumElts));
31134 
31135     // Emit two multiplies, one for the lower 2 ints and one for the higher 2
31136     // ints.
31137     MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
31138     unsigned Opcode =
31139         (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
31140     // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
31141     // => <2 x i64> <ae|cg>
31142     SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
31143                                                   DAG.getBitcast(MulVT, A),
31144                                                   DAG.getBitcast(MulVT, B)));
31145     // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
31146     // => <2 x i64> <bf|dh>
31147     SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
31148                                                   DAG.getBitcast(MulVT, Odd0),
31149                                                   DAG.getBitcast(MulVT, Odd1)));
31150 
31151     // Shuffle it back into the right order.
31152     SmallVector<int, 16> ShufMask(NumElts);
31153     for (int i = 0; i != (int)NumElts; ++i)
31154       ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
31155 
31156     SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
31157 
31158     // If we have a signed multiply but no PMULDQ fix up the result of an
31159     // unsigned multiply.
31160     if (IsSigned && !Subtarget.hasSSE41()) {
31161       SDValue Zero = DAG.getConstant(0, dl, VT);
31162       SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
31163                                DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
31164       SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
31165                                DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
31166 
31167       SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
31168       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
31169     }
31170 
31171     return Res;
31172   }
31173 
31174   // Only i8 vectors should need custom lowering after this.
31175   assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
31176          (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
31177          "Unsupported vector type");
31178 
31179   // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
31180   // logical shift down the upper half and pack back to i8.
31181 
31182   // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
31183   // and then ashr/lshr the upper bits down to the lower bits before multiply.
31184 
31185   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
31186       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
31187     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
31188     unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
31189     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
31190     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
31191     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
31192     Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
31193     return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
31194   }
31195 
31196   return LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG);
31197 }
31198 
31199 // Custom lowering for SMULO/UMULO.
31200 static SDValue LowerMULO(SDValue Op, const X86Subtarget &Subtarget,
31201                          SelectionDAG &DAG) {
31202   MVT VT = Op.getSimpleValueType();
31203 
31204   // Scalars defer to LowerXALUO.
31205   if (!VT.isVector())
31206     return LowerXALUO(Op, DAG);
31207 
31208   SDLoc dl(Op);
31209   bool IsSigned = Op->getOpcode() == ISD::SMULO;
31210   SDValue A = Op.getOperand(0);
31211   SDValue B = Op.getOperand(1);
31212   EVT OvfVT = Op->getValueType(1);
31213 
31214   if ((VT == MVT::v32i8 && !Subtarget.hasInt256()) ||
31215       (VT == MVT::v64i8 && !Subtarget.hasBWI())) {
31216     // Extract the LHS Lo/Hi vectors
31217     SDValue LHSLo, LHSHi;
31218     std::tie(LHSLo, LHSHi) = splitVector(A, DAG, dl);
31219 
31220     // Extract the RHS Lo/Hi vectors
31221     SDValue RHSLo, RHSHi;
31222     std::tie(RHSLo, RHSHi) = splitVector(B, DAG, dl);
31223 
31224     EVT LoOvfVT, HiOvfVT;
31225     std::tie(LoOvfVT, HiOvfVT) = DAG.GetSplitDestVTs(OvfVT);
31226     SDVTList LoVTs = DAG.getVTList(LHSLo.getValueType(), LoOvfVT);
31227     SDVTList HiVTs = DAG.getVTList(LHSHi.getValueType(), HiOvfVT);
31228 
31229     // Issue the split operations.
31230     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, LoVTs, LHSLo, RHSLo);
31231     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, HiVTs, LHSHi, RHSHi);
31232 
31233     // Join the separate data results and the overflow results.
31234     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
31235     SDValue Ovf = DAG.getNode(ISD::CONCAT_VECTORS, dl, OvfVT, Lo.getValue(1),
31236                               Hi.getValue(1));
31237 
31238     return DAG.getMergeValues({Res, Ovf}, dl);
31239   }
31240 
31241   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
31242   EVT SetccVT =
31243       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
31244 
31245   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
31246       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
31247     unsigned NumElts = VT.getVectorNumElements();
31248     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
31249     unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
31250     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
31251     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
31252     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
31253 
31254     SDValue Low = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
31255 
31256     SDValue Ovf;
31257     if (IsSigned) {
31258       SDValue High, LowSign;
31259       if (OvfVT.getVectorElementType() == MVT::i1 &&
31260           (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
31261         // Rather the truncating try to do the compare on vXi16 or vXi32.
31262         // Shift the high down filling with sign bits.
31263         High = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Mul, 8, DAG);
31264         // Fill all 16 bits with the sign bit from the low.
31265         LowSign =
31266             getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExVT, Mul, 8, DAG);
31267         LowSign = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, LowSign,
31268                                              15, DAG);
31269         SetccVT = OvfVT;
31270         if (!Subtarget.hasBWI()) {
31271           // We can't do a vXi16 compare so sign extend to v16i32.
31272           High = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, High);
31273           LowSign = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, LowSign);
31274         }
31275       } else {
31276         // Otherwise do the compare at vXi8.
31277         High = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
31278         High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
31279         LowSign =
31280             DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
31281       }
31282 
31283       Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
31284     } else {
31285       SDValue High =
31286           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
31287       if (OvfVT.getVectorElementType() == MVT::i1 &&
31288           (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
31289         // Rather the truncating try to do the compare on vXi16 or vXi32.
31290         SetccVT = OvfVT;
31291         if (!Subtarget.hasBWI()) {
31292           // We can't do a vXi16 compare so sign extend to v16i32.
31293           High = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, High);
31294         }
31295       } else {
31296         // Otherwise do the compare at vXi8.
31297         High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
31298       }
31299 
31300       Ovf =
31301           DAG.getSetCC(dl, SetccVT, High,
31302                        DAG.getConstant(0, dl, High.getValueType()), ISD::SETNE);
31303     }
31304 
31305     Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
31306 
31307     return DAG.getMergeValues({Low, Ovf}, dl);
31308   }
31309 
31310   SDValue Low;
31311   SDValue High =
31312       LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG, &Low);
31313 
31314   SDValue Ovf;
31315   if (IsSigned) {
31316     // SMULO overflows if the high bits don't match the sign of the low.
31317     SDValue LowSign =
31318         DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
31319     Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
31320   } else {
31321     // UMULO overflows if the high bits are non-zero.
31322     Ovf =
31323         DAG.getSetCC(dl, SetccVT, High, DAG.getConstant(0, dl, VT), ISD::SETNE);
31324   }
31325 
31326   Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
31327 
31328   return DAG.getMergeValues({Low, Ovf}, dl);
31329 }
31330 
31331 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
31332   assert(Subtarget.isTargetWin64() && "Unexpected target");
31333   EVT VT = Op.getValueType();
31334   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
31335          "Unexpected return type for lowering");
31336 
31337   if (isa<ConstantSDNode>(Op->getOperand(1))) {
31338     SmallVector<SDValue> Result;
31339     if (expandDIVREMByConstant(Op.getNode(), Result, MVT::i64, DAG))
31340       return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), VT, Result[0], Result[1]);
31341   }
31342 
31343   RTLIB::Libcall LC;
31344   bool isSigned;
31345   switch (Op->getOpcode()) {
31346   default: llvm_unreachable("Unexpected request for libcall!");
31347   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
31348   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
31349   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
31350   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
31351   }
31352 
31353   SDLoc dl(Op);
31354   SDValue InChain = DAG.getEntryNode();
31355 
31356   TargetLowering::ArgListTy Args;
31357   TargetLowering::ArgListEntry Entry;
31358   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
31359     EVT ArgVT = Op->getOperand(i).getValueType();
31360     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
31361            "Unexpected argument type for lowering");
31362     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
31363     int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
31364     MachinePointerInfo MPI =
31365         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
31366     Entry.Node = StackPtr;
31367     InChain =
31368         DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MPI, Align(16));
31369     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
31370     Entry.Ty = PointerType::get(ArgTy,0);
31371     Entry.IsSExt = false;
31372     Entry.IsZExt = false;
31373     Args.push_back(Entry);
31374   }
31375 
31376   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
31377                                          getPointerTy(DAG.getDataLayout()));
31378 
31379   TargetLowering::CallLoweringInfo CLI(DAG);
31380   CLI.setDebugLoc(dl)
31381       .setChain(InChain)
31382       .setLibCallee(
31383           getLibcallCallingConv(LC),
31384           static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
31385           std::move(Args))
31386       .setInRegister()
31387       .setSExtResult(isSigned)
31388       .setZExtResult(!isSigned);
31389 
31390   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
31391   return DAG.getBitcast(VT, CallInfo.first);
31392 }
31393 
31394 SDValue X86TargetLowering::LowerWin64_FP_TO_INT128(SDValue Op,
31395                                                    SelectionDAG &DAG,
31396                                                    SDValue &Chain) const {
31397   assert(Subtarget.isTargetWin64() && "Unexpected target");
31398   EVT VT = Op.getValueType();
31399   bool IsStrict = Op->isStrictFPOpcode();
31400 
31401   SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
31402   EVT ArgVT = Arg.getValueType();
31403 
31404   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
31405          "Unexpected return type for lowering");
31406 
31407   RTLIB::Libcall LC;
31408   if (Op->getOpcode() == ISD::FP_TO_SINT ||
31409       Op->getOpcode() == ISD::STRICT_FP_TO_SINT)
31410     LC = RTLIB::getFPTOSINT(ArgVT, VT);
31411   else
31412     LC = RTLIB::getFPTOUINT(ArgVT, VT);
31413   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
31414 
31415   SDLoc dl(Op);
31416   MakeLibCallOptions CallOptions;
31417   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
31418 
31419   SDValue Result;
31420   // Expect the i128 argument returned as a v2i64 in xmm0, cast back to the
31421   // expected VT (i128).
31422   std::tie(Result, Chain) =
31423       makeLibCall(DAG, LC, MVT::v2i64, Arg, CallOptions, dl, Chain);
31424   Result = DAG.getBitcast(VT, Result);
31425   return Result;
31426 }
31427 
31428 SDValue X86TargetLowering::LowerWin64_INT128_TO_FP(SDValue Op,
31429                                                    SelectionDAG &DAG) const {
31430   assert(Subtarget.isTargetWin64() && "Unexpected target");
31431   EVT VT = Op.getValueType();
31432   bool IsStrict = Op->isStrictFPOpcode();
31433 
31434   SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
31435   EVT ArgVT = Arg.getValueType();
31436 
31437   assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
31438          "Unexpected argument type for lowering");
31439 
31440   RTLIB::Libcall LC;
31441   if (Op->getOpcode() == ISD::SINT_TO_FP ||
31442       Op->getOpcode() == ISD::STRICT_SINT_TO_FP)
31443     LC = RTLIB::getSINTTOFP(ArgVT, VT);
31444   else
31445     LC = RTLIB::getUINTTOFP(ArgVT, VT);
31446   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
31447 
31448   SDLoc dl(Op);
31449   MakeLibCallOptions CallOptions;
31450   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
31451 
31452   // Pass the i128 argument as an indirect argument on the stack.
31453   SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
31454   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
31455   MachinePointerInfo MPI =
31456       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
31457   Chain = DAG.getStore(Chain, dl, Arg, StackPtr, MPI, Align(16));
31458 
31459   SDValue Result;
31460   std::tie(Result, Chain) =
31461       makeLibCall(DAG, LC, VT, StackPtr, CallOptions, dl, Chain);
31462   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
31463 }
31464 
31465 // Return true if the required (according to Opcode) shift-imm form is natively
31466 // supported by the Subtarget
31467 static bool supportedVectorShiftWithImm(EVT VT, const X86Subtarget &Subtarget,
31468                                         unsigned Opcode) {
31469   if (!VT.isSimple())
31470     return false;
31471 
31472   if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
31473     return false;
31474 
31475   if (VT.getScalarSizeInBits() < 16)
31476     return false;
31477 
31478   if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
31479       (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
31480     return true;
31481 
31482   bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
31483                 (VT.is256BitVector() && Subtarget.hasInt256());
31484 
31485   bool AShift = LShift && (Subtarget.hasAVX512() ||
31486                            (VT != MVT::v2i64 && VT != MVT::v4i64));
31487   return (Opcode == ISD::SRA) ? AShift : LShift;
31488 }
31489 
31490 // The shift amount is a variable, but it is the same for all vector lanes.
31491 // These instructions are defined together with shift-immediate.
31492 static
31493 bool supportedVectorShiftWithBaseAmnt(EVT VT, const X86Subtarget &Subtarget,
31494                                       unsigned Opcode) {
31495   return supportedVectorShiftWithImm(VT, Subtarget, Opcode);
31496 }
31497 
31498 // Return true if the required (according to Opcode) variable-shift form is
31499 // natively supported by the Subtarget
31500 static bool supportedVectorVarShift(EVT VT, const X86Subtarget &Subtarget,
31501                                     unsigned Opcode) {
31502   if (!VT.isSimple())
31503     return false;
31504 
31505   if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
31506     return false;
31507 
31508   if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
31509     return false;
31510 
31511   // vXi16 supported only on AVX-512, BWI
31512   if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
31513     return false;
31514 
31515   if (Subtarget.hasAVX512() &&
31516       (Subtarget.useAVX512Regs() || !VT.is512BitVector()))
31517     return true;
31518 
31519   bool LShift = VT.is128BitVector() || VT.is256BitVector();
31520   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
31521   return (Opcode == ISD::SRA) ? AShift : LShift;
31522 }
31523 
31524 static SDValue LowerShiftByScalarImmediate(SDValue Op, SelectionDAG &DAG,
31525                                            const X86Subtarget &Subtarget) {
31526   MVT VT = Op.getSimpleValueType();
31527   SDLoc dl(Op);
31528   SDValue R = Op.getOperand(0);
31529   SDValue Amt = Op.getOperand(1);
31530   unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
31531 
31532   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
31533     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
31534     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
31535     SDValue Ex = DAG.getBitcast(ExVT, R);
31536 
31537     // ashr(R, 63) === cmp_slt(R, 0)
31538     if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
31539       assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
31540              "Unsupported PCMPGT op");
31541       return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
31542     }
31543 
31544     if (ShiftAmt >= 32) {
31545       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
31546       SDValue Upper =
31547           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
31548       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
31549                                                  ShiftAmt - 32, DAG);
31550       if (VT == MVT::v2i64)
31551         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
31552       if (VT == MVT::v4i64)
31553         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
31554                                   {9, 1, 11, 3, 13, 5, 15, 7});
31555     } else {
31556       // SRA upper i32, SRL whole i64 and select lower i32.
31557       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
31558                                                  ShiftAmt, DAG);
31559       SDValue Lower =
31560           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
31561       Lower = DAG.getBitcast(ExVT, Lower);
31562       if (VT == MVT::v2i64)
31563         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
31564       if (VT == MVT::v4i64)
31565         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
31566                                   {8, 1, 10, 3, 12, 5, 14, 7});
31567     }
31568     return DAG.getBitcast(VT, Ex);
31569   };
31570 
31571   // Optimize shl/srl/sra with constant shift amount.
31572   APInt APIntShiftAmt;
31573   if (!X86::isConstantSplat(Amt, APIntShiftAmt))
31574     return SDValue();
31575 
31576   // If the shift amount is out of range, return undef.
31577   if (APIntShiftAmt.uge(VT.getScalarSizeInBits()))
31578     return DAG.getUNDEF(VT);
31579 
31580   uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
31581 
31582   if (supportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode())) {
31583     // Hardware support for vector shifts is sparse which makes us scalarize the
31584     // vector operations in many cases. Also, on sandybridge ADD is faster than
31585     // shl: (shl V, 1) -> (add (freeze V), (freeze V))
31586     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1) {
31587       // R may be undef at run-time, but (shl R, 1) must be an even number (LSB
31588       // must be 0). (add undef, undef) however can be any value. To make this
31589       // safe, we must freeze R to ensure that register allocation uses the same
31590       // register for an undefined value. This ensures that the result will
31591       // still be even and preserves the original semantics.
31592       R = DAG.getFreeze(R);
31593       return DAG.getNode(ISD::ADD, dl, VT, R, R);
31594     }
31595 
31596     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
31597   }
31598 
31599   // i64 SRA needs to be performed as partial shifts.
31600   if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
31601        (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
31602       Op.getOpcode() == ISD::SRA)
31603     return ArithmeticShiftRight64(ShiftAmt);
31604 
31605   if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
31606       (Subtarget.hasBWI() && VT == MVT::v64i8)) {
31607     unsigned NumElts = VT.getVectorNumElements();
31608     MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
31609 
31610     // Simple i8 add case
31611     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1) {
31612       // R may be undef at run-time, but (shl R, 1) must be an even number (LSB
31613       // must be 0). (add undef, undef) however can be any value. To make this
31614       // safe, we must freeze R to ensure that register allocation uses the same
31615       // register for an undefined value. This ensures that the result will
31616       // still be even and preserves the original semantics.
31617       R = DAG.getFreeze(R);
31618       return DAG.getNode(ISD::ADD, dl, VT, R, R);
31619     }
31620 
31621     // ashr(R, 7)  === cmp_slt(R, 0)
31622     if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
31623       SDValue Zeros = DAG.getConstant(0, dl, VT);
31624       if (VT.is512BitVector()) {
31625         assert(VT == MVT::v64i8 && "Unexpected element type!");
31626         SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
31627         return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
31628       }
31629       return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
31630     }
31631 
31632     // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
31633     if (VT == MVT::v16i8 && Subtarget.hasXOP())
31634       return SDValue();
31635 
31636     if (Op.getOpcode() == ISD::SHL) {
31637       // Make a large shift.
31638       SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
31639                                                ShiftAmt, DAG);
31640       SHL = DAG.getBitcast(VT, SHL);
31641       // Zero out the rightmost bits.
31642       APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
31643       return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
31644     }
31645     if (Op.getOpcode() == ISD::SRL) {
31646       // Make a large shift.
31647       SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
31648                                                ShiftAmt, DAG);
31649       SRL = DAG.getBitcast(VT, SRL);
31650       // Zero out the leftmost bits.
31651       APInt Mask = APInt::getLowBitsSet(8, 8 - ShiftAmt);
31652       return DAG.getNode(ISD::AND, dl, VT, SRL, DAG.getConstant(Mask, dl, VT));
31653     }
31654     if (Op.getOpcode() == ISD::SRA) {
31655       // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
31656       SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
31657 
31658       SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
31659       Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
31660       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
31661       return Res;
31662     }
31663     llvm_unreachable("Unknown shift opcode.");
31664   }
31665 
31666   return SDValue();
31667 }
31668 
31669 static SDValue LowerShiftByScalarVariable(SDValue Op, SelectionDAG &DAG,
31670                                           const X86Subtarget &Subtarget) {
31671   MVT VT = Op.getSimpleValueType();
31672   SDLoc dl(Op);
31673   SDValue R = Op.getOperand(0);
31674   SDValue Amt = Op.getOperand(1);
31675   unsigned Opcode = Op.getOpcode();
31676   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
31677 
31678   int BaseShAmtIdx = -1;
31679   if (SDValue BaseShAmt = DAG.getSplatSourceVector(Amt, BaseShAmtIdx)) {
31680     if (supportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode))
31681       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, BaseShAmtIdx,
31682                                  Subtarget, DAG);
31683 
31684     // vXi8 shifts - shift as v8i16 + mask result.
31685     if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
31686          (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
31687          VT == MVT::v64i8) &&
31688         !Subtarget.hasXOP()) {
31689       unsigned NumElts = VT.getVectorNumElements();
31690       MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
31691       if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
31692         unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
31693         unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
31694 
31695         // Create the mask using vXi16 shifts. For shift-rights we need to move
31696         // the upper byte down before splatting the vXi8 mask.
31697         SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
31698         BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
31699                                       BaseShAmt, BaseShAmtIdx, Subtarget, DAG);
31700         if (Opcode != ISD::SHL)
31701           BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
31702                                                8, DAG);
31703         BitMask = DAG.getBitcast(VT, BitMask);
31704         BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
31705                                        SmallVector<int, 64>(NumElts, 0));
31706 
31707         SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
31708                                           DAG.getBitcast(ExtVT, R), BaseShAmt,
31709                                           BaseShAmtIdx, Subtarget, DAG);
31710         Res = DAG.getBitcast(VT, Res);
31711         Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
31712 
31713         if (Opcode == ISD::SRA) {
31714           // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
31715           // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
31716           SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
31717           SignMask =
31718               getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask, BaseShAmt,
31719                                   BaseShAmtIdx, Subtarget, DAG);
31720           SignMask = DAG.getBitcast(VT, SignMask);
31721           Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
31722           Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
31723         }
31724         return Res;
31725       }
31726     }
31727   }
31728 
31729   return SDValue();
31730 }
31731 
31732 // Convert a shift/rotate left amount to a multiplication scale factor.
31733 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
31734                                        const X86Subtarget &Subtarget,
31735                                        SelectionDAG &DAG) {
31736   MVT VT = Amt.getSimpleValueType();
31737   if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
31738         (Subtarget.hasInt256() && VT == MVT::v16i16) ||
31739         (Subtarget.hasAVX512() && VT == MVT::v32i16) ||
31740         (!Subtarget.hasAVX512() && VT == MVT::v16i8) ||
31741         (Subtarget.hasInt256() && VT == MVT::v32i8) ||
31742         (Subtarget.hasBWI() && VT == MVT::v64i8)))
31743     return SDValue();
31744 
31745   MVT SVT = VT.getVectorElementType();
31746   unsigned SVTBits = SVT.getSizeInBits();
31747   unsigned NumElems = VT.getVectorNumElements();
31748 
31749   APInt UndefElts;
31750   SmallVector<APInt> EltBits;
31751   if (getTargetConstantBitsFromNode(Amt, SVTBits, UndefElts, EltBits)) {
31752     APInt One(SVTBits, 1);
31753     SmallVector<SDValue> Elts(NumElems, DAG.getUNDEF(SVT));
31754     for (unsigned I = 0; I != NumElems; ++I) {
31755       if (UndefElts[I] || EltBits[I].uge(SVTBits))
31756         continue;
31757       uint64_t ShAmt = EltBits[I].getZExtValue();
31758       Elts[I] = DAG.getConstant(One.shl(ShAmt), dl, SVT);
31759     }
31760     return DAG.getBuildVector(VT, dl, Elts);
31761   }
31762 
31763   // If the target doesn't support variable shifts, use either FP conversion
31764   // or integer multiplication to avoid shifting each element individually.
31765   if (VT == MVT::v4i32) {
31766     Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
31767     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
31768                       DAG.getConstant(0x3f800000U, dl, VT));
31769     Amt = DAG.getBitcast(MVT::v4f32, Amt);
31770     return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
31771   }
31772 
31773   // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
31774   if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
31775     SDValue Z = DAG.getConstant(0, dl, VT);
31776     SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
31777     SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
31778     Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
31779     Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
31780     if (Subtarget.hasSSE41())
31781       return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
31782     return getPack(DAG, Subtarget, dl, VT, Lo, Hi);
31783   }
31784 
31785   return SDValue();
31786 }
31787 
31788 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
31789                           SelectionDAG &DAG) {
31790   MVT VT = Op.getSimpleValueType();
31791   SDLoc dl(Op);
31792   SDValue R = Op.getOperand(0);
31793   SDValue Amt = Op.getOperand(1);
31794   unsigned EltSizeInBits = VT.getScalarSizeInBits();
31795   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
31796 
31797   unsigned Opc = Op.getOpcode();
31798   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
31799   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
31800 
31801   assert(VT.isVector() && "Custom lowering only for vector shifts!");
31802   assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
31803 
31804   if (SDValue V = LowerShiftByScalarImmediate(Op, DAG, Subtarget))
31805     return V;
31806 
31807   if (SDValue V = LowerShiftByScalarVariable(Op, DAG, Subtarget))
31808     return V;
31809 
31810   if (supportedVectorVarShift(VT, Subtarget, Opc))
31811     return Op;
31812 
31813   // i64 vector arithmetic shift can be emulated with the transform:
31814   // M = lshr(SIGN_MASK, Amt)
31815   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
31816   if (((VT == MVT::v2i64 && !Subtarget.hasXOP()) ||
31817        (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
31818       Opc == ISD::SRA) {
31819     SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
31820     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
31821     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
31822     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
31823     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
31824     return R;
31825   }
31826 
31827   // XOP has 128-bit variable logical/arithmetic shifts.
31828   // +ve/-ve Amt = shift left/right.
31829   if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
31830                              VT == MVT::v8i16 || VT == MVT::v16i8)) {
31831     if (Opc == ISD::SRL || Opc == ISD::SRA) {
31832       SDValue Zero = DAG.getConstant(0, dl, VT);
31833       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
31834     }
31835     if (Opc == ISD::SHL || Opc == ISD::SRL)
31836       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
31837     if (Opc == ISD::SRA)
31838       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
31839   }
31840 
31841   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
31842   // shifts per-lane and then shuffle the partial results back together.
31843   if (VT == MVT::v2i64 && Opc != ISD::SRA) {
31844     // Splat the shift amounts so the scalar shifts above will catch it.
31845     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
31846     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
31847     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
31848     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
31849     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
31850   }
31851 
31852   // If possible, lower this shift as a sequence of two shifts by
31853   // constant plus a BLENDing shuffle instead of scalarizing it.
31854   // Example:
31855   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
31856   //
31857   // Could be rewritten as:
31858   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
31859   //
31860   // The advantage is that the two shifts from the example would be
31861   // lowered as X86ISD::VSRLI nodes in parallel before blending.
31862   if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
31863                       (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
31864     SDValue Amt1, Amt2;
31865     unsigned NumElts = VT.getVectorNumElements();
31866     SmallVector<int, 8> ShuffleMask;
31867     for (unsigned i = 0; i != NumElts; ++i) {
31868       SDValue A = Amt->getOperand(i);
31869       if (A.isUndef()) {
31870         ShuffleMask.push_back(SM_SentinelUndef);
31871         continue;
31872       }
31873       if (!Amt1 || Amt1 == A) {
31874         ShuffleMask.push_back(i);
31875         Amt1 = A;
31876         continue;
31877       }
31878       if (!Amt2 || Amt2 == A) {
31879         ShuffleMask.push_back(i + NumElts);
31880         Amt2 = A;
31881         continue;
31882       }
31883       break;
31884     }
31885 
31886     // Only perform this blend if we can perform it without loading a mask.
31887     if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
31888         (VT != MVT::v16i16 ||
31889          is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
31890         (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
31891          canWidenShuffleElements(ShuffleMask))) {
31892       auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
31893       auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
31894       if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
31895           Cst2->getAPIntValue().ult(EltSizeInBits)) {
31896         SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
31897                                                     Cst1->getZExtValue(), DAG);
31898         SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
31899                                                     Cst2->getZExtValue(), DAG);
31900         return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
31901       }
31902     }
31903   }
31904 
31905   // If possible, lower this packed shift into a vector multiply instead of
31906   // expanding it into a sequence of scalar shifts.
31907   // For v32i8 cases, it might be quicker to split/extend to vXi16 shifts.
31908   if (Opc == ISD::SHL && !(VT == MVT::v32i8 && (Subtarget.hasXOP() ||
31909                                                 Subtarget.canExtendTo512BW())))
31910     if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
31911       return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
31912 
31913   // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
31914   // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
31915   if (Opc == ISD::SRL && ConstantAmt &&
31916       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
31917     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
31918     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
31919     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
31920       SDValue Zero = DAG.getConstant(0, dl, VT);
31921       SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
31922       SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
31923       return DAG.getSelect(dl, VT, ZAmt, R, Res);
31924     }
31925   }
31926 
31927   // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
31928   // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
31929   // TODO: Special case handling for shift by 0/1, really we can afford either
31930   // of these cases in pre-SSE41/XOP/AVX512 but not both.
31931   if (Opc == ISD::SRA && ConstantAmt &&
31932       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
31933       ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
31934         !Subtarget.hasAVX512()) ||
31935        DAG.isKnownNeverZero(Amt))) {
31936     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
31937     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
31938     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
31939       SDValue Amt0 =
31940           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
31941       SDValue Amt1 =
31942           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
31943       SDValue Sra1 =
31944           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
31945       SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
31946       Res = DAG.getSelect(dl, VT, Amt0, R, Res);
31947       return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
31948     }
31949   }
31950 
31951   // v4i32 Non Uniform Shifts.
31952   // If the shift amount is constant we can shift each lane using the SSE2
31953   // immediate shifts, else we need to zero-extend each lane to the lower i64
31954   // and shift using the SSE2 variable shifts.
31955   // The separate results can then be blended together.
31956   if (VT == MVT::v4i32) {
31957     SDValue Amt0, Amt1, Amt2, Amt3;
31958     if (ConstantAmt) {
31959       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
31960       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
31961       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
31962       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
31963     } else {
31964       // The SSE2 shifts use the lower i64 as the same shift amount for
31965       // all lanes and the upper i64 is ignored. On AVX we're better off
31966       // just zero-extending, but for SSE just duplicating the top 16-bits is
31967       // cheaper and has the same effect for out of range values.
31968       if (Subtarget.hasAVX()) {
31969         SDValue Z = DAG.getConstant(0, dl, VT);
31970         Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
31971         Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
31972         Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
31973         Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
31974       } else {
31975         SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
31976         SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
31977                                              {4, 5, 6, 7, -1, -1, -1, -1});
31978         SDValue Msk02 = getV4X86ShuffleImm8ForMask({0, 1, 1, 1}, dl, DAG);
31979         SDValue Msk13 = getV4X86ShuffleImm8ForMask({2, 3, 3, 3}, dl, DAG);
31980         Amt0 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt01, Msk02);
31981         Amt1 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt01, Msk13);
31982         Amt2 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt23, Msk02);
31983         Amt3 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt23, Msk13);
31984       }
31985     }
31986 
31987     unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
31988     SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
31989     SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
31990     SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
31991     SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
31992 
31993     // Merge the shifted lane results optimally with/without PBLENDW.
31994     // TODO - ideally shuffle combining would handle this.
31995     if (Subtarget.hasSSE41()) {
31996       SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
31997       SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
31998       return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
31999     }
32000     SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
32001     SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
32002     return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
32003   }
32004 
32005   // It's worth extending once and using the vXi16/vXi32 shifts for smaller
32006   // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
32007   // make the existing SSE solution better.
32008   // NOTE: We honor prefered vector width before promoting to 512-bits.
32009   if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
32010       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
32011       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
32012       (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
32013       (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
32014     assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
32015            "Unexpected vector type");
32016     MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
32017     MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
32018     unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
32019     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
32020     Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
32021     return DAG.getNode(ISD::TRUNCATE, dl, VT,
32022                        DAG.getNode(Opc, dl, ExtVT, R, Amt));
32023   }
32024 
32025   // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
32026   // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
32027   if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
32028       (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
32029        (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
32030       !Subtarget.hasXOP()) {
32031     int NumElts = VT.getVectorNumElements();
32032     SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
32033 
32034     // Extend constant shift amount to vXi16 (it doesn't matter if the type
32035     // isn't legal).
32036     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
32037     Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
32038     Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
32039     Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
32040     assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
32041            "Constant build vector expected");
32042 
32043     if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
32044       bool IsSigned = Opc == ISD::SRA;
32045       R = DAG.getExtOrTrunc(IsSigned, R, dl, ExVT);
32046       R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
32047       R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
32048       return DAG.getZExtOrTrunc(R, dl, VT);
32049     }
32050 
32051     SmallVector<SDValue, 16> LoAmt, HiAmt;
32052     for (int i = 0; i != NumElts; i += 16) {
32053       for (int j = 0; j != 8; ++j) {
32054         LoAmt.push_back(Amt.getOperand(i + j));
32055         HiAmt.push_back(Amt.getOperand(i + j + 8));
32056       }
32057     }
32058 
32059     MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
32060     SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
32061     SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
32062 
32063     SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
32064     SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
32065     LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
32066     HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
32067     LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
32068     HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
32069     LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
32070     HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
32071     return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
32072   }
32073 
32074   if (VT == MVT::v16i8 ||
32075       (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
32076       (VT == MVT::v64i8 && Subtarget.hasBWI())) {
32077     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
32078 
32079     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
32080       if (VT.is512BitVector()) {
32081         // On AVX512BW targets we make use of the fact that VSELECT lowers
32082         // to a masked blend which selects bytes based just on the sign bit
32083         // extracted to a mask.
32084         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
32085         V0 = DAG.getBitcast(VT, V0);
32086         V1 = DAG.getBitcast(VT, V1);
32087         Sel = DAG.getBitcast(VT, Sel);
32088         Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
32089                            ISD::SETGT);
32090         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
32091       } else if (Subtarget.hasSSE41()) {
32092         // On SSE41 targets we can use PBLENDVB which selects bytes based just
32093         // on the sign bit.
32094         V0 = DAG.getBitcast(VT, V0);
32095         V1 = DAG.getBitcast(VT, V1);
32096         Sel = DAG.getBitcast(VT, Sel);
32097         return DAG.getBitcast(SelVT,
32098                               DAG.getNode(X86ISD::BLENDV, dl, VT, Sel, V0, V1));
32099       }
32100       // On pre-SSE41 targets we test for the sign bit by comparing to
32101       // zero - a negative value will set all bits of the lanes to true
32102       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
32103       SDValue Z = DAG.getConstant(0, dl, SelVT);
32104       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
32105       return DAG.getSelect(dl, SelVT, C, V0, V1);
32106     };
32107 
32108     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
32109     // We can safely do this using i16 shifts as we're only interested in
32110     // the 3 lower bits of each byte.
32111     Amt = DAG.getBitcast(ExtVT, Amt);
32112     Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
32113     Amt = DAG.getBitcast(VT, Amt);
32114 
32115     if (Opc == ISD::SHL || Opc == ISD::SRL) {
32116       // r = VSELECT(r, shift(r, 4), a);
32117       SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
32118       R = SignBitSelect(VT, Amt, M, R);
32119 
32120       // a += a
32121       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
32122 
32123       // r = VSELECT(r, shift(r, 2), a);
32124       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
32125       R = SignBitSelect(VT, Amt, M, R);
32126 
32127       // a += a
32128       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
32129 
32130       // return VSELECT(r, shift(r, 1), a);
32131       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
32132       R = SignBitSelect(VT, Amt, M, R);
32133       return R;
32134     }
32135 
32136     if (Opc == ISD::SRA) {
32137       // For SRA we need to unpack each byte to the higher byte of a i16 vector
32138       // so we can correctly sign extend. We don't care what happens to the
32139       // lower byte.
32140       SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
32141       SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
32142       SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
32143       SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
32144       ALo = DAG.getBitcast(ExtVT, ALo);
32145       AHi = DAG.getBitcast(ExtVT, AHi);
32146       RLo = DAG.getBitcast(ExtVT, RLo);
32147       RHi = DAG.getBitcast(ExtVT, RHi);
32148 
32149       // r = VSELECT(r, shift(r, 4), a);
32150       SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
32151       SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
32152       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
32153       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
32154 
32155       // a += a
32156       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
32157       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
32158 
32159       // r = VSELECT(r, shift(r, 2), a);
32160       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
32161       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
32162       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
32163       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
32164 
32165       // a += a
32166       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
32167       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
32168 
32169       // r = VSELECT(r, shift(r, 1), a);
32170       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
32171       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
32172       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
32173       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
32174 
32175       // Logical shift the result back to the lower byte, leaving a zero upper
32176       // byte meaning that we can safely pack with PACKUSWB.
32177       RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
32178       RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
32179       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
32180     }
32181   }
32182 
32183   if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
32184     MVT ExtVT = MVT::v8i32;
32185     SDValue Z = DAG.getConstant(0, dl, VT);
32186     SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
32187     SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
32188     SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
32189     SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
32190     ALo = DAG.getBitcast(ExtVT, ALo);
32191     AHi = DAG.getBitcast(ExtVT, AHi);
32192     RLo = DAG.getBitcast(ExtVT, RLo);
32193     RHi = DAG.getBitcast(ExtVT, RHi);
32194     SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
32195     SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
32196     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
32197     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
32198     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
32199   }
32200 
32201   if (VT == MVT::v8i16) {
32202     // If we have a constant shift amount, the non-SSE41 path is best as
32203     // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
32204     bool UseSSE41 = Subtarget.hasSSE41() &&
32205                     !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
32206 
32207     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
32208       // On SSE41 targets we can use PBLENDVB which selects bytes based just on
32209       // the sign bit.
32210       if (UseSSE41) {
32211         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
32212         V0 = DAG.getBitcast(ExtVT, V0);
32213         V1 = DAG.getBitcast(ExtVT, V1);
32214         Sel = DAG.getBitcast(ExtVT, Sel);
32215         return DAG.getBitcast(
32216             VT, DAG.getNode(X86ISD::BLENDV, dl, ExtVT, Sel, V0, V1));
32217       }
32218       // On pre-SSE41 targets we splat the sign bit - a negative value will
32219       // set all bits of the lanes to true and VSELECT uses that in
32220       // its OR(AND(V0,C),AND(V1,~C)) lowering.
32221       SDValue C =
32222           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
32223       return DAG.getSelect(dl, VT, C, V0, V1);
32224     };
32225 
32226     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
32227     if (UseSSE41) {
32228       // On SSE41 targets we need to replicate the shift mask in both
32229       // bytes for PBLENDVB.
32230       Amt = DAG.getNode(
32231           ISD::OR, dl, VT,
32232           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
32233           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
32234     } else {
32235       Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
32236     }
32237 
32238     // r = VSELECT(r, shift(r, 8), a);
32239     SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
32240     R = SignBitSelect(Amt, M, R);
32241 
32242     // a += a
32243     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
32244 
32245     // r = VSELECT(r, shift(r, 4), a);
32246     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
32247     R = SignBitSelect(Amt, M, R);
32248 
32249     // a += a
32250     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
32251 
32252     // r = VSELECT(r, shift(r, 2), a);
32253     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
32254     R = SignBitSelect(Amt, M, R);
32255 
32256     // a += a
32257     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
32258 
32259     // return VSELECT(r, shift(r, 1), a);
32260     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
32261     R = SignBitSelect(Amt, M, R);
32262     return R;
32263   }
32264 
32265   // Decompose 256-bit shifts into 128-bit shifts.
32266   if (VT.is256BitVector())
32267     return splitVectorIntBinary(Op, DAG);
32268 
32269   if (VT == MVT::v32i16 || VT == MVT::v64i8)
32270     return splitVectorIntBinary(Op, DAG);
32271 
32272   return SDValue();
32273 }
32274 
32275 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
32276                                 SelectionDAG &DAG) {
32277   MVT VT = Op.getSimpleValueType();
32278   assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
32279          "Unexpected funnel shift opcode!");
32280 
32281   SDLoc DL(Op);
32282   SDValue Op0 = Op.getOperand(0);
32283   SDValue Op1 = Op.getOperand(1);
32284   SDValue Amt = Op.getOperand(2);
32285   unsigned EltSizeInBits = VT.getScalarSizeInBits();
32286   bool IsFSHR = Op.getOpcode() == ISD::FSHR;
32287 
32288   if (VT.isVector()) {
32289     APInt APIntShiftAmt;
32290     bool IsCstSplat = X86::isConstantSplat(Amt, APIntShiftAmt);
32291 
32292     if (Subtarget.hasVBMI2() && EltSizeInBits > 8) {
32293       if (IsFSHR)
32294         std::swap(Op0, Op1);
32295 
32296       if (IsCstSplat) {
32297         uint64_t ShiftAmt = APIntShiftAmt.urem(EltSizeInBits);
32298         SDValue Imm = DAG.getTargetConstant(ShiftAmt, DL, MVT::i8);
32299         return getAVX512Node(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT,
32300                              {Op0, Op1, Imm}, DAG, Subtarget);
32301       }
32302       return getAVX512Node(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
32303                            {Op0, Op1, Amt}, DAG, Subtarget);
32304     }
32305     assert((VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8 ||
32306             VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16 ||
32307             VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) &&
32308            "Unexpected funnel shift type!");
32309 
32310     // fshl(x,y,z) -> unpack(y,x) << (z & (bw-1))) >> bw.
32311     // fshr(x,y,z) -> unpack(y,x) >> (z & (bw-1))).
32312     if (IsCstSplat) {
32313       // TODO: Can't use generic expansion as UNDEF amt elements can be
32314       // converted to other values when folded to shift amounts, losing the
32315       // splat.
32316       uint64_t ShiftAmt = APIntShiftAmt.urem(EltSizeInBits);
32317       uint64_t ShXAmt = IsFSHR ? (EltSizeInBits - ShiftAmt) : ShiftAmt;
32318       uint64_t ShYAmt = IsFSHR ? ShiftAmt : (EltSizeInBits - ShiftAmt);
32319       SDValue ShX = DAG.getNode(ISD::SHL, DL, VT, Op0,
32320                                 DAG.getShiftAmountConstant(ShXAmt, VT, DL));
32321       SDValue ShY = DAG.getNode(ISD::SRL, DL, VT, Op1,
32322                                 DAG.getShiftAmountConstant(ShYAmt, VT, DL));
32323       return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
32324     }
32325 
32326     SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
32327     SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
32328     bool IsCst = ISD::isBuildVectorOfConstantSDNodes(AmtMod.getNode());
32329 
32330     // Constant vXi16 funnel shifts can be efficiently handled by default.
32331     if (IsCst && EltSizeInBits == 16)
32332       return SDValue();
32333 
32334     unsigned ShiftOpc = IsFSHR ? ISD::SRL : ISD::SHL;
32335     unsigned NumElts = VT.getVectorNumElements();
32336     MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
32337     MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
32338 
32339     // Split 256-bit integers on XOP/pre-AVX2 targets.
32340     // Split 512-bit integers on non 512-bit BWI targets.
32341     if ((VT.is256BitVector() && ((Subtarget.hasXOP() && EltSizeInBits < 16) ||
32342                                  !Subtarget.hasAVX2())) ||
32343         (VT.is512BitVector() && !Subtarget.useBWIRegs() &&
32344          EltSizeInBits < 32)) {
32345       // Pre-mask the amount modulo using the wider vector.
32346       Op = DAG.getNode(Op.getOpcode(), DL, VT, Op0, Op1, AmtMod);
32347       return splitVectorOp(Op, DAG);
32348     }
32349 
32350     // Attempt to fold scalar shift as unpack(y,x) << zext(splat(z))
32351     if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, ShiftOpc)) {
32352       int ScalarAmtIdx = -1;
32353       if (SDValue ScalarAmt = DAG.getSplatSourceVector(AmtMod, ScalarAmtIdx)) {
32354         // Uniform vXi16 funnel shifts can be efficiently handled by default.
32355         if (EltSizeInBits == 16)
32356           return SDValue();
32357 
32358         SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, Op1, Op0));
32359         SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, Op1, Op0));
32360         Lo = getTargetVShiftNode(ShiftOpc, DL, ExtVT, Lo, ScalarAmt,
32361                                  ScalarAmtIdx, Subtarget, DAG);
32362         Hi = getTargetVShiftNode(ShiftOpc, DL, ExtVT, Hi, ScalarAmt,
32363                                  ScalarAmtIdx, Subtarget, DAG);
32364         return getPack(DAG, Subtarget, DL, VT, Lo, Hi, !IsFSHR);
32365       }
32366     }
32367 
32368     MVT WideSVT = MVT::getIntegerVT(
32369         std::min<unsigned>(EltSizeInBits * 2, Subtarget.hasBWI() ? 16 : 32));
32370     MVT WideVT = MVT::getVectorVT(WideSVT, NumElts);
32371 
32372     // If per-element shifts are legal, fallback to generic expansion.
32373     if (supportedVectorVarShift(VT, Subtarget, ShiftOpc) || Subtarget.hasXOP())
32374       return SDValue();
32375 
32376     // Attempt to fold as:
32377     // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
32378     // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
32379     if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
32380         supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
32381       Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Op0);
32382       Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Op1);
32383       AmtMod = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
32384       Op0 = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, Op0,
32385                                        EltSizeInBits, DAG);
32386       SDValue Res = DAG.getNode(ISD::OR, DL, WideVT, Op0, Op1);
32387       Res = DAG.getNode(ShiftOpc, DL, WideVT, Res, AmtMod);
32388       if (!IsFSHR)
32389         Res = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, Res,
32390                                          EltSizeInBits, DAG);
32391       return DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
32392     }
32393 
32394     // Attempt to fold per-element (ExtVT) shift as unpack(y,x) << zext(z)
32395     if (((IsCst || !Subtarget.hasAVX512()) && !IsFSHR && EltSizeInBits <= 16) ||
32396         supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc)) {
32397       SDValue Z = DAG.getConstant(0, DL, VT);
32398       SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, Op1, Op0));
32399       SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, Op1, Op0));
32400       SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
32401       SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
32402       SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
32403       SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
32404       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, !IsFSHR);
32405     }
32406 
32407     // Fallback to generic expansion.
32408     return SDValue();
32409   }
32410   assert(
32411       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
32412       "Unexpected funnel shift type!");
32413 
32414   // Expand slow SHLD/SHRD cases if we are not optimizing for size.
32415   bool OptForSize = DAG.shouldOptForSize();
32416   bool ExpandFunnel = !OptForSize && Subtarget.isSHLDSlow();
32417 
32418   // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
32419   // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
32420   if ((VT == MVT::i8 || (ExpandFunnel && VT == MVT::i16)) &&
32421       !isa<ConstantSDNode>(Amt)) {
32422     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, Amt.getValueType());
32423     SDValue HiShift = DAG.getConstant(EltSizeInBits, DL, Amt.getValueType());
32424     Op0 = DAG.getAnyExtOrTrunc(Op0, DL, MVT::i32);
32425     Op1 = DAG.getZExtOrTrunc(Op1, DL, MVT::i32);
32426     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt, Mask);
32427     SDValue Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Op0, HiShift);
32428     Res = DAG.getNode(ISD::OR, DL, MVT::i32, Res, Op1);
32429     if (IsFSHR) {
32430       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, Amt);
32431     } else {
32432       Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Res, Amt);
32433       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, HiShift);
32434     }
32435     return DAG.getZExtOrTrunc(Res, DL, VT);
32436   }
32437 
32438   if (VT == MVT::i8 || ExpandFunnel)
32439     return SDValue();
32440 
32441   // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
32442   if (VT == MVT::i16) {
32443     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
32444                       DAG.getConstant(15, DL, Amt.getValueType()));
32445     unsigned FSHOp = (IsFSHR ? X86ISD::FSHR : X86ISD::FSHL);
32446     return DAG.getNode(FSHOp, DL, VT, Op0, Op1, Amt);
32447   }
32448 
32449   return Op;
32450 }
32451 
32452 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
32453                            SelectionDAG &DAG) {
32454   MVT VT = Op.getSimpleValueType();
32455   assert(VT.isVector() && "Custom lowering only for vector rotates!");
32456 
32457   SDLoc DL(Op);
32458   SDValue R = Op.getOperand(0);
32459   SDValue Amt = Op.getOperand(1);
32460   unsigned Opcode = Op.getOpcode();
32461   unsigned EltSizeInBits = VT.getScalarSizeInBits();
32462   int NumElts = VT.getVectorNumElements();
32463   bool IsROTL = Opcode == ISD::ROTL;
32464 
32465   // Check for constant splat rotation amount.
32466   APInt CstSplatValue;
32467   bool IsCstSplat = X86::isConstantSplat(Amt, CstSplatValue);
32468 
32469   // Check for splat rotate by zero.
32470   if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
32471     return R;
32472 
32473   // AVX512 implicitly uses modulo rotation amounts.
32474   if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
32475     // Attempt to rotate by immediate.
32476     if (IsCstSplat) {
32477       unsigned RotOpc = IsROTL ? X86ISD::VROTLI : X86ISD::VROTRI;
32478       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
32479       return DAG.getNode(RotOpc, DL, VT, R,
32480                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
32481     }
32482 
32483     // Else, fall-back on VPROLV/VPRORV.
32484     return Op;
32485   }
32486 
32487   // AVX512 VBMI2 vXi16 - lower to funnel shifts.
32488   if (Subtarget.hasVBMI2() && 16 == EltSizeInBits) {
32489     unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
32490     return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
32491   }
32492 
32493   SDValue Z = DAG.getConstant(0, DL, VT);
32494 
32495   if (!IsROTL) {
32496     // If the ISD::ROTR amount is constant, we're always better converting to
32497     // ISD::ROTL.
32498     if (SDValue NegAmt = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {Z, Amt}))
32499       return DAG.getNode(ISD::ROTL, DL, VT, R, NegAmt);
32500 
32501     // XOP targets always prefers ISD::ROTL.
32502     if (Subtarget.hasXOP())
32503       return DAG.getNode(ISD::ROTL, DL, VT, R,
32504                          DAG.getNode(ISD::SUB, DL, VT, Z, Amt));
32505   }
32506 
32507   // Split 256-bit integers on XOP/pre-AVX2 targets.
32508   if (VT.is256BitVector() && (Subtarget.hasXOP() || !Subtarget.hasAVX2()))
32509     return splitVectorIntBinary(Op, DAG);
32510 
32511   // XOP has 128-bit vector variable + immediate rotates.
32512   // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
32513   // XOP implicitly uses modulo rotation amounts.
32514   if (Subtarget.hasXOP()) {
32515     assert(IsROTL && "Only ROTL expected");
32516     assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
32517 
32518     // Attempt to rotate by immediate.
32519     if (IsCstSplat) {
32520       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
32521       return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
32522                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
32523     }
32524 
32525     // Use general rotate by variable (per-element).
32526     return Op;
32527   }
32528 
32529   // Rotate by an uniform constant - expand back to shifts.
32530   // TODO: Can't use generic expansion as UNDEF amt elements can be converted
32531   // to other values when folded to shift amounts, losing the splat.
32532   if (IsCstSplat) {
32533     uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
32534     uint64_t ShlAmt = IsROTL ? RotAmt : (EltSizeInBits - RotAmt);
32535     uint64_t SrlAmt = IsROTL ? (EltSizeInBits - RotAmt) : RotAmt;
32536     SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, R,
32537                               DAG.getShiftAmountConstant(ShlAmt, VT, DL));
32538     SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, R,
32539                               DAG.getShiftAmountConstant(SrlAmt, VT, DL));
32540     return DAG.getNode(ISD::OR, DL, VT, Shl, Srl);
32541   }
32542 
32543   // Split 512-bit integers on non 512-bit BWI targets.
32544   if (VT.is512BitVector() && !Subtarget.useBWIRegs())
32545     return splitVectorIntBinary(Op, DAG);
32546 
32547   assert(
32548       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
32549        ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&
32550         Subtarget.hasAVX2()) ||
32551        ((VT == MVT::v32i16 || VT == MVT::v64i8) && Subtarget.useBWIRegs())) &&
32552       "Only vXi32/vXi16/vXi8 vector rotates supported");
32553 
32554   MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
32555   MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
32556 
32557   SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
32558   SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
32559 
32560   // Attempt to fold as unpack(x,x) << zext(splat(y)):
32561   // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
32562   // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
32563   if (EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) {
32564     int BaseRotAmtIdx = -1;
32565     if (SDValue BaseRotAmt = DAG.getSplatSourceVector(AmtMod, BaseRotAmtIdx)) {
32566       if (EltSizeInBits == 16 && Subtarget.hasSSE41()) {
32567         unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
32568         return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
32569       }
32570       unsigned ShiftX86Opc = IsROTL ? X86ISD::VSHLI : X86ISD::VSRLI;
32571       SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
32572       SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
32573       Lo = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Lo, BaseRotAmt,
32574                                BaseRotAmtIdx, Subtarget, DAG);
32575       Hi = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Hi, BaseRotAmt,
32576                                BaseRotAmtIdx, Subtarget, DAG);
32577       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
32578     }
32579   }
32580 
32581   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
32582   unsigned ShiftOpc = IsROTL ? ISD::SHL : ISD::SRL;
32583 
32584   // Attempt to fold as unpack(x,x) << zext(y):
32585   // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
32586   // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
32587   // Const vXi16/vXi32 are excluded in favor of MUL-based lowering.
32588   if (!(ConstantAmt && EltSizeInBits != 8) &&
32589       !supportedVectorVarShift(VT, Subtarget, ShiftOpc) &&
32590       (ConstantAmt || supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc))) {
32591     SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
32592     SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
32593     SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
32594     SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
32595     SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
32596     SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
32597     return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
32598   }
32599 
32600   // v16i8/v32i8/v64i8: Split rotation into rot4/rot2/rot1 stages and select by
32601   // the amount bit.
32602   // TODO: We're doing nothing here that we couldn't do for funnel shifts.
32603   if (EltSizeInBits == 8) {
32604     MVT WideVT =
32605         MVT::getVectorVT(Subtarget.hasBWI() ? MVT::i16 : MVT::i32, NumElts);
32606 
32607     // Attempt to fold as:
32608     // rotl(x,y) -> (((aext(x) << bw) | zext(x)) << (y & (bw-1))) >> bw.
32609     // rotr(x,y) -> (((aext(x) << bw) | zext(x)) >> (y & (bw-1))).
32610     if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
32611         supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
32612       // If we're rotating by constant, just use default promotion.
32613       if (ConstantAmt)
32614         return SDValue();
32615       // See if we can perform this by widening to vXi16 or vXi32.
32616       R = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, R);
32617       R = DAG.getNode(
32618           ISD::OR, DL, WideVT, R,
32619           getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, R, 8, DAG));
32620       Amt = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
32621       R = DAG.getNode(ShiftOpc, DL, WideVT, R, Amt);
32622       if (IsROTL)
32623         R = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, R, 8, DAG);
32624       return DAG.getNode(ISD::TRUNCATE, DL, VT, R);
32625     }
32626 
32627     // We don't need ModuloAmt here as we just peek at individual bits.
32628     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
32629       if (Subtarget.hasSSE41()) {
32630         // On SSE41 targets we can use PBLENDVB which selects bytes based just
32631         // on the sign bit.
32632         V0 = DAG.getBitcast(VT, V0);
32633         V1 = DAG.getBitcast(VT, V1);
32634         Sel = DAG.getBitcast(VT, Sel);
32635         return DAG.getBitcast(SelVT,
32636                               DAG.getNode(X86ISD::BLENDV, DL, VT, Sel, V0, V1));
32637       }
32638       // On pre-SSE41 targets we test for the sign bit by comparing to
32639       // zero - a negative value will set all bits of the lanes to true
32640       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
32641       SDValue Z = DAG.getConstant(0, DL, SelVT);
32642       SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
32643       return DAG.getSelect(DL, SelVT, C, V0, V1);
32644     };
32645 
32646     // ISD::ROTR is currently only profitable on AVX512 targets with VPTERNLOG.
32647     if (!IsROTL && !useVPTERNLOG(Subtarget, VT)) {
32648       Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
32649       IsROTL = true;
32650     }
32651 
32652     unsigned ShiftLHS = IsROTL ? ISD::SHL : ISD::SRL;
32653     unsigned ShiftRHS = IsROTL ? ISD::SRL : ISD::SHL;
32654 
32655     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
32656     // We can safely do this using i16 shifts as we're only interested in
32657     // the 3 lower bits of each byte.
32658     Amt = DAG.getBitcast(ExtVT, Amt);
32659     Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
32660     Amt = DAG.getBitcast(VT, Amt);
32661 
32662     // r = VSELECT(r, rot(r, 4), a);
32663     SDValue M;
32664     M = DAG.getNode(
32665         ISD::OR, DL, VT,
32666         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(4, DL, VT)),
32667         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(4, DL, VT)));
32668     R = SignBitSelect(VT, Amt, M, R);
32669 
32670     // a += a
32671     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
32672 
32673     // r = VSELECT(r, rot(r, 2), a);
32674     M = DAG.getNode(
32675         ISD::OR, DL, VT,
32676         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(2, DL, VT)),
32677         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(6, DL, VT)));
32678     R = SignBitSelect(VT, Amt, M, R);
32679 
32680     // a += a
32681     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
32682 
32683     // return VSELECT(r, rot(r, 1), a);
32684     M = DAG.getNode(
32685         ISD::OR, DL, VT,
32686         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(1, DL, VT)),
32687         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(7, DL, VT)));
32688     return SignBitSelect(VT, Amt, M, R);
32689   }
32690 
32691   bool IsSplatAmt = DAG.isSplatValue(Amt);
32692   bool LegalVarShifts = supportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
32693                         supportedVectorVarShift(VT, Subtarget, ISD::SRL);
32694 
32695   // Fallback for splats + all supported variable shifts.
32696   // Fallback for non-constants AVX2 vXi16 as well.
32697   if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
32698     Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
32699     SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
32700     AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
32701     SDValue SHL = DAG.getNode(IsROTL ? ISD::SHL : ISD::SRL, DL, VT, R, Amt);
32702     SDValue SRL = DAG.getNode(IsROTL ? ISD::SRL : ISD::SHL, DL, VT, R, AmtR);
32703     return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
32704   }
32705 
32706   // Everything below assumes ISD::ROTL.
32707   if (!IsROTL) {
32708     Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
32709     IsROTL = true;
32710   }
32711 
32712   // ISD::ROT* uses modulo rotate amounts.
32713   Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
32714 
32715   assert(IsROTL && "Only ROTL supported");
32716 
32717   // As with shifts, attempt to convert the rotation amount to a multiplication
32718   // factor, fallback to general expansion.
32719   SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
32720   if (!Scale)
32721     return SDValue();
32722 
32723   // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
32724   if (EltSizeInBits == 16) {
32725     SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
32726     SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
32727     return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
32728   }
32729 
32730   // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
32731   // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
32732   // that can then be OR'd with the lower 32-bits.
32733   assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
32734   static const int OddMask[] = {1, -1, 3, -1};
32735   SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
32736   SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
32737 
32738   SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
32739                               DAG.getBitcast(MVT::v2i64, R),
32740                               DAG.getBitcast(MVT::v2i64, Scale));
32741   SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
32742                               DAG.getBitcast(MVT::v2i64, R13),
32743                               DAG.getBitcast(MVT::v2i64, Scale13));
32744   Res02 = DAG.getBitcast(VT, Res02);
32745   Res13 = DAG.getBitcast(VT, Res13);
32746 
32747   return DAG.getNode(ISD::OR, DL, VT,
32748                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
32749                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
32750 }
32751 
32752 /// Returns true if the operand type is exactly twice the native width, and
32753 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
32754 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
32755 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
32756 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
32757   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
32758 
32759   if (OpWidth == 64)
32760     return Subtarget.canUseCMPXCHG8B() && !Subtarget.is64Bit();
32761   if (OpWidth == 128)
32762     return Subtarget.canUseCMPXCHG16B();
32763 
32764   return false;
32765 }
32766 
32767 TargetLoweringBase::AtomicExpansionKind
32768 X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
32769   Type *MemType = SI->getValueOperand()->getType();
32770 
32771   bool NoImplicitFloatOps =
32772       SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
32773   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
32774       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
32775       (Subtarget.hasSSE1() || Subtarget.hasX87()))
32776     return AtomicExpansionKind::None;
32777 
32778   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::Expand
32779                                  : AtomicExpansionKind::None;
32780 }
32781 
32782 // Note: this turns large loads into lock cmpxchg8b/16b.
32783 // TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
32784 TargetLowering::AtomicExpansionKind
32785 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
32786   Type *MemType = LI->getType();
32787 
32788   // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
32789   // can use movq to do the load. If we have X87 we can load into an 80-bit
32790   // X87 register and store it to a stack temporary.
32791   bool NoImplicitFloatOps =
32792       LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
32793   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
32794       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
32795       (Subtarget.hasSSE1() || Subtarget.hasX87()))
32796     return AtomicExpansionKind::None;
32797 
32798   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
32799                                  : AtomicExpansionKind::None;
32800 }
32801 
32802 enum BitTestKind : unsigned {
32803   UndefBit,
32804   ConstantBit,
32805   NotConstantBit,
32806   ShiftBit,
32807   NotShiftBit
32808 };
32809 
32810 static std::pair<Value *, BitTestKind> FindSingleBitChange(Value *V) {
32811   using namespace llvm::PatternMatch;
32812   BitTestKind BTK = UndefBit;
32813   auto *C = dyn_cast<ConstantInt>(V);
32814   if (C) {
32815     // Check if V is a power of 2 or NOT power of 2.
32816     if (isPowerOf2_64(C->getZExtValue()))
32817       BTK = ConstantBit;
32818     else if (isPowerOf2_64((~C->getValue()).getZExtValue()))
32819       BTK = NotConstantBit;
32820     return {V, BTK};
32821   }
32822 
32823   // Check if V is some power of 2 pattern known to be non-zero
32824   auto *I = dyn_cast<Instruction>(V);
32825   if (I) {
32826     bool Not = false;
32827     // Check if we have a NOT
32828     Value *PeekI;
32829     if (match(I, m_c_Xor(m_Value(PeekI), m_AllOnes())) ||
32830         match(I, m_Sub(m_AllOnes(), m_Value(PeekI)))) {
32831       Not = true;
32832       I = dyn_cast<Instruction>(PeekI);
32833 
32834       // If I is constant, it will fold and we can evaluate later. If its an
32835       // argument or something of that nature, we can't analyze.
32836       if (I == nullptr)
32837         return {nullptr, UndefBit};
32838     }
32839     // We can only use 1 << X without more sophisticated analysis. C << X where
32840     // C is a power of 2 but not 1 can result in zero which cannot be translated
32841     // to bittest. Likewise any C >> X (either arith or logical) can be zero.
32842     if (I->getOpcode() == Instruction::Shl) {
32843       // Todo(1): The cmpxchg case is pretty costly so matching `BLSI(X)`, `X &
32844       // -X` and some other provable power of 2 patterns that we can use CTZ on
32845       // may be profitable.
32846       // Todo(2): It may be possible in some cases to prove that Shl(C, X) is
32847       // non-zero even where C != 1. Likewise LShr(C, X) and AShr(C, X) may also
32848       // be provably a non-zero power of 2.
32849       // Todo(3): ROTL and ROTR patterns on a power of 2 C should also be
32850       // transformable to bittest.
32851       auto *ShiftVal = dyn_cast<ConstantInt>(I->getOperand(0));
32852       if (!ShiftVal)
32853         return {nullptr, UndefBit};
32854       if (ShiftVal->equalsInt(1))
32855         BTK = Not ? NotShiftBit : ShiftBit;
32856 
32857       if (BTK == UndefBit)
32858         return {nullptr, UndefBit};
32859 
32860       Value *BitV = I->getOperand(1);
32861 
32862       Value *AndOp;
32863       const APInt *AndC;
32864       if (match(BitV, m_c_And(m_Value(AndOp), m_APInt(AndC)))) {
32865         // Read past a shiftmask instruction to find count
32866         if (*AndC == (I->getType()->getPrimitiveSizeInBits() - 1))
32867           BitV = AndOp;
32868       }
32869       return {BitV, BTK};
32870     }
32871   }
32872   return {nullptr, UndefBit};
32873 }
32874 
32875 TargetLowering::AtomicExpansionKind
32876 X86TargetLowering::shouldExpandLogicAtomicRMWInIR(AtomicRMWInst *AI) const {
32877   using namespace llvm::PatternMatch;
32878   // If the atomicrmw's result isn't actually used, we can just add a "lock"
32879   // prefix to a normal instruction for these operations.
32880   if (AI->use_empty())
32881     return AtomicExpansionKind::None;
32882 
32883   if (AI->getOperation() == AtomicRMWInst::Xor) {
32884     // A ^ SignBit -> A + SignBit. This allows us to use `xadd` which is
32885     // preferable to both `cmpxchg` and `btc`.
32886     if (match(AI->getOperand(1), m_SignMask()))
32887       return AtomicExpansionKind::None;
32888   }
32889 
32890   // If the atomicrmw's result is used by a single bit AND, we may use
32891   // bts/btr/btc instruction for these operations.
32892   // Note: InstCombinePass can cause a de-optimization here. It replaces the
32893   // SETCC(And(AtomicRMW(P, power_of_2), power_of_2)) with LShr and Xor
32894   // (depending on CC). This pattern can only use bts/btr/btc but we don't
32895   // detect it.
32896   Instruction *I = AI->user_back();
32897   auto BitChange = FindSingleBitChange(AI->getValOperand());
32898   if (BitChange.second == UndefBit || !AI->hasOneUse() ||
32899       I->getOpcode() != Instruction::And ||
32900       AI->getType()->getPrimitiveSizeInBits() == 8 ||
32901       AI->getParent() != I->getParent())
32902     return AtomicExpansionKind::CmpXChg;
32903 
32904   unsigned OtherIdx = I->getOperand(0) == AI ? 1 : 0;
32905 
32906   // This is a redundant AND, it should get cleaned up elsewhere.
32907   if (AI == I->getOperand(OtherIdx))
32908     return AtomicExpansionKind::CmpXChg;
32909 
32910   // The following instruction must be a AND single bit.
32911   if (BitChange.second == ConstantBit || BitChange.second == NotConstantBit) {
32912     auto *C1 = cast<ConstantInt>(AI->getValOperand());
32913     auto *C2 = dyn_cast<ConstantInt>(I->getOperand(OtherIdx));
32914     if (!C2 || !isPowerOf2_64(C2->getZExtValue())) {
32915       return AtomicExpansionKind::CmpXChg;
32916     }
32917     if (AI->getOperation() == AtomicRMWInst::And) {
32918       return ~C1->getValue() == C2->getValue()
32919                  ? AtomicExpansionKind::BitTestIntrinsic
32920                  : AtomicExpansionKind::CmpXChg;
32921     }
32922     return C1 == C2 ? AtomicExpansionKind::BitTestIntrinsic
32923                     : AtomicExpansionKind::CmpXChg;
32924   }
32925 
32926   assert(BitChange.second == ShiftBit || BitChange.second == NotShiftBit);
32927 
32928   auto BitTested = FindSingleBitChange(I->getOperand(OtherIdx));
32929   if (BitTested.second != ShiftBit && BitTested.second != NotShiftBit)
32930     return AtomicExpansionKind::CmpXChg;
32931 
32932   assert(BitChange.first != nullptr && BitTested.first != nullptr);
32933 
32934   // If shift amounts are not the same we can't use BitTestIntrinsic.
32935   if (BitChange.first != BitTested.first)
32936     return AtomicExpansionKind::CmpXChg;
32937 
32938   // If atomic AND need to be masking all be one bit and testing the one bit
32939   // unset in the mask.
32940   if (AI->getOperation() == AtomicRMWInst::And)
32941     return (BitChange.second == NotShiftBit && BitTested.second == ShiftBit)
32942                ? AtomicExpansionKind::BitTestIntrinsic
32943                : AtomicExpansionKind::CmpXChg;
32944 
32945   // If atomic XOR/OR need to be setting and testing the same bit.
32946   return (BitChange.second == ShiftBit && BitTested.second == ShiftBit)
32947              ? AtomicExpansionKind::BitTestIntrinsic
32948              : AtomicExpansionKind::CmpXChg;
32949 }
32950 
32951 void X86TargetLowering::emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const {
32952   IRBuilder<> Builder(AI);
32953   Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
32954   Intrinsic::ID IID_C = Intrinsic::not_intrinsic;
32955   Intrinsic::ID IID_I = Intrinsic::not_intrinsic;
32956   switch (AI->getOperation()) {
32957   default:
32958     llvm_unreachable("Unknown atomic operation");
32959   case AtomicRMWInst::Or:
32960     IID_C = Intrinsic::x86_atomic_bts;
32961     IID_I = Intrinsic::x86_atomic_bts_rm;
32962     break;
32963   case AtomicRMWInst::Xor:
32964     IID_C = Intrinsic::x86_atomic_btc;
32965     IID_I = Intrinsic::x86_atomic_btc_rm;
32966     break;
32967   case AtomicRMWInst::And:
32968     IID_C = Intrinsic::x86_atomic_btr;
32969     IID_I = Intrinsic::x86_atomic_btr_rm;
32970     break;
32971   }
32972   Instruction *I = AI->user_back();
32973   LLVMContext &Ctx = AI->getContext();
32974   Value *Addr = Builder.CreatePointerCast(AI->getPointerOperand(),
32975                                           Type::getInt8PtrTy(Ctx));
32976   Function *BitTest = nullptr;
32977   Value *Result = nullptr;
32978   auto BitTested = FindSingleBitChange(AI->getValOperand());
32979   assert(BitTested.first != nullptr);
32980 
32981   if (BitTested.second == ConstantBit || BitTested.second == NotConstantBit) {
32982     auto *C = cast<ConstantInt>(I->getOperand(I->getOperand(0) == AI ? 1 : 0));
32983 
32984     BitTest = Intrinsic::getDeclaration(AI->getModule(), IID_C, AI->getType());
32985 
32986     unsigned Imm = llvm::countr_zero(C->getZExtValue());
32987     Result = Builder.CreateCall(BitTest, {Addr, Builder.getInt8(Imm)});
32988   } else {
32989     BitTest = Intrinsic::getDeclaration(AI->getModule(), IID_I, AI->getType());
32990 
32991     assert(BitTested.second == ShiftBit || BitTested.second == NotShiftBit);
32992 
32993     Value *SI = BitTested.first;
32994     assert(SI != nullptr);
32995 
32996     // BT{S|R|C} on memory operand don't modulo bit position so we need to
32997     // mask it.
32998     unsigned ShiftBits = SI->getType()->getPrimitiveSizeInBits();
32999     Value *BitPos =
33000         Builder.CreateAnd(SI, Builder.getIntN(ShiftBits, ShiftBits - 1));
33001     // Todo(1): In many cases it may be provable that SI is less than
33002     // ShiftBits in which case this mask is unnecessary
33003     // Todo(2): In the fairly idiomatic case of P[X / sizeof_bits(X)] OP 1
33004     // << (X % sizeof_bits(X)) we can drop the shift mask and AGEN in
33005     // favor of just a raw BT{S|R|C}.
33006 
33007     Result = Builder.CreateCall(BitTest, {Addr, BitPos});
33008     Result = Builder.CreateZExtOrTrunc(Result, AI->getType());
33009 
33010     // If the result is only used for zero/non-zero status then we don't need to
33011     // shift value back. Otherwise do so.
33012     for (auto It = I->user_begin(); It != I->user_end(); ++It) {
33013       if (auto *ICmp = dyn_cast<ICmpInst>(*It)) {
33014         if (ICmp->isEquality()) {
33015           auto *C0 = dyn_cast<ConstantInt>(ICmp->getOperand(0));
33016           auto *C1 = dyn_cast<ConstantInt>(ICmp->getOperand(1));
33017           if (C0 || C1) {
33018             assert(C0 == nullptr || C1 == nullptr);
33019             if ((C0 ? C0 : C1)->isZero())
33020               continue;
33021           }
33022         }
33023       }
33024       Result = Builder.CreateShl(Result, BitPos);
33025       break;
33026     }
33027   }
33028 
33029   I->replaceAllUsesWith(Result);
33030   I->eraseFromParent();
33031   AI->eraseFromParent();
33032 }
33033 
33034 static bool shouldExpandCmpArithRMWInIR(AtomicRMWInst *AI) {
33035   using namespace llvm::PatternMatch;
33036   if (!AI->hasOneUse())
33037     return false;
33038 
33039   Value *Op = AI->getOperand(1);
33040   ICmpInst::Predicate Pred;
33041   Instruction *I = AI->user_back();
33042   AtomicRMWInst::BinOp Opc = AI->getOperation();
33043   if (Opc == AtomicRMWInst::Add) {
33044     if (match(I, m_c_ICmp(Pred, m_Sub(m_ZeroInt(), m_Specific(Op)), m_Value())))
33045       return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
33046     if (match(I, m_OneUse(m_c_Add(m_Specific(Op), m_Value())))) {
33047       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
33048         return Pred == CmpInst::ICMP_SLT;
33049       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_AllOnes())))
33050         return Pred == CmpInst::ICMP_SGT;
33051     }
33052     return false;
33053   }
33054   if (Opc == AtomicRMWInst::Sub) {
33055     if (match(I, m_c_ICmp(Pred, m_Specific(Op), m_Value())))
33056       return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
33057     if (match(I, m_OneUse(m_Sub(m_Value(), m_Specific(Op))))) {
33058       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
33059         return Pred == CmpInst::ICMP_SLT;
33060       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_AllOnes())))
33061         return Pred == CmpInst::ICMP_SGT;
33062     }
33063     return false;
33064   }
33065   if ((Opc == AtomicRMWInst::Or &&
33066        match(I, m_OneUse(m_c_Or(m_Specific(Op), m_Value())))) ||
33067       (Opc == AtomicRMWInst::And &&
33068        match(I, m_OneUse(m_c_And(m_Specific(Op), m_Value()))))) {
33069     if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
33070       return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE ||
33071              Pred == CmpInst::ICMP_SLT;
33072     if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_AllOnes())))
33073       return Pred == CmpInst::ICMP_SGT;
33074     return false;
33075   }
33076   if (Opc == AtomicRMWInst::Xor) {
33077     if (match(I, m_c_ICmp(Pred, m_Specific(Op), m_Value())))
33078       return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
33079     if (match(I, m_OneUse(m_c_Xor(m_Specific(Op), m_Value())))) {
33080       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
33081         return Pred == CmpInst::ICMP_SLT;
33082       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_AllOnes())))
33083         return Pred == CmpInst::ICMP_SGT;
33084     }
33085     return false;
33086   }
33087 
33088   return false;
33089 }
33090 
33091 void X86TargetLowering::emitCmpArithAtomicRMWIntrinsic(
33092     AtomicRMWInst *AI) const {
33093   IRBuilder<> Builder(AI);
33094   Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
33095   Instruction *TempI = nullptr;
33096   LLVMContext &Ctx = AI->getContext();
33097   ICmpInst *ICI = dyn_cast<ICmpInst>(AI->user_back());
33098   if (!ICI) {
33099     TempI = AI->user_back();
33100     assert(TempI->hasOneUse() && "Must have one use");
33101     ICI = cast<ICmpInst>(TempI->user_back());
33102   }
33103   X86::CondCode CC = X86::COND_INVALID;
33104   ICmpInst::Predicate Pred = ICI->getPredicate();
33105   switch (Pred) {
33106   default:
33107     llvm_unreachable("Not supported Pred");
33108   case CmpInst::ICMP_EQ:
33109     CC = X86::COND_E;
33110     break;
33111   case CmpInst::ICMP_NE:
33112     CC = X86::COND_NE;
33113     break;
33114   case CmpInst::ICMP_SLT:
33115     CC = X86::COND_S;
33116     break;
33117   case CmpInst::ICMP_SGT:
33118     CC = X86::COND_NS;
33119     break;
33120   }
33121   Intrinsic::ID IID = Intrinsic::not_intrinsic;
33122   switch (AI->getOperation()) {
33123   default:
33124     llvm_unreachable("Unknown atomic operation");
33125   case AtomicRMWInst::Add:
33126     IID = Intrinsic::x86_atomic_add_cc;
33127     break;
33128   case AtomicRMWInst::Sub:
33129     IID = Intrinsic::x86_atomic_sub_cc;
33130     break;
33131   case AtomicRMWInst::Or:
33132     IID = Intrinsic::x86_atomic_or_cc;
33133     break;
33134   case AtomicRMWInst::And:
33135     IID = Intrinsic::x86_atomic_and_cc;
33136     break;
33137   case AtomicRMWInst::Xor:
33138     IID = Intrinsic::x86_atomic_xor_cc;
33139     break;
33140   }
33141   Function *CmpArith =
33142       Intrinsic::getDeclaration(AI->getModule(), IID, AI->getType());
33143   Value *Addr = Builder.CreatePointerCast(AI->getPointerOperand(),
33144                                           Type::getInt8PtrTy(Ctx));
33145   Value *Call = Builder.CreateCall(
33146       CmpArith, {Addr, AI->getValOperand(), Builder.getInt32((unsigned)CC)});
33147   Value *Result = Builder.CreateTrunc(Call, Type::getInt1Ty(Ctx));
33148   ICI->replaceAllUsesWith(Result);
33149   ICI->eraseFromParent();
33150   if (TempI)
33151     TempI->eraseFromParent();
33152   AI->eraseFromParent();
33153 }
33154 
33155 TargetLowering::AtomicExpansionKind
33156 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
33157   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
33158   Type *MemType = AI->getType();
33159 
33160   // If the operand is too big, we must see if cmpxchg8/16b is available
33161   // and default to library calls otherwise.
33162   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
33163     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
33164                                    : AtomicExpansionKind::None;
33165   }
33166 
33167   AtomicRMWInst::BinOp Op = AI->getOperation();
33168   switch (Op) {
33169   case AtomicRMWInst::Xchg:
33170     return AtomicExpansionKind::None;
33171   case AtomicRMWInst::Add:
33172   case AtomicRMWInst::Sub:
33173     if (shouldExpandCmpArithRMWInIR(AI))
33174       return AtomicExpansionKind::CmpArithIntrinsic;
33175     // It's better to use xadd, xsub or xchg for these in other cases.
33176     return AtomicExpansionKind::None;
33177   case AtomicRMWInst::Or:
33178   case AtomicRMWInst::And:
33179   case AtomicRMWInst::Xor:
33180     if (shouldExpandCmpArithRMWInIR(AI))
33181       return AtomicExpansionKind::CmpArithIntrinsic;
33182     return shouldExpandLogicAtomicRMWInIR(AI);
33183   case AtomicRMWInst::Nand:
33184   case AtomicRMWInst::Max:
33185   case AtomicRMWInst::Min:
33186   case AtomicRMWInst::UMax:
33187   case AtomicRMWInst::UMin:
33188   case AtomicRMWInst::FAdd:
33189   case AtomicRMWInst::FSub:
33190   case AtomicRMWInst::FMax:
33191   case AtomicRMWInst::FMin:
33192   case AtomicRMWInst::UIncWrap:
33193   case AtomicRMWInst::UDecWrap:
33194   default:
33195     // These always require a non-trivial set of data operations on x86. We must
33196     // use a cmpxchg loop.
33197     return AtomicExpansionKind::CmpXChg;
33198   }
33199 }
33200 
33201 LoadInst *
33202 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
33203   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
33204   Type *MemType = AI->getType();
33205   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
33206   // there is no benefit in turning such RMWs into loads, and it is actually
33207   // harmful as it introduces a mfence.
33208   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
33209     return nullptr;
33210 
33211   // If this is a canonical idempotent atomicrmw w/no uses, we have a better
33212   // lowering available in lowerAtomicArith.
33213   // TODO: push more cases through this path.
33214   if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
33215     if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
33216         AI->use_empty())
33217       return nullptr;
33218 
33219   IRBuilder<> Builder(AI);
33220   Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
33221   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
33222   auto SSID = AI->getSyncScopeID();
33223   // We must restrict the ordering to avoid generating loads with Release or
33224   // ReleaseAcquire orderings.
33225   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
33226 
33227   // Before the load we need a fence. Here is an example lifted from
33228   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
33229   // is required:
33230   // Thread 0:
33231   //   x.store(1, relaxed);
33232   //   r1 = y.fetch_add(0, release);
33233   // Thread 1:
33234   //   y.fetch_add(42, acquire);
33235   //   r2 = x.load(relaxed);
33236   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
33237   // lowered to just a load without a fence. A mfence flushes the store buffer,
33238   // making the optimization clearly correct.
33239   // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
33240   // otherwise, we might be able to be more aggressive on relaxed idempotent
33241   // rmw. In practice, they do not look useful, so we don't try to be
33242   // especially clever.
33243   if (SSID == SyncScope::SingleThread)
33244     // FIXME: we could just insert an ISD::MEMBARRIER here, except we are at
33245     // the IR level, so we must wrap it in an intrinsic.
33246     return nullptr;
33247 
33248   if (!Subtarget.hasMFence())
33249     // FIXME: it might make sense to use a locked operation here but on a
33250     // different cache-line to prevent cache-line bouncing. In practice it
33251     // is probably a small win, and x86 processors without mfence are rare
33252     // enough that we do not bother.
33253     return nullptr;
33254 
33255   Function *MFence =
33256       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
33257   Builder.CreateCall(MFence, {});
33258 
33259   // Finally we can emit the atomic load.
33260   LoadInst *Loaded = Builder.CreateAlignedLoad(
33261       AI->getType(), AI->getPointerOperand(), AI->getAlign());
33262   Loaded->setAtomic(Order, SSID);
33263   AI->replaceAllUsesWith(Loaded);
33264   AI->eraseFromParent();
33265   return Loaded;
33266 }
33267 
33268 bool X86TargetLowering::lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
33269   if (!SI.isUnordered())
33270     return false;
33271   return ExperimentalUnorderedISEL;
33272 }
33273 bool X86TargetLowering::lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
33274   if (!LI.isUnordered())
33275     return false;
33276   return ExperimentalUnorderedISEL;
33277 }
33278 
33279 
33280 /// Emit a locked operation on a stack location which does not change any
33281 /// memory location, but does involve a lock prefix.  Location is chosen to be
33282 /// a) very likely accessed only by a single thread to minimize cache traffic,
33283 /// and b) definitely dereferenceable.  Returns the new Chain result.
33284 static SDValue emitLockedStackOp(SelectionDAG &DAG,
33285                                  const X86Subtarget &Subtarget, SDValue Chain,
33286                                  const SDLoc &DL) {
33287   // Implementation notes:
33288   // 1) LOCK prefix creates a full read/write reordering barrier for memory
33289   // operations issued by the current processor.  As such, the location
33290   // referenced is not relevant for the ordering properties of the instruction.
33291   // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
33292   // 8.2.3.9  Loads and Stores Are Not Reordered with Locked Instructions
33293   // 2) Using an immediate operand appears to be the best encoding choice
33294   // here since it doesn't require an extra register.
33295   // 3) OR appears to be very slightly faster than ADD. (Though, the difference
33296   // is small enough it might just be measurement noise.)
33297   // 4) When choosing offsets, there are several contributing factors:
33298   //   a) If there's no redzone, we default to TOS.  (We could allocate a cache
33299   //      line aligned stack object to improve this case.)
33300   //   b) To minimize our chances of introducing a false dependence, we prefer
33301   //      to offset the stack usage from TOS slightly.
33302   //   c) To minimize concerns about cross thread stack usage - in particular,
33303   //      the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
33304   //      captures state in the TOS frame and accesses it from many threads -
33305   //      we want to use an offset such that the offset is in a distinct cache
33306   //      line from the TOS frame.
33307   //
33308   // For a general discussion of the tradeoffs and benchmark results, see:
33309   // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
33310 
33311   auto &MF = DAG.getMachineFunction();
33312   auto &TFL = *Subtarget.getFrameLowering();
33313   const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
33314 
33315   if (Subtarget.is64Bit()) {
33316     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
33317     SDValue Ops[] = {
33318       DAG.getRegister(X86::RSP, MVT::i64),                  // Base
33319       DAG.getTargetConstant(1, DL, MVT::i8),                // Scale
33320       DAG.getRegister(0, MVT::i64),                         // Index
33321       DAG.getTargetConstant(SPOffset, DL, MVT::i32),        // Disp
33322       DAG.getRegister(0, MVT::i16),                         // Segment.
33323       Zero,
33324       Chain};
33325     SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
33326                                      MVT::Other, Ops);
33327     return SDValue(Res, 1);
33328   }
33329 
33330   SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
33331   SDValue Ops[] = {
33332     DAG.getRegister(X86::ESP, MVT::i32),            // Base
33333     DAG.getTargetConstant(1, DL, MVT::i8),          // Scale
33334     DAG.getRegister(0, MVT::i32),                   // Index
33335     DAG.getTargetConstant(SPOffset, DL, MVT::i32),  // Disp
33336     DAG.getRegister(0, MVT::i16),                   // Segment.
33337     Zero,
33338     Chain
33339   };
33340   SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
33341                                    MVT::Other, Ops);
33342   return SDValue(Res, 1);
33343 }
33344 
33345 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
33346                                  SelectionDAG &DAG) {
33347   SDLoc dl(Op);
33348   AtomicOrdering FenceOrdering =
33349       static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
33350   SyncScope::ID FenceSSID =
33351       static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
33352 
33353   // The only fence that needs an instruction is a sequentially-consistent
33354   // cross-thread fence.
33355   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
33356       FenceSSID == SyncScope::System) {
33357     if (Subtarget.hasMFence())
33358       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
33359 
33360     SDValue Chain = Op.getOperand(0);
33361     return emitLockedStackOp(DAG, Subtarget, Chain, dl);
33362   }
33363 
33364   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
33365   return DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
33366 }
33367 
33368 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
33369                              SelectionDAG &DAG) {
33370   MVT T = Op.getSimpleValueType();
33371   SDLoc DL(Op);
33372   unsigned Reg = 0;
33373   unsigned size = 0;
33374   switch(T.SimpleTy) {
33375   default: llvm_unreachable("Invalid value type!");
33376   case MVT::i8:  Reg = X86::AL;  size = 1; break;
33377   case MVT::i16: Reg = X86::AX;  size = 2; break;
33378   case MVT::i32: Reg = X86::EAX; size = 4; break;
33379   case MVT::i64:
33380     assert(Subtarget.is64Bit() && "Node not type legal!");
33381     Reg = X86::RAX; size = 8;
33382     break;
33383   }
33384   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
33385                                   Op.getOperand(2), SDValue());
33386   SDValue Ops[] = { cpIn.getValue(0),
33387                     Op.getOperand(1),
33388                     Op.getOperand(3),
33389                     DAG.getTargetConstant(size, DL, MVT::i8),
33390                     cpIn.getValue(1) };
33391   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
33392   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
33393   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
33394                                            Ops, T, MMO);
33395 
33396   SDValue cpOut =
33397     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
33398   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
33399                                       MVT::i32, cpOut.getValue(2));
33400   SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
33401 
33402   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
33403                      cpOut, Success, EFLAGS.getValue(1));
33404 }
33405 
33406 // Create MOVMSKB, taking into account whether we need to split for AVX1.
33407 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
33408                            const X86Subtarget &Subtarget) {
33409   MVT InVT = V.getSimpleValueType();
33410 
33411   if (InVT == MVT::v64i8) {
33412     SDValue Lo, Hi;
33413     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
33414     Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
33415     Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
33416     Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
33417     Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
33418     Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
33419                      DAG.getConstant(32, DL, MVT::i8));
33420     return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
33421   }
33422   if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
33423     SDValue Lo, Hi;
33424     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
33425     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
33426     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
33427     Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
33428                      DAG.getConstant(16, DL, MVT::i8));
33429     return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
33430   }
33431 
33432   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
33433 }
33434 
33435 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
33436                             SelectionDAG &DAG) {
33437   SDValue Src = Op.getOperand(0);
33438   MVT SrcVT = Src.getSimpleValueType();
33439   MVT DstVT = Op.getSimpleValueType();
33440 
33441   // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
33442   // half to v32i1 and concatenating the result.
33443   if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
33444     assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
33445     assert(Subtarget.hasBWI() && "Expected BWI target");
33446     SDLoc dl(Op);
33447     SDValue Lo, Hi;
33448     std::tie(Lo, Hi) = DAG.SplitScalar(Src, dl, MVT::i32, MVT::i32);
33449     Lo = DAG.getBitcast(MVT::v32i1, Lo);
33450     Hi = DAG.getBitcast(MVT::v32i1, Hi);
33451     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
33452   }
33453 
33454   // Use MOVMSK for vector to scalar conversion to prevent scalarization.
33455   if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
33456     assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
33457     MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
33458     SDLoc DL(Op);
33459     SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
33460     V = getPMOVMSKB(DL, V, DAG, Subtarget);
33461     return DAG.getZExtOrTrunc(V, DL, DstVT);
33462   }
33463 
33464   assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
33465           SrcVT == MVT::i64) && "Unexpected VT!");
33466 
33467   assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
33468   if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
33469       !(DstVT == MVT::x86mmx && SrcVT.isVector()))
33470     // This conversion needs to be expanded.
33471     return SDValue();
33472 
33473   SDLoc dl(Op);
33474   if (SrcVT.isVector()) {
33475     // Widen the vector in input in the case of MVT::v2i32.
33476     // Example: from MVT::v2i32 to MVT::v4i32.
33477     MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
33478                                  SrcVT.getVectorNumElements() * 2);
33479     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
33480                       DAG.getUNDEF(SrcVT));
33481   } else {
33482     assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
33483            "Unexpected source type in LowerBITCAST");
33484     Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
33485   }
33486 
33487   MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
33488   Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
33489 
33490   if (DstVT == MVT::x86mmx)
33491     return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
33492 
33493   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
33494                      DAG.getIntPtrConstant(0, dl));
33495 }
33496 
33497 /// Compute the horizontal sum of bytes in V for the elements of VT.
33498 ///
33499 /// Requires V to be a byte vector and VT to be an integer vector type with
33500 /// wider elements than V's type. The width of the elements of VT determines
33501 /// how many bytes of V are summed horizontally to produce each element of the
33502 /// result.
33503 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
33504                                       const X86Subtarget &Subtarget,
33505                                       SelectionDAG &DAG) {
33506   SDLoc DL(V);
33507   MVT ByteVecVT = V.getSimpleValueType();
33508   MVT EltVT = VT.getVectorElementType();
33509   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
33510          "Expected value to have byte element type.");
33511   assert(EltVT != MVT::i8 &&
33512          "Horizontal byte sum only makes sense for wider elements!");
33513   unsigned VecSize = VT.getSizeInBits();
33514   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
33515 
33516   // PSADBW instruction horizontally add all bytes and leave the result in i64
33517   // chunks, thus directly computes the pop count for v2i64 and v4i64.
33518   if (EltVT == MVT::i64) {
33519     SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
33520     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
33521     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
33522     return DAG.getBitcast(VT, V);
33523   }
33524 
33525   if (EltVT == MVT::i32) {
33526     // We unpack the low half and high half into i32s interleaved with zeros so
33527     // that we can use PSADBW to horizontally sum them. The most useful part of
33528     // this is that it lines up the results of two PSADBW instructions to be
33529     // two v2i64 vectors which concatenated are the 4 population counts. We can
33530     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
33531     SDValue Zeros = DAG.getConstant(0, DL, VT);
33532     SDValue V32 = DAG.getBitcast(VT, V);
33533     SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
33534     SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
33535 
33536     // Do the horizontal sums into two v2i64s.
33537     Zeros = DAG.getConstant(0, DL, ByteVecVT);
33538     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
33539     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
33540                       DAG.getBitcast(ByteVecVT, Low), Zeros);
33541     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
33542                        DAG.getBitcast(ByteVecVT, High), Zeros);
33543 
33544     // Merge them together.
33545     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
33546     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
33547                     DAG.getBitcast(ShortVecVT, Low),
33548                     DAG.getBitcast(ShortVecVT, High));
33549 
33550     return DAG.getBitcast(VT, V);
33551   }
33552 
33553   // The only element type left is i16.
33554   assert(EltVT == MVT::i16 && "Unknown how to handle type");
33555 
33556   // To obtain pop count for each i16 element starting from the pop count for
33557   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
33558   // right by 8. It is important to shift as i16s as i8 vector shift isn't
33559   // directly supported.
33560   SDValue ShifterV = DAG.getConstant(8, DL, VT);
33561   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
33562   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
33563                   DAG.getBitcast(ByteVecVT, V));
33564   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
33565 }
33566 
33567 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
33568                                         const X86Subtarget &Subtarget,
33569                                         SelectionDAG &DAG) {
33570   MVT VT = Op.getSimpleValueType();
33571   MVT EltVT = VT.getVectorElementType();
33572   int NumElts = VT.getVectorNumElements();
33573   (void)EltVT;
33574   assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
33575 
33576   // Implement a lookup table in register by using an algorithm based on:
33577   // http://wm.ite.pl/articles/sse-popcount.html
33578   //
33579   // The general idea is that every lower byte nibble in the input vector is an
33580   // index into a in-register pre-computed pop count table. We then split up the
33581   // input vector in two new ones: (1) a vector with only the shifted-right
33582   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
33583   // masked out higher ones) for each byte. PSHUFB is used separately with both
33584   // to index the in-register table. Next, both are added and the result is a
33585   // i8 vector where each element contains the pop count for input byte.
33586   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
33587                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
33588                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
33589                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
33590 
33591   SmallVector<SDValue, 64> LUTVec;
33592   for (int i = 0; i < NumElts; ++i)
33593     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
33594   SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
33595   SDValue M0F = DAG.getConstant(0x0F, DL, VT);
33596 
33597   // High nibbles
33598   SDValue FourV = DAG.getConstant(4, DL, VT);
33599   SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
33600 
33601   // Low nibbles
33602   SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
33603 
33604   // The input vector is used as the shuffle mask that index elements into the
33605   // LUT. After counting low and high nibbles, add the vector to obtain the
33606   // final pop count per i8 element.
33607   SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
33608   SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
33609   return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
33610 }
33611 
33612 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
33613 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
33614 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
33615                                 SelectionDAG &DAG) {
33616   MVT VT = Op.getSimpleValueType();
33617   assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
33618          "Unknown CTPOP type to handle");
33619   SDLoc DL(Op.getNode());
33620   SDValue Op0 = Op.getOperand(0);
33621 
33622   // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
33623   if (Subtarget.hasVPOPCNTDQ()) {
33624     unsigned NumElems = VT.getVectorNumElements();
33625     assert((VT.getVectorElementType() == MVT::i8 ||
33626             VT.getVectorElementType() == MVT::i16) && "Unexpected type");
33627     if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
33628       MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
33629       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
33630       Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
33631       return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
33632     }
33633   }
33634 
33635   // Decompose 256-bit ops into smaller 128-bit ops.
33636   if (VT.is256BitVector() && !Subtarget.hasInt256())
33637     return splitVectorIntUnary(Op, DAG);
33638 
33639   // Decompose 512-bit ops into smaller 256-bit ops.
33640   if (VT.is512BitVector() && !Subtarget.hasBWI())
33641     return splitVectorIntUnary(Op, DAG);
33642 
33643   // For element types greater than i8, do vXi8 pop counts and a bytesum.
33644   if (VT.getScalarType() != MVT::i8) {
33645     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
33646     SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
33647     SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
33648     return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
33649   }
33650 
33651   // We can't use the fast LUT approach, so fall back on LegalizeDAG.
33652   if (!Subtarget.hasSSSE3())
33653     return SDValue();
33654 
33655   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
33656 }
33657 
33658 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
33659                           SelectionDAG &DAG) {
33660   assert(Op.getSimpleValueType().isVector() &&
33661          "We only do custom lowering for vector population count.");
33662   return LowerVectorCTPOP(Op, Subtarget, DAG);
33663 }
33664 
33665 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
33666   MVT VT = Op.getSimpleValueType();
33667   SDValue In = Op.getOperand(0);
33668   SDLoc DL(Op);
33669 
33670   // For scalars, its still beneficial to transfer to/from the SIMD unit to
33671   // perform the BITREVERSE.
33672   if (!VT.isVector()) {
33673     MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
33674     SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
33675     Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
33676     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
33677                        DAG.getIntPtrConstant(0, DL));
33678   }
33679 
33680   int NumElts = VT.getVectorNumElements();
33681   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
33682 
33683   // Decompose 256-bit ops into smaller 128-bit ops.
33684   if (VT.is256BitVector())
33685     return splitVectorIntUnary(Op, DAG);
33686 
33687   assert(VT.is128BitVector() &&
33688          "Only 128-bit vector bitreverse lowering supported.");
33689 
33690   // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
33691   // perform the BSWAP in the shuffle.
33692   // Its best to shuffle using the second operand as this will implicitly allow
33693   // memory folding for multiple vectors.
33694   SmallVector<SDValue, 16> MaskElts;
33695   for (int i = 0; i != NumElts; ++i) {
33696     for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
33697       int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
33698       int PermuteByte = SourceByte | (2 << 5);
33699       MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
33700     }
33701   }
33702 
33703   SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
33704   SDValue Res = DAG.getBitcast(MVT::v16i8, In);
33705   Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
33706                     Res, Mask);
33707   return DAG.getBitcast(VT, Res);
33708 }
33709 
33710 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
33711                                SelectionDAG &DAG) {
33712   MVT VT = Op.getSimpleValueType();
33713 
33714   if (Subtarget.hasXOP() && !VT.is512BitVector())
33715     return LowerBITREVERSE_XOP(Op, DAG);
33716 
33717   assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
33718 
33719   SDValue In = Op.getOperand(0);
33720   SDLoc DL(Op);
33721 
33722   assert(VT.getScalarType() == MVT::i8 &&
33723          "Only byte vector BITREVERSE supported");
33724 
33725   // Split v64i8 without BWI so that we can still use the PSHUFB lowering.
33726   if (VT == MVT::v64i8 && !Subtarget.hasBWI())
33727     return splitVectorIntUnary(Op, DAG);
33728 
33729   // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
33730   if (VT == MVT::v32i8 && !Subtarget.hasInt256())
33731     return splitVectorIntUnary(Op, DAG);
33732 
33733   unsigned NumElts = VT.getVectorNumElements();
33734 
33735   // If we have GFNI, we can use GF2P8AFFINEQB to reverse the bits.
33736   if (Subtarget.hasGFNI()) {
33737     MVT MatrixVT = MVT::getVectorVT(MVT::i64, NumElts / 8);
33738     SDValue Matrix = DAG.getConstant(0x8040201008040201ULL, DL, MatrixVT);
33739     Matrix = DAG.getBitcast(VT, Matrix);
33740     return DAG.getNode(X86ISD::GF2P8AFFINEQB, DL, VT, In, Matrix,
33741                        DAG.getTargetConstant(0, DL, MVT::i8));
33742   }
33743 
33744   // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
33745   // two nibbles and a PSHUFB lookup to find the bitreverse of each
33746   // 0-15 value (moved to the other nibble).
33747   SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
33748   SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
33749   SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
33750 
33751   const int LoLUT[16] = {
33752       /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
33753       /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
33754       /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
33755       /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
33756   const int HiLUT[16] = {
33757       /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
33758       /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
33759       /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
33760       /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
33761 
33762   SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
33763   for (unsigned i = 0; i < NumElts; ++i) {
33764     LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
33765     HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
33766   }
33767 
33768   SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
33769   SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
33770   Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
33771   Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
33772   return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
33773 }
33774 
33775 static SDValue LowerPARITY(SDValue Op, const X86Subtarget &Subtarget,
33776                            SelectionDAG &DAG) {
33777   SDLoc DL(Op);
33778   SDValue X = Op.getOperand(0);
33779   MVT VT = Op.getSimpleValueType();
33780 
33781   // Special case. If the input fits in 8-bits we can use a single 8-bit TEST.
33782   if (VT == MVT::i8 ||
33783       DAG.MaskedValueIsZero(X, APInt::getBitsSetFrom(VT.getSizeInBits(), 8))) {
33784     X = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
33785     SDValue Flags = DAG.getNode(X86ISD::CMP, DL, MVT::i32, X,
33786                                 DAG.getConstant(0, DL, MVT::i8));
33787     // Copy the inverse of the parity flag into a register with setcc.
33788     SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
33789     // Extend to the original type.
33790     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
33791   }
33792 
33793   // If we have POPCNT, use the default expansion.
33794   if (Subtarget.hasPOPCNT())
33795     return SDValue();
33796 
33797   if (VT == MVT::i64) {
33798     // Xor the high and low 16-bits together using a 32-bit operation.
33799     SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
33800                              DAG.getNode(ISD::SRL, DL, MVT::i64, X,
33801                                          DAG.getConstant(32, DL, MVT::i8)));
33802     SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
33803     X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
33804   }
33805 
33806   if (VT != MVT::i16) {
33807     // Xor the high and low 16-bits together using a 32-bit operation.
33808     SDValue Hi16 = DAG.getNode(ISD::SRL, DL, MVT::i32, X,
33809                                DAG.getConstant(16, DL, MVT::i8));
33810     X = DAG.getNode(ISD::XOR, DL, MVT::i32, X, Hi16);
33811   } else {
33812     // If the input is 16-bits, we need to extend to use an i32 shift below.
33813     X = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, X);
33814   }
33815 
33816   // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
33817   // This should allow an h-reg to be used to save a shift.
33818   SDValue Hi = DAG.getNode(
33819       ISD::TRUNCATE, DL, MVT::i8,
33820       DAG.getNode(ISD::SRL, DL, MVT::i32, X, DAG.getConstant(8, DL, MVT::i8)));
33821   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
33822   SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
33823   SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
33824 
33825   // Copy the inverse of the parity flag into a register with setcc.
33826   SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
33827   // Extend to the original type.
33828   return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
33829 }
33830 
33831 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
33832                                         const X86Subtarget &Subtarget) {
33833   unsigned NewOpc = 0;
33834   switch (N->getOpcode()) {
33835   case ISD::ATOMIC_LOAD_ADD:
33836     NewOpc = X86ISD::LADD;
33837     break;
33838   case ISD::ATOMIC_LOAD_SUB:
33839     NewOpc = X86ISD::LSUB;
33840     break;
33841   case ISD::ATOMIC_LOAD_OR:
33842     NewOpc = X86ISD::LOR;
33843     break;
33844   case ISD::ATOMIC_LOAD_XOR:
33845     NewOpc = X86ISD::LXOR;
33846     break;
33847   case ISD::ATOMIC_LOAD_AND:
33848     NewOpc = X86ISD::LAND;
33849     break;
33850   default:
33851     llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
33852   }
33853 
33854   MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
33855 
33856   return DAG.getMemIntrinsicNode(
33857       NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
33858       {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
33859       /*MemVT=*/N->getSimpleValueType(0), MMO);
33860 }
33861 
33862 /// Lower atomic_load_ops into LOCK-prefixed operations.
33863 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
33864                                 const X86Subtarget &Subtarget) {
33865   AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
33866   SDValue Chain = N->getOperand(0);
33867   SDValue LHS = N->getOperand(1);
33868   SDValue RHS = N->getOperand(2);
33869   unsigned Opc = N->getOpcode();
33870   MVT VT = N->getSimpleValueType(0);
33871   SDLoc DL(N);
33872 
33873   // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
33874   // can only be lowered when the result is unused.  They should have already
33875   // been transformed into a cmpxchg loop in AtomicExpand.
33876   if (N->hasAnyUseOfValue(0)) {
33877     // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
33878     // select LXADD if LOCK_SUB can't be selected.
33879     // Handle (atomic_load_xor p, SignBit) as (atomic_load_add p, SignBit) so we
33880     // can use LXADD as opposed to cmpxchg.
33881     if (Opc == ISD::ATOMIC_LOAD_SUB ||
33882         (Opc == ISD::ATOMIC_LOAD_XOR && isMinSignedConstant(RHS))) {
33883       RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
33884       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS, RHS,
33885                            AN->getMemOperand());
33886     }
33887     assert(Opc == ISD::ATOMIC_LOAD_ADD &&
33888            "Used AtomicRMW ops other than Add should have been expanded!");
33889     return N;
33890   }
33891 
33892   // Specialized lowering for the canonical form of an idemptotent atomicrmw.
33893   // The core idea here is that since the memory location isn't actually
33894   // changing, all we need is a lowering for the *ordering* impacts of the
33895   // atomicrmw.  As such, we can chose a different operation and memory
33896   // location to minimize impact on other code.
33897   // The above holds unless the node is marked volatile in which
33898   // case it needs to be preserved according to the langref.
33899   if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS) && !AN->isVolatile()) {
33900     // On X86, the only ordering which actually requires an instruction is
33901     // seq_cst which isn't SingleThread, everything just needs to be preserved
33902     // during codegen and then dropped. Note that we expect (but don't assume),
33903     // that orderings other than seq_cst and acq_rel have been canonicalized to
33904     // a store or load.
33905     if (AN->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent &&
33906         AN->getSyncScopeID() == SyncScope::System) {
33907       // Prefer a locked operation against a stack location to minimize cache
33908       // traffic.  This assumes that stack locations are very likely to be
33909       // accessed only by the owning thread.
33910       SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
33911       assert(!N->hasAnyUseOfValue(0));
33912       // NOTE: The getUNDEF is needed to give something for the unused result 0.
33913       return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
33914                          DAG.getUNDEF(VT), NewChain);
33915     }
33916     // MEMBARRIER is a compiler barrier; it codegens to a no-op.
33917     SDValue NewChain = DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Chain);
33918     assert(!N->hasAnyUseOfValue(0));
33919     // NOTE: The getUNDEF is needed to give something for the unused result 0.
33920     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
33921                        DAG.getUNDEF(VT), NewChain);
33922   }
33923 
33924   SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
33925   // RAUW the chain, but don't worry about the result, as it's unused.
33926   assert(!N->hasAnyUseOfValue(0));
33927   // NOTE: The getUNDEF is needed to give something for the unused result 0.
33928   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
33929                      DAG.getUNDEF(VT), LockOp.getValue(1));
33930 }
33931 
33932 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
33933                                  const X86Subtarget &Subtarget) {
33934   auto *Node = cast<AtomicSDNode>(Op.getNode());
33935   SDLoc dl(Node);
33936   EVT VT = Node->getMemoryVT();
33937 
33938   bool IsSeqCst =
33939       Node->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent;
33940   bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
33941 
33942   // If this store is not sequentially consistent and the type is legal
33943   // we can just keep it.
33944   if (!IsSeqCst && IsTypeLegal)
33945     return Op;
33946 
33947   if (VT == MVT::i64 && !IsTypeLegal) {
33948     // For illegal i64 atomic_stores, we can try to use MOVQ or MOVLPS if SSE
33949     // is enabled.
33950     bool NoImplicitFloatOps =
33951         DAG.getMachineFunction().getFunction().hasFnAttribute(
33952             Attribute::NoImplicitFloat);
33953     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
33954       SDValue Chain;
33955       if (Subtarget.hasSSE1()) {
33956         SDValue SclToVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
33957                                        Node->getOperand(2));
33958         MVT StVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
33959         SclToVec = DAG.getBitcast(StVT, SclToVec);
33960         SDVTList Tys = DAG.getVTList(MVT::Other);
33961         SDValue Ops[] = {Node->getChain(), SclToVec, Node->getBasePtr()};
33962         Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops,
33963                                         MVT::i64, Node->getMemOperand());
33964       } else if (Subtarget.hasX87()) {
33965         // First load this into an 80-bit X87 register using a stack temporary.
33966         // This will put the whole integer into the significand.
33967         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
33968         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
33969         MachinePointerInfo MPI =
33970             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
33971         Chain =
33972             DAG.getStore(Node->getChain(), dl, Node->getOperand(2), StackPtr,
33973                          MPI, MaybeAlign(), MachineMemOperand::MOStore);
33974         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
33975         SDValue LdOps[] = {Chain, StackPtr};
33976         SDValue Value = DAG.getMemIntrinsicNode(
33977             X86ISD::FILD, dl, Tys, LdOps, MVT::i64, MPI,
33978             /*Align*/ std::nullopt, MachineMemOperand::MOLoad);
33979         Chain = Value.getValue(1);
33980 
33981         // Now use an FIST to do the atomic store.
33982         SDValue StoreOps[] = {Chain, Value, Node->getBasePtr()};
33983         Chain =
33984             DAG.getMemIntrinsicNode(X86ISD::FIST, dl, DAG.getVTList(MVT::Other),
33985                                     StoreOps, MVT::i64, Node->getMemOperand());
33986       }
33987 
33988       if (Chain) {
33989         // If this is a sequentially consistent store, also emit an appropriate
33990         // barrier.
33991         if (IsSeqCst)
33992           Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
33993 
33994         return Chain;
33995       }
33996     }
33997   }
33998 
33999   // Convert seq_cst store -> xchg
34000   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
34001   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
34002   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
34003                                Node->getMemoryVT(),
34004                                Node->getOperand(0),
34005                                Node->getOperand(1), Node->getOperand(2),
34006                                Node->getMemOperand());
34007   return Swap.getValue(1);
34008 }
34009 
34010 static SDValue LowerADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG) {
34011   SDNode *N = Op.getNode();
34012   MVT VT = N->getSimpleValueType(0);
34013   unsigned Opc = Op.getOpcode();
34014 
34015   // Let legalize expand this if it isn't a legal type yet.
34016   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
34017     return SDValue();
34018 
34019   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
34020   SDLoc DL(N);
34021 
34022   // Set the carry flag.
34023   SDValue Carry = Op.getOperand(2);
34024   EVT CarryVT = Carry.getValueType();
34025   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
34026                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
34027 
34028   bool IsAdd = Opc == ISD::UADDO_CARRY || Opc == ISD::SADDO_CARRY;
34029   SDValue Sum = DAG.getNode(IsAdd ? X86ISD::ADC : X86ISD::SBB, DL, VTs,
34030                             Op.getOperand(0), Op.getOperand(1),
34031                             Carry.getValue(1));
34032 
34033   bool IsSigned = Opc == ISD::SADDO_CARRY || Opc == ISD::SSUBO_CARRY;
34034   SDValue SetCC = getSETCC(IsSigned ? X86::COND_O : X86::COND_B,
34035                            Sum.getValue(1), DL, DAG);
34036   if (N->getValueType(1) == MVT::i1)
34037     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
34038 
34039   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
34040 }
34041 
34042 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
34043                             SelectionDAG &DAG) {
34044   assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
34045 
34046   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
34047   // which returns the values as { float, float } (in XMM0) or
34048   // { double, double } (which is returned in XMM0, XMM1).
34049   SDLoc dl(Op);
34050   SDValue Arg = Op.getOperand(0);
34051   EVT ArgVT = Arg.getValueType();
34052   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
34053 
34054   TargetLowering::ArgListTy Args;
34055   TargetLowering::ArgListEntry Entry;
34056 
34057   Entry.Node = Arg;
34058   Entry.Ty = ArgTy;
34059   Entry.IsSExt = false;
34060   Entry.IsZExt = false;
34061   Args.push_back(Entry);
34062 
34063   bool isF64 = ArgVT == MVT::f64;
34064   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
34065   // the small struct {f32, f32} is returned in (eax, edx). For f64,
34066   // the results are returned via SRet in memory.
34067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
34068   RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
34069   const char *LibcallName = TLI.getLibcallName(LC);
34070   SDValue Callee =
34071       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
34072 
34073   Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
34074                       : (Type *)FixedVectorType::get(ArgTy, 4);
34075 
34076   TargetLowering::CallLoweringInfo CLI(DAG);
34077   CLI.setDebugLoc(dl)
34078       .setChain(DAG.getEntryNode())
34079       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
34080 
34081   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
34082 
34083   if (isF64)
34084     // Returned in xmm0 and xmm1.
34085     return CallResult.first;
34086 
34087   // Returned in bits 0:31 and 32:64 xmm0.
34088   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
34089                                CallResult.first, DAG.getIntPtrConstant(0, dl));
34090   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
34091                                CallResult.first, DAG.getIntPtrConstant(1, dl));
34092   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
34093   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
34094 }
34095 
34096 /// Widen a vector input to a vector of NVT.  The
34097 /// input vector must have the same element type as NVT.
34098 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
34099                             bool FillWithZeroes = false) {
34100   // Check if InOp already has the right width.
34101   MVT InVT = InOp.getSimpleValueType();
34102   if (InVT == NVT)
34103     return InOp;
34104 
34105   if (InOp.isUndef())
34106     return DAG.getUNDEF(NVT);
34107 
34108   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
34109          "input and widen element type must match");
34110 
34111   unsigned InNumElts = InVT.getVectorNumElements();
34112   unsigned WidenNumElts = NVT.getVectorNumElements();
34113   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
34114          "Unexpected request for vector widening");
34115 
34116   SDLoc dl(InOp);
34117   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
34118       InOp.getNumOperands() == 2) {
34119     SDValue N1 = InOp.getOperand(1);
34120     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
34121         N1.isUndef()) {
34122       InOp = InOp.getOperand(0);
34123       InVT = InOp.getSimpleValueType();
34124       InNumElts = InVT.getVectorNumElements();
34125     }
34126   }
34127   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
34128       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
34129     SmallVector<SDValue, 16> Ops;
34130     for (unsigned i = 0; i < InNumElts; ++i)
34131       Ops.push_back(InOp.getOperand(i));
34132 
34133     EVT EltVT = InOp.getOperand(0).getValueType();
34134 
34135     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
34136       DAG.getUNDEF(EltVT);
34137     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
34138       Ops.push_back(FillVal);
34139     return DAG.getBuildVector(NVT, dl, Ops);
34140   }
34141   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
34142     DAG.getUNDEF(NVT);
34143   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
34144                      InOp, DAG.getIntPtrConstant(0, dl));
34145 }
34146 
34147 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
34148                              SelectionDAG &DAG) {
34149   assert(Subtarget.hasAVX512() &&
34150          "MGATHER/MSCATTER are supported on AVX-512 arch only");
34151 
34152   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
34153   SDValue Src = N->getValue();
34154   MVT VT = Src.getSimpleValueType();
34155   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
34156   SDLoc dl(Op);
34157 
34158   SDValue Scale = N->getScale();
34159   SDValue Index = N->getIndex();
34160   SDValue Mask = N->getMask();
34161   SDValue Chain = N->getChain();
34162   SDValue BasePtr = N->getBasePtr();
34163 
34164   if (VT == MVT::v2f32 || VT == MVT::v2i32) {
34165     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
34166     // If the index is v2i64 and we have VLX we can use xmm for data and index.
34167     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
34168       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
34169       EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
34170       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
34171       SDVTList VTs = DAG.getVTList(MVT::Other);
34172       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
34173       return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
34174                                      N->getMemoryVT(), N->getMemOperand());
34175     }
34176     return SDValue();
34177   }
34178 
34179   MVT IndexVT = Index.getSimpleValueType();
34180 
34181   // If the index is v2i32, we're being called by type legalization and we
34182   // should just let the default handling take care of it.
34183   if (IndexVT == MVT::v2i32)
34184     return SDValue();
34185 
34186   // If we don't have VLX and neither the passthru or index is 512-bits, we
34187   // need to widen until one is.
34188   if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
34189       !Index.getSimpleValueType().is512BitVector()) {
34190     // Determine how much we need to widen by to get a 512-bit type.
34191     unsigned Factor = std::min(512/VT.getSizeInBits(),
34192                                512/IndexVT.getSizeInBits());
34193     unsigned NumElts = VT.getVectorNumElements() * Factor;
34194 
34195     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
34196     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
34197     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
34198 
34199     Src = ExtendToType(Src, VT, DAG);
34200     Index = ExtendToType(Index, IndexVT, DAG);
34201     Mask = ExtendToType(Mask, MaskVT, DAG, true);
34202   }
34203 
34204   SDVTList VTs = DAG.getVTList(MVT::Other);
34205   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
34206   return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
34207                                  N->getMemoryVT(), N->getMemOperand());
34208 }
34209 
34210 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
34211                           SelectionDAG &DAG) {
34212 
34213   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
34214   MVT VT = Op.getSimpleValueType();
34215   MVT ScalarVT = VT.getScalarType();
34216   SDValue Mask = N->getMask();
34217   MVT MaskVT = Mask.getSimpleValueType();
34218   SDValue PassThru = N->getPassThru();
34219   SDLoc dl(Op);
34220 
34221   // Handle AVX masked loads which don't support passthru other than 0.
34222   if (MaskVT.getVectorElementType() != MVT::i1) {
34223     // We also allow undef in the isel pattern.
34224     if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
34225       return Op;
34226 
34227     SDValue NewLoad = DAG.getMaskedLoad(
34228         VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
34229         getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
34230         N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
34231         N->isExpandingLoad());
34232     // Emit a blend.
34233     SDValue Select = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
34234     return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
34235   }
34236 
34237   assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
34238          "Expanding masked load is supported on AVX-512 target only!");
34239 
34240   assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
34241          "Expanding masked load is supported for 32 and 64-bit types only!");
34242 
34243   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
34244          "Cannot lower masked load op.");
34245 
34246   assert((ScalarVT.getSizeInBits() >= 32 ||
34247           (Subtarget.hasBWI() &&
34248               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
34249          "Unsupported masked load op.");
34250 
34251   // This operation is legal for targets with VLX, but without
34252   // VLX the vector should be widened to 512 bit
34253   unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
34254   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
34255   PassThru = ExtendToType(PassThru, WideDataVT, DAG);
34256 
34257   // Mask element has to be i1.
34258   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
34259          "Unexpected mask type");
34260 
34261   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
34262 
34263   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
34264   SDValue NewLoad = DAG.getMaskedLoad(
34265       WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
34266       PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
34267       N->getExtensionType(), N->isExpandingLoad());
34268 
34269   SDValue Extract =
34270       DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, NewLoad.getValue(0),
34271                   DAG.getIntPtrConstant(0, dl));
34272   SDValue RetOps[] = {Extract, NewLoad.getValue(1)};
34273   return DAG.getMergeValues(RetOps, dl);
34274 }
34275 
34276 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
34277                            SelectionDAG &DAG) {
34278   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
34279   SDValue DataToStore = N->getValue();
34280   MVT VT = DataToStore.getSimpleValueType();
34281   MVT ScalarVT = VT.getScalarType();
34282   SDValue Mask = N->getMask();
34283   SDLoc dl(Op);
34284 
34285   assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
34286          "Expanding masked load is supported on AVX-512 target only!");
34287 
34288   assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
34289          "Expanding masked load is supported for 32 and 64-bit types only!");
34290 
34291   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
34292          "Cannot lower masked store op.");
34293 
34294   assert((ScalarVT.getSizeInBits() >= 32 ||
34295           (Subtarget.hasBWI() &&
34296               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
34297           "Unsupported masked store op.");
34298 
34299   // This operation is legal for targets with VLX, but without
34300   // VLX the vector should be widened to 512 bit
34301   unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
34302   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
34303 
34304   // Mask element has to be i1.
34305   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
34306          "Unexpected mask type");
34307 
34308   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
34309 
34310   DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
34311   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
34312   return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
34313                             N->getOffset(), Mask, N->getMemoryVT(),
34314                             N->getMemOperand(), N->getAddressingMode(),
34315                             N->isTruncatingStore(), N->isCompressingStore());
34316 }
34317 
34318 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
34319                             SelectionDAG &DAG) {
34320   assert(Subtarget.hasAVX2() &&
34321          "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
34322 
34323   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
34324   SDLoc dl(Op);
34325   MVT VT = Op.getSimpleValueType();
34326   SDValue Index = N->getIndex();
34327   SDValue Mask = N->getMask();
34328   SDValue PassThru = N->getPassThru();
34329   MVT IndexVT = Index.getSimpleValueType();
34330 
34331   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
34332 
34333   // If the index is v2i32, we're being called by type legalization.
34334   if (IndexVT == MVT::v2i32)
34335     return SDValue();
34336 
34337   // If we don't have VLX and neither the passthru or index is 512-bits, we
34338   // need to widen until one is.
34339   MVT OrigVT = VT;
34340   if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
34341       !IndexVT.is512BitVector()) {
34342     // Determine how much we need to widen by to get a 512-bit type.
34343     unsigned Factor = std::min(512/VT.getSizeInBits(),
34344                                512/IndexVT.getSizeInBits());
34345 
34346     unsigned NumElts = VT.getVectorNumElements() * Factor;
34347 
34348     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
34349     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
34350     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
34351 
34352     PassThru = ExtendToType(PassThru, VT, DAG);
34353     Index = ExtendToType(Index, IndexVT, DAG);
34354     Mask = ExtendToType(Mask, MaskVT, DAG, true);
34355   }
34356 
34357   // Break dependency on the data register.
34358   if (PassThru.isUndef())
34359     PassThru = getZeroVector(VT, Subtarget, DAG, dl);
34360 
34361   SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
34362                     N->getScale() };
34363   SDValue NewGather = DAG.getMemIntrinsicNode(
34364       X86ISD::MGATHER, dl, DAG.getVTList(VT, MVT::Other), Ops, N->getMemoryVT(),
34365       N->getMemOperand());
34366   SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
34367                                 NewGather, DAG.getIntPtrConstant(0, dl));
34368   return DAG.getMergeValues({Extract, NewGather.getValue(1)}, dl);
34369 }
34370 
34371 static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
34372   SDLoc dl(Op);
34373   SDValue Src = Op.getOperand(0);
34374   MVT DstVT = Op.getSimpleValueType();
34375 
34376   AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
34377   unsigned SrcAS = N->getSrcAddressSpace();
34378 
34379   assert(SrcAS != N->getDestAddressSpace() &&
34380          "addrspacecast must be between different address spaces");
34381 
34382   if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
34383     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
34384   } else if (DstVT == MVT::i64) {
34385     Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
34386   } else if (DstVT == MVT::i32) {
34387     Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
34388   } else {
34389     report_fatal_error("Bad address space in addrspacecast");
34390   }
34391   return Op;
34392 }
34393 
34394 SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
34395                                               SelectionDAG &DAG) const {
34396   // TODO: Eventually, the lowering of these nodes should be informed by or
34397   // deferred to the GC strategy for the function in which they appear. For
34398   // now, however, they must be lowered to something. Since they are logically
34399   // no-ops in the case of a null GC strategy (or a GC strategy which does not
34400   // require special handling for these nodes), lower them as literal NOOPs for
34401   // the time being.
34402   SmallVector<SDValue, 2> Ops;
34403   Ops.push_back(Op.getOperand(0));
34404   if (Op->getGluedNode())
34405     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
34406 
34407   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
34408   return SDValue(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
34409 }
34410 
34411 // Custom split CVTPS2PH with wide types.
34412 static SDValue LowerCVTPS2PH(SDValue Op, SelectionDAG &DAG) {
34413   SDLoc dl(Op);
34414   EVT VT = Op.getValueType();
34415   SDValue Lo, Hi;
34416   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
34417   EVT LoVT, HiVT;
34418   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
34419   SDValue RC = Op.getOperand(1);
34420   Lo = DAG.getNode(X86ISD::CVTPS2PH, dl, LoVT, Lo, RC);
34421   Hi = DAG.getNode(X86ISD::CVTPS2PH, dl, HiVT, Hi, RC);
34422   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
34423 }
34424 
34425 static SDValue LowerPREFETCH(SDValue Op, const X86Subtarget &Subtarget,
34426                              SelectionDAG &DAG) {
34427   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
34428 
34429   // We don't support non-data prefetch without PREFETCHI.
34430   // Just preserve the chain.
34431   if (!IsData && !Subtarget.hasPREFETCHI())
34432     return Op.getOperand(0);
34433 
34434   return Op;
34435 }
34436 
34437 static StringRef getInstrStrFromOpNo(const SmallVectorImpl<StringRef> &AsmStrs,
34438                                      unsigned OpNo) {
34439   const APInt Operand(32, OpNo);
34440   std::string OpNoStr = llvm::toString(Operand, 10, false);
34441   std::string Str(" $");
34442 
34443   std::string OpNoStr1(Str + OpNoStr);             // e.g. " $1" (OpNo=1)
34444   std::string OpNoStr2(Str + "{" + OpNoStr + ":"); // With modifier, e.g. ${1:P}
34445 
34446   auto I = StringRef::npos;
34447   for (auto &AsmStr : AsmStrs) {
34448     // Match the OpNo string. We should match exactly to exclude match
34449     // sub-string, e.g. "$12" contain "$1"
34450     if (AsmStr.endswith(OpNoStr1))
34451       I = AsmStr.size() - OpNoStr1.size();
34452 
34453     // Get the index of operand in AsmStr.
34454     if (I == StringRef::npos)
34455       I = AsmStr.find(OpNoStr1 + ",");
34456     if (I == StringRef::npos)
34457       I = AsmStr.find(OpNoStr2);
34458 
34459     if (I == StringRef::npos)
34460       continue;
34461 
34462     assert(I > 0 && "Unexpected inline asm string!");
34463     // Remove the operand string and label (if exsit).
34464     // For example:
34465     // ".L__MSASMLABEL_.${:uid}__l:call dword ptr ${0:P}"
34466     // ==>
34467     // ".L__MSASMLABEL_.${:uid}__l:call dword ptr "
34468     // ==>
34469     // "call dword ptr "
34470     auto TmpStr = AsmStr.substr(0, I);
34471     I = TmpStr.rfind(':');
34472     if (I != StringRef::npos)
34473       TmpStr = TmpStr.substr(I + 1);
34474     return TmpStr.take_while(llvm::isAlpha);
34475   }
34476 
34477   return StringRef();
34478 }
34479 
34480 bool X86TargetLowering::isInlineAsmTargetBranch(
34481     const SmallVectorImpl<StringRef> &AsmStrs, unsigned OpNo) const {
34482   // In a __asm block, __asm inst foo where inst is CALL or JMP should be
34483   // changed from indirect TargetLowering::C_Memory to direct
34484   // TargetLowering::C_Address.
34485   // We don't need to special case LOOP* and Jcc, which cannot target a memory
34486   // location.
34487   StringRef Inst = getInstrStrFromOpNo(AsmStrs, OpNo);
34488   return Inst.equals_insensitive("call") || Inst.equals_insensitive("jmp");
34489 }
34490 
34491 /// Provide custom lowering hooks for some operations.
34492 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
34493   switch (Op.getOpcode()) {
34494   default: llvm_unreachable("Should not custom lower this!");
34495   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
34496   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
34497     return LowerCMP_SWAP(Op, Subtarget, DAG);
34498   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
34499   case ISD::ATOMIC_LOAD_ADD:
34500   case ISD::ATOMIC_LOAD_SUB:
34501   case ISD::ATOMIC_LOAD_OR:
34502   case ISD::ATOMIC_LOAD_XOR:
34503   case ISD::ATOMIC_LOAD_AND:    return lowerAtomicArith(Op, DAG, Subtarget);
34504   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG, Subtarget);
34505   case ISD::BITREVERSE:         return LowerBITREVERSE(Op, Subtarget, DAG);
34506   case ISD::PARITY:             return LowerPARITY(Op, Subtarget, DAG);
34507   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
34508   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
34509   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
34510   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
34511   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
34512   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
34513   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
34514   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
34515   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
34516   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
34517   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
34518   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
34519   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
34520   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
34521   case ISD::SHL_PARTS:
34522   case ISD::SRA_PARTS:
34523   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
34524   case ISD::FSHL:
34525   case ISD::FSHR:               return LowerFunnelShift(Op, Subtarget, DAG);
34526   case ISD::STRICT_SINT_TO_FP:
34527   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
34528   case ISD::STRICT_UINT_TO_FP:
34529   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
34530   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
34531   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
34532   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
34533   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
34534   case ISD::ZERO_EXTEND_VECTOR_INREG:
34535   case ISD::SIGN_EXTEND_VECTOR_INREG:
34536     return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
34537   case ISD::FP_TO_SINT:
34538   case ISD::STRICT_FP_TO_SINT:
34539   case ISD::FP_TO_UINT:
34540   case ISD::STRICT_FP_TO_UINT:  return LowerFP_TO_INT(Op, DAG);
34541   case ISD::FP_TO_SINT_SAT:
34542   case ISD::FP_TO_UINT_SAT:     return LowerFP_TO_INT_SAT(Op, DAG);
34543   case ISD::FP_EXTEND:
34544   case ISD::STRICT_FP_EXTEND:   return LowerFP_EXTEND(Op, DAG);
34545   case ISD::FP_ROUND:
34546   case ISD::STRICT_FP_ROUND:    return LowerFP_ROUND(Op, DAG);
34547   case ISD::FP16_TO_FP:
34548   case ISD::STRICT_FP16_TO_FP:  return LowerFP16_TO_FP(Op, DAG);
34549   case ISD::FP_TO_FP16:
34550   case ISD::STRICT_FP_TO_FP16:  return LowerFP_TO_FP16(Op, DAG);
34551   case ISD::FP_TO_BF16:         return LowerFP_TO_BF16(Op, DAG);
34552   case ISD::LOAD:               return LowerLoad(Op, Subtarget, DAG);
34553   case ISD::STORE:              return LowerStore(Op, Subtarget, DAG);
34554   case ISD::FADD:
34555   case ISD::FSUB:               return lowerFaddFsub(Op, DAG);
34556   case ISD::FROUND:             return LowerFROUND(Op, DAG);
34557   case ISD::FABS:
34558   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
34559   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
34560   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
34561   case ISD::LRINT:
34562   case ISD::LLRINT:             return LowerLRINT_LLRINT(Op, DAG);
34563   case ISD::SETCC:
34564   case ISD::STRICT_FSETCC:
34565   case ISD::STRICT_FSETCCS:     return LowerSETCC(Op, DAG);
34566   case ISD::SETCCCARRY:         return LowerSETCCCARRY(Op, DAG);
34567   case ISD::SELECT:             return LowerSELECT(Op, DAG);
34568   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
34569   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
34570   case ISD::VASTART:            return LowerVASTART(Op, DAG);
34571   case ISD::VAARG:              return LowerVAARG(Op, DAG);
34572   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
34573   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
34574   case ISD::INTRINSIC_VOID:
34575   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
34576   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
34577   case ISD::ADDROFRETURNADDR:   return LowerADDROFRETURNADDR(Op, DAG);
34578   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
34579   case ISD::FRAME_TO_ARGS_OFFSET:
34580                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
34581   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
34582   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
34583   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
34584   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
34585   case ISD::EH_SJLJ_SETUP_DISPATCH:
34586     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
34587   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
34588   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
34589   case ISD::GET_ROUNDING:       return LowerGET_ROUNDING(Op, DAG);
34590   case ISD::SET_ROUNDING:       return LowerSET_ROUNDING(Op, DAG);
34591   case ISD::GET_FPENV_MEM:      return LowerGET_FPENV_MEM(Op, DAG);
34592   case ISD::SET_FPENV_MEM:      return LowerSET_FPENV_MEM(Op, DAG);
34593   case ISD::RESET_FPENV:        return LowerRESET_FPENV(Op, DAG);
34594   case ISD::CTLZ:
34595   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ(Op, Subtarget, DAG);
34596   case ISD::CTTZ:
34597   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, Subtarget, DAG);
34598   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
34599   case ISD::MULHS:
34600   case ISD::MULHU:              return LowerMULH(Op, Subtarget, DAG);
34601   case ISD::ROTL:
34602   case ISD::ROTR:               return LowerRotate(Op, Subtarget, DAG);
34603   case ISD::SRA:
34604   case ISD::SRL:
34605   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
34606   case ISD::SADDO:
34607   case ISD::UADDO:
34608   case ISD::SSUBO:
34609   case ISD::USUBO:              return LowerXALUO(Op, DAG);
34610   case ISD::SMULO:
34611   case ISD::UMULO:              return LowerMULO(Op, Subtarget, DAG);
34612   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
34613   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
34614   case ISD::SADDO_CARRY:
34615   case ISD::SSUBO_CARRY:
34616   case ISD::UADDO_CARRY:
34617   case ISD::USUBO_CARRY:        return LowerADDSUBO_CARRY(Op, DAG);
34618   case ISD::ADD:
34619   case ISD::SUB:                return lowerAddSub(Op, DAG, Subtarget);
34620   case ISD::UADDSAT:
34621   case ISD::SADDSAT:
34622   case ISD::USUBSAT:
34623   case ISD::SSUBSAT:            return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
34624   case ISD::SMAX:
34625   case ISD::SMIN:
34626   case ISD::UMAX:
34627   case ISD::UMIN:               return LowerMINMAX(Op, Subtarget, DAG);
34628   case ISD::FMINIMUM:
34629   case ISD::FMAXIMUM:
34630     return LowerFMINIMUM_FMAXIMUM(Op, Subtarget, DAG);
34631   case ISD::ABS:                return LowerABS(Op, Subtarget, DAG);
34632   case ISD::ABDS:
34633   case ISD::ABDU:               return LowerABD(Op, Subtarget, DAG);
34634   case ISD::AVGCEILU:           return LowerAVG(Op, Subtarget, DAG);
34635   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
34636   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
34637   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
34638   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
34639   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
34640   case ISD::GC_TRANSITION_START:
34641   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION(Op, DAG);
34642   case ISD::ADDRSPACECAST:      return LowerADDRSPACECAST(Op, DAG);
34643   case X86ISD::CVTPS2PH:        return LowerCVTPS2PH(Op, DAG);
34644   case ISD::PREFETCH:           return LowerPREFETCH(Op, Subtarget, DAG);
34645   }
34646 }
34647 
34648 /// Replace a node with an illegal result type with a new node built out of
34649 /// custom code.
34650 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
34651                                            SmallVectorImpl<SDValue>&Results,
34652                                            SelectionDAG &DAG) const {
34653   SDLoc dl(N);
34654   switch (N->getOpcode()) {
34655   default:
34656 #ifndef NDEBUG
34657     dbgs() << "ReplaceNodeResults: ";
34658     N->dump(&DAG);
34659 #endif
34660     llvm_unreachable("Do not know how to custom type legalize this operation!");
34661   case X86ISD::CVTPH2PS: {
34662     EVT VT = N->getValueType(0);
34663     SDValue Lo, Hi;
34664     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
34665     EVT LoVT, HiVT;
34666     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
34667     Lo = DAG.getNode(X86ISD::CVTPH2PS, dl, LoVT, Lo);
34668     Hi = DAG.getNode(X86ISD::CVTPH2PS, dl, HiVT, Hi);
34669     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
34670     Results.push_back(Res);
34671     return;
34672   }
34673   case X86ISD::STRICT_CVTPH2PS: {
34674     EVT VT = N->getValueType(0);
34675     SDValue Lo, Hi;
34676     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 1);
34677     EVT LoVT, HiVT;
34678     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
34679     Lo = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {LoVT, MVT::Other},
34680                      {N->getOperand(0), Lo});
34681     Hi = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {HiVT, MVT::Other},
34682                      {N->getOperand(0), Hi});
34683     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
34684                                 Lo.getValue(1), Hi.getValue(1));
34685     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
34686     Results.push_back(Res);
34687     Results.push_back(Chain);
34688     return;
34689   }
34690   case X86ISD::CVTPS2PH:
34691     Results.push_back(LowerCVTPS2PH(SDValue(N, 0), DAG));
34692     return;
34693   case ISD::CTPOP: {
34694     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
34695     // Use a v2i64 if possible.
34696     bool NoImplicitFloatOps =
34697         DAG.getMachineFunction().getFunction().hasFnAttribute(
34698             Attribute::NoImplicitFloat);
34699     if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
34700       SDValue Wide =
34701           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
34702       Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
34703       // Bit count should fit in 32-bits, extract it as that and then zero
34704       // extend to i64. Otherwise we end up extracting bits 63:32 separately.
34705       Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
34706       Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
34707                          DAG.getIntPtrConstant(0, dl));
34708       Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
34709       Results.push_back(Wide);
34710     }
34711     return;
34712   }
34713   case ISD::MUL: {
34714     EVT VT = N->getValueType(0);
34715     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
34716            VT.getVectorElementType() == MVT::i8 && "Unexpected VT!");
34717     // Pre-promote these to vXi16 to avoid op legalization thinking all 16
34718     // elements are needed.
34719     MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
34720     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
34721     SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
34722     SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
34723     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
34724     unsigned NumConcats = 16 / VT.getVectorNumElements();
34725     SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
34726     ConcatOps[0] = Res;
34727     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
34728     Results.push_back(Res);
34729     return;
34730   }
34731   case ISD::SMULO:
34732   case ISD::UMULO: {
34733     EVT VT = N->getValueType(0);
34734     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
34735            VT == MVT::v2i32 && "Unexpected VT!");
34736     bool IsSigned = N->getOpcode() == ISD::SMULO;
34737     unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
34738     SDValue Op0 = DAG.getNode(ExtOpc, dl, MVT::v2i64, N->getOperand(0));
34739     SDValue Op1 = DAG.getNode(ExtOpc, dl, MVT::v2i64, N->getOperand(1));
34740     SDValue Res = DAG.getNode(ISD::MUL, dl, MVT::v2i64, Op0, Op1);
34741     // Extract the high 32 bits from each result using PSHUFD.
34742     // TODO: Could use SRL+TRUNCATE but that doesn't become a PSHUFD.
34743     SDValue Hi = DAG.getBitcast(MVT::v4i32, Res);
34744     Hi = DAG.getVectorShuffle(MVT::v4i32, dl, Hi, Hi, {1, 3, -1, -1});
34745     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Hi,
34746                      DAG.getIntPtrConstant(0, dl));
34747 
34748     // Truncate the low bits of the result. This will become PSHUFD.
34749     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
34750 
34751     SDValue HiCmp;
34752     if (IsSigned) {
34753       // SMULO overflows if the high bits don't match the sign of the low.
34754       HiCmp = DAG.getNode(ISD::SRA, dl, VT, Res, DAG.getConstant(31, dl, VT));
34755     } else {
34756       // UMULO overflows if the high bits are non-zero.
34757       HiCmp = DAG.getConstant(0, dl, VT);
34758     }
34759     SDValue Ovf = DAG.getSetCC(dl, N->getValueType(1), Hi, HiCmp, ISD::SETNE);
34760 
34761     // Widen the result with by padding with undef.
34762     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
34763                       DAG.getUNDEF(VT));
34764     Results.push_back(Res);
34765     Results.push_back(Ovf);
34766     return;
34767   }
34768   case X86ISD::VPMADDWD: {
34769     // Legalize types for X86ISD::VPMADDWD by widening.
34770     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
34771 
34772     EVT VT = N->getValueType(0);
34773     EVT InVT = N->getOperand(0).getValueType();
34774     assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
34775            "Expected a VT that divides into 128 bits.");
34776     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
34777            "Unexpected type action!");
34778     unsigned NumConcat = 128 / InVT.getSizeInBits();
34779 
34780     EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
34781                                     InVT.getVectorElementType(),
34782                                     NumConcat * InVT.getVectorNumElements());
34783     EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
34784                                   VT.getVectorElementType(),
34785                                   NumConcat * VT.getVectorNumElements());
34786 
34787     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
34788     Ops[0] = N->getOperand(0);
34789     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
34790     Ops[0] = N->getOperand(1);
34791     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
34792 
34793     SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
34794     Results.push_back(Res);
34795     return;
34796   }
34797   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
34798   case X86ISD::FMINC:
34799   case X86ISD::FMIN:
34800   case X86ISD::FMAXC:
34801   case X86ISD::FMAX: {
34802     EVT VT = N->getValueType(0);
34803     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
34804     SDValue UNDEF = DAG.getUNDEF(VT);
34805     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
34806                               N->getOperand(0), UNDEF);
34807     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
34808                               N->getOperand(1), UNDEF);
34809     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
34810     return;
34811   }
34812   case ISD::SDIV:
34813   case ISD::UDIV:
34814   case ISD::SREM:
34815   case ISD::UREM: {
34816     EVT VT = N->getValueType(0);
34817     if (VT.isVector()) {
34818       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
34819              "Unexpected type action!");
34820       // If this RHS is a constant splat vector we can widen this and let
34821       // division/remainder by constant optimize it.
34822       // TODO: Can we do something for non-splat?
34823       APInt SplatVal;
34824       if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
34825         unsigned NumConcats = 128 / VT.getSizeInBits();
34826         SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
34827         Ops0[0] = N->getOperand(0);
34828         EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
34829         SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
34830         SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
34831         SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
34832         Results.push_back(Res);
34833       }
34834       return;
34835     }
34836 
34837     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
34838     Results.push_back(V);
34839     return;
34840   }
34841   case ISD::TRUNCATE: {
34842     MVT VT = N->getSimpleValueType(0);
34843     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
34844       return;
34845 
34846     // The generic legalizer will try to widen the input type to the same
34847     // number of elements as the widened result type. But this isn't always
34848     // the best thing so do some custom legalization to avoid some cases.
34849     MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
34850     SDValue In = N->getOperand(0);
34851     EVT InVT = In.getValueType();
34852     EVT InEltVT = InVT.getVectorElementType();
34853     EVT EltVT = VT.getVectorElementType();
34854     unsigned WidenNumElts = WidenVT.getVectorNumElements();
34855 
34856     unsigned InBits = InVT.getSizeInBits();
34857     if (128 % InBits == 0) {
34858       // 128 bit and smaller inputs should avoid truncate all together and
34859       // just use a build_vector that will become a shuffle.
34860       // TODO: Widen and use a shuffle directly?
34861       SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
34862       // Use the original element count so we don't do more scalar opts than
34863       // necessary.
34864       unsigned MinElts = VT.getVectorNumElements();
34865       for (unsigned i=0; i < MinElts; ++i) {
34866         SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
34867                                   DAG.getIntPtrConstant(i, dl));
34868         Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
34869       }
34870       Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
34871       return;
34872     }
34873     // With AVX512 there are some cases that can use a target specific
34874     // truncate node to go from 256/512 to less than 128 with zeros in the
34875     // upper elements of the 128 bit result.
34876     if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
34877       // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
34878       if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
34879         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
34880         return;
34881       }
34882       // There's one case we can widen to 512 bits and use VTRUNC.
34883       if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
34884         In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
34885                          DAG.getUNDEF(MVT::v4i64));
34886         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
34887         return;
34888       }
34889     }
34890     if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
34891         getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
34892         isTypeLegal(MVT::v4i64)) {
34893       // Input needs to be split and output needs to widened. Let's use two
34894       // VTRUNCs, and shuffle their results together into the wider type.
34895       SDValue Lo, Hi;
34896       std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
34897 
34898       Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
34899       Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
34900       SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
34901                                          { 0,  1,  2,  3, 16, 17, 18, 19,
34902                                           -1, -1, -1, -1, -1, -1, -1, -1 });
34903       Results.push_back(Res);
34904       return;
34905     }
34906 
34907     // Attempt to widen the truncation input vector to let LowerTRUNCATE handle
34908     // this via type legalization.
34909     if ((InEltVT == MVT::i16 || InEltVT == MVT::i32 || InEltVT == MVT::i64) &&
34910         (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32) &&
34911         (!Subtarget.hasSSSE3() || (InVT == MVT::v8i64 && VT == MVT::v8i8) ||
34912          (InVT == MVT::v4i64 && VT == MVT::v4i16 && !Subtarget.hasAVX()))) {
34913       SDValue WidenIn = widenSubVector(In, false, Subtarget, DAG, dl,
34914                                        InEltVT.getSizeInBits() * WidenNumElts);
34915       Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, WidenVT, WidenIn));
34916       return;
34917     }
34918 
34919     return;
34920   }
34921   case ISD::ANY_EXTEND:
34922     // Right now, only MVT::v8i8 has Custom action for an illegal type.
34923     // It's intended to custom handle the input type.
34924     assert(N->getValueType(0) == MVT::v8i8 &&
34925            "Do not know how to legalize this Node");
34926     return;
34927   case ISD::SIGN_EXTEND:
34928   case ISD::ZERO_EXTEND: {
34929     EVT VT = N->getValueType(0);
34930     SDValue In = N->getOperand(0);
34931     EVT InVT = In.getValueType();
34932     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
34933         (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
34934       assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&
34935              "Unexpected type action!");
34936       assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode");
34937       // Custom split this so we can extend i8/i16->i32 invec. This is better
34938       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
34939       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
34940       // we allow the sra from the extend to i32 to be shared by the split.
34941       In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
34942 
34943       // Fill a vector with sign bits for each element.
34944       SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
34945       SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
34946 
34947       // Create an unpackl and unpackh to interleave the sign bits then bitcast
34948       // to v2i64.
34949       SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
34950                                         {0, 4, 1, 5});
34951       Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
34952       SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
34953                                         {2, 6, 3, 7});
34954       Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
34955 
34956       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
34957       Results.push_back(Res);
34958       return;
34959     }
34960 
34961     if (VT == MVT::v16i32 || VT == MVT::v8i64) {
34962       if (!InVT.is128BitVector()) {
34963         // Not a 128 bit vector, but maybe type legalization will promote
34964         // it to 128 bits.
34965         if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
34966           return;
34967         InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
34968         if (!InVT.is128BitVector())
34969           return;
34970 
34971         // Promote the input to 128 bits. Type legalization will turn this into
34972         // zext_inreg/sext_inreg.
34973         In = DAG.getNode(N->getOpcode(), dl, InVT, In);
34974       }
34975 
34976       // Perform custom splitting instead of the two stage extend we would get
34977       // by default.
34978       EVT LoVT, HiVT;
34979       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
34980       assert(isTypeLegal(LoVT) && "Split VT not legal?");
34981 
34982       SDValue Lo = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, LoVT, In, DAG);
34983 
34984       // We need to shift the input over by half the number of elements.
34985       unsigned NumElts = InVT.getVectorNumElements();
34986       unsigned HalfNumElts = NumElts / 2;
34987       SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
34988       for (unsigned i = 0; i != HalfNumElts; ++i)
34989         ShufMask[i] = i + HalfNumElts;
34990 
34991       SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
34992       Hi = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, HiVT, Hi, DAG);
34993 
34994       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
34995       Results.push_back(Res);
34996     }
34997     return;
34998   }
34999   case ISD::FP_TO_SINT:
35000   case ISD::STRICT_FP_TO_SINT:
35001   case ISD::FP_TO_UINT:
35002   case ISD::STRICT_FP_TO_UINT: {
35003     bool IsStrict = N->isStrictFPOpcode();
35004     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
35005                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
35006     EVT VT = N->getValueType(0);
35007     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
35008     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
35009     EVT SrcVT = Src.getValueType();
35010 
35011     SDValue Res;
35012     if (isSoftF16(SrcVT, Subtarget)) {
35013       EVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
35014       if (IsStrict) {
35015         Res =
35016             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
35017                         {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
35018                                             {NVT, MVT::Other}, {Chain, Src})});
35019         Chain = Res.getValue(1);
35020       } else {
35021         Res = DAG.getNode(N->getOpcode(), dl, VT,
35022                           DAG.getNode(ISD::FP_EXTEND, dl, NVT, Src));
35023       }
35024       Results.push_back(Res);
35025       if (IsStrict)
35026         Results.push_back(Chain);
35027 
35028       return;
35029     }
35030 
35031     if (VT.isVector() && Subtarget.hasFP16() &&
35032         SrcVT.getVectorElementType() == MVT::f16) {
35033       EVT EleVT = VT.getVectorElementType();
35034       EVT ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
35035 
35036       if (SrcVT != MVT::v8f16) {
35037         SDValue Tmp =
35038             IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
35039         SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
35040         Ops[0] = Src;
35041         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
35042       }
35043 
35044       if (IsStrict) {
35045         unsigned Opc =
35046             IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
35047         Res =
35048             DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {N->getOperand(0), Src});
35049         Chain = Res.getValue(1);
35050       } else {
35051         unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
35052         Res = DAG.getNode(Opc, dl, ResVT, Src);
35053       }
35054 
35055       // TODO: Need to add exception check code for strict FP.
35056       if (EleVT.getSizeInBits() < 16) {
35057         MVT TmpVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8);
35058         Res = DAG.getNode(ISD::TRUNCATE, dl, TmpVT, Res);
35059 
35060         // Now widen to 128 bits.
35061         unsigned NumConcats = 128 / TmpVT.getSizeInBits();
35062         MVT ConcatVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8 * NumConcats);
35063         SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(TmpVT));
35064         ConcatOps[0] = Res;
35065         Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
35066       }
35067 
35068       Results.push_back(Res);
35069       if (IsStrict)
35070         Results.push_back(Chain);
35071 
35072       return;
35073     }
35074 
35075     if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
35076       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
35077              "Unexpected type action!");
35078 
35079       // Try to create a 128 bit vector, but don't exceed a 32 bit element.
35080       unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
35081       MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
35082                                        VT.getVectorNumElements());
35083       SDValue Res;
35084       SDValue Chain;
35085       if (IsStrict) {
35086         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
35087                           {N->getOperand(0), Src});
35088         Chain = Res.getValue(1);
35089       } else
35090         Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
35091 
35092       // Preserve what we know about the size of the original result. If the
35093       // result is v2i32, we have to manually widen the assert.
35094       if (PromoteVT == MVT::v2i32)
35095         Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
35096                           DAG.getUNDEF(MVT::v2i32));
35097 
35098       Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext, dl,
35099                         Res.getValueType(), Res,
35100                         DAG.getValueType(VT.getVectorElementType()));
35101 
35102       if (PromoteVT == MVT::v2i32)
35103         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
35104                           DAG.getIntPtrConstant(0, dl));
35105 
35106       // Truncate back to the original width.
35107       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
35108 
35109       // Now widen to 128 bits.
35110       unsigned NumConcats = 128 / VT.getSizeInBits();
35111       MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
35112                                       VT.getVectorNumElements() * NumConcats);
35113       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
35114       ConcatOps[0] = Res;
35115       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
35116       Results.push_back(Res);
35117       if (IsStrict)
35118         Results.push_back(Chain);
35119       return;
35120     }
35121 
35122 
35123     if (VT == MVT::v2i32) {
35124       assert((!IsStrict || IsSigned || Subtarget.hasAVX512()) &&
35125              "Strict unsigned conversion requires AVX512");
35126       assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
35127       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
35128              "Unexpected type action!");
35129       if (Src.getValueType() == MVT::v2f64) {
35130         if (!IsSigned && !Subtarget.hasAVX512()) {
35131           SDValue Res =
35132               expandFP_TO_UINT_SSE(MVT::v4i32, Src, dl, DAG, Subtarget);
35133           Results.push_back(Res);
35134           return;
35135         }
35136 
35137         unsigned Opc;
35138         if (IsStrict)
35139           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
35140         else
35141           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
35142 
35143         // If we have VLX we can emit a target specific FP_TO_UINT node,.
35144         if (!IsSigned && !Subtarget.hasVLX()) {
35145           // Otherwise we can defer to the generic legalizer which will widen
35146           // the input as well. This will be further widened during op
35147           // legalization to v8i32<-v8f64.
35148           // For strict nodes we'll need to widen ourselves.
35149           // FIXME: Fix the type legalizer to safely widen strict nodes?
35150           if (!IsStrict)
35151             return;
35152           Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
35153                             DAG.getConstantFP(0.0, dl, MVT::v2f64));
35154           Opc = N->getOpcode();
35155         }
35156         SDValue Res;
35157         SDValue Chain;
35158         if (IsStrict) {
35159           Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
35160                             {N->getOperand(0), Src});
35161           Chain = Res.getValue(1);
35162         } else {
35163           Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
35164         }
35165         Results.push_back(Res);
35166         if (IsStrict)
35167           Results.push_back(Chain);
35168         return;
35169       }
35170 
35171       // Custom widen strict v2f32->v2i32 by padding with zeros.
35172       // FIXME: Should generic type legalizer do this?
35173       if (Src.getValueType() == MVT::v2f32 && IsStrict) {
35174         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
35175                           DAG.getConstantFP(0.0, dl, MVT::v2f32));
35176         SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
35177                                   {N->getOperand(0), Src});
35178         Results.push_back(Res);
35179         Results.push_back(Res.getValue(1));
35180         return;
35181       }
35182 
35183       // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
35184       // so early out here.
35185       return;
35186     }
35187 
35188     assert(!VT.isVector() && "Vectors should have been handled above!");
35189 
35190     if ((Subtarget.hasDQI() && VT == MVT::i64 &&
35191          (SrcVT == MVT::f32 || SrcVT == MVT::f64)) ||
35192         (Subtarget.hasFP16() && SrcVT == MVT::f16)) {
35193       assert(!Subtarget.is64Bit() && "i64 should be legal");
35194       unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
35195       // If we use a 128-bit result we might need to use a target specific node.
35196       unsigned SrcElts =
35197           std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
35198       MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
35199       MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
35200       unsigned Opc = N->getOpcode();
35201       if (NumElts != SrcElts) {
35202         if (IsStrict)
35203           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
35204         else
35205           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
35206       }
35207 
35208       SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
35209       SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
35210                                 DAG.getConstantFP(0.0, dl, VecInVT), Src,
35211                                 ZeroIdx);
35212       SDValue Chain;
35213       if (IsStrict) {
35214         SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
35215         Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
35216         Chain = Res.getValue(1);
35217       } else
35218         Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
35219       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
35220       Results.push_back(Res);
35221       if (IsStrict)
35222         Results.push_back(Chain);
35223       return;
35224     }
35225 
35226     if (VT == MVT::i128 && Subtarget.isTargetWin64()) {
35227       SDValue Chain;
35228       SDValue V = LowerWin64_FP_TO_INT128(SDValue(N, 0), DAG, Chain);
35229       Results.push_back(V);
35230       if (IsStrict)
35231         Results.push_back(Chain);
35232       return;
35233     }
35234 
35235     if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
35236       Results.push_back(V);
35237       if (IsStrict)
35238         Results.push_back(Chain);
35239     }
35240     return;
35241   }
35242   case ISD::LRINT:
35243   case ISD::LLRINT: {
35244     if (SDValue V = LRINT_LLRINTHelper(N, DAG))
35245       Results.push_back(V);
35246     return;
35247   }
35248 
35249   case ISD::SINT_TO_FP:
35250   case ISD::STRICT_SINT_TO_FP:
35251   case ISD::UINT_TO_FP:
35252   case ISD::STRICT_UINT_TO_FP: {
35253     bool IsStrict = N->isStrictFPOpcode();
35254     bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
35255                     N->getOpcode() == ISD::STRICT_SINT_TO_FP;
35256     EVT VT = N->getValueType(0);
35257     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
35258     if (VT.getVectorElementType() == MVT::f16 && Subtarget.hasFP16() &&
35259         Subtarget.hasVLX()) {
35260       if (Src.getValueType().getVectorElementType() == MVT::i16)
35261         return;
35262 
35263       if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2i32)
35264         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
35265                           IsStrict ? DAG.getConstant(0, dl, MVT::v2i32)
35266                                    : DAG.getUNDEF(MVT::v2i32));
35267       if (IsStrict) {
35268         unsigned Opc =
35269             IsSigned ? X86ISD::STRICT_CVTSI2P : X86ISD::STRICT_CVTUI2P;
35270         SDValue Res = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
35271                                   {N->getOperand(0), Src});
35272         Results.push_back(Res);
35273         Results.push_back(Res.getValue(1));
35274       } else {
35275         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
35276         Results.push_back(DAG.getNode(Opc, dl, MVT::v8f16, Src));
35277       }
35278       return;
35279     }
35280     if (VT != MVT::v2f32)
35281       return;
35282     EVT SrcVT = Src.getValueType();
35283     if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
35284       if (IsStrict) {
35285         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
35286                                 : X86ISD::STRICT_CVTUI2P;
35287         SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
35288                                   {N->getOperand(0), Src});
35289         Results.push_back(Res);
35290         Results.push_back(Res.getValue(1));
35291       } else {
35292         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
35293         Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
35294       }
35295       return;
35296     }
35297     if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
35298         Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
35299       SDValue Zero = DAG.getConstant(0, dl, SrcVT);
35300       SDValue One  = DAG.getConstant(1, dl, SrcVT);
35301       SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
35302                                  DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
35303                                  DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
35304       SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
35305       SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
35306       SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
35307       for (int i = 0; i != 2; ++i) {
35308         SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
35309                                   SignSrc, DAG.getIntPtrConstant(i, dl));
35310         if (IsStrict)
35311           SignCvts[i] =
35312               DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
35313                           {N->getOperand(0), Elt});
35314         else
35315           SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Elt);
35316       };
35317       SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
35318       SDValue Slow, Chain;
35319       if (IsStrict) {
35320         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
35321                             SignCvts[0].getValue(1), SignCvts[1].getValue(1));
35322         Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
35323                            {Chain, SignCvt, SignCvt});
35324         Chain = Slow.getValue(1);
35325       } else {
35326         Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
35327       }
35328       IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
35329       IsNeg =
35330           DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
35331       SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
35332       Results.push_back(Cvt);
35333       if (IsStrict)
35334         Results.push_back(Chain);
35335       return;
35336     }
35337 
35338     if (SrcVT != MVT::v2i32)
35339       return;
35340 
35341     if (IsSigned || Subtarget.hasAVX512()) {
35342       if (!IsStrict)
35343         return;
35344 
35345       // Custom widen strict v2i32->v2f32 to avoid scalarization.
35346       // FIXME: Should generic type legalizer do this?
35347       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
35348                         DAG.getConstant(0, dl, MVT::v2i32));
35349       SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
35350                                 {N->getOperand(0), Src});
35351       Results.push_back(Res);
35352       Results.push_back(Res.getValue(1));
35353       return;
35354     }
35355 
35356     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
35357     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
35358     SDValue VBias = DAG.getConstantFP(
35359         llvm::bit_cast<double>(0x4330000000000000ULL), dl, MVT::v2f64);
35360     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
35361                              DAG.getBitcast(MVT::v2i64, VBias));
35362     Or = DAG.getBitcast(MVT::v2f64, Or);
35363     if (IsStrict) {
35364       SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
35365                                 {N->getOperand(0), Or, VBias});
35366       SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
35367                                 {MVT::v4f32, MVT::Other},
35368                                 {Sub.getValue(1), Sub});
35369       Results.push_back(Res);
35370       Results.push_back(Res.getValue(1));
35371     } else {
35372       // TODO: Are there any fast-math-flags to propagate here?
35373       SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
35374       Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
35375     }
35376     return;
35377   }
35378   case ISD::STRICT_FP_ROUND:
35379   case ISD::FP_ROUND: {
35380     bool IsStrict = N->isStrictFPOpcode();
35381     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
35382     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
35383     SDValue Rnd = N->getOperand(IsStrict ? 2 : 1);
35384     EVT SrcVT = Src.getValueType();
35385     EVT VT = N->getValueType(0);
35386     SDValue V;
35387     if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2f32) {
35388       SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f32)
35389                              : DAG.getUNDEF(MVT::v2f32);
35390       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src, Ext);
35391     }
35392     if (!Subtarget.hasFP16() && VT.getVectorElementType() == MVT::f16) {
35393       assert(Subtarget.hasF16C() && "Cannot widen f16 without F16C");
35394       if (SrcVT.getVectorElementType() != MVT::f32)
35395         return;
35396 
35397       if (IsStrict)
35398         V = DAG.getNode(X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
35399                         {Chain, Src, Rnd});
35400       else
35401         V = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Src, Rnd);
35402 
35403       Results.push_back(DAG.getBitcast(MVT::v8f16, V));
35404       if (IsStrict)
35405         Results.push_back(V.getValue(1));
35406       return;
35407     }
35408     if (!isTypeLegal(Src.getValueType()))
35409       return;
35410     EVT NewVT = VT.getVectorElementType() == MVT::f16 ? MVT::v8f16 : MVT::v4f32;
35411     if (IsStrict)
35412       V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {NewVT, MVT::Other},
35413                       {Chain, Src});
35414     else
35415       V = DAG.getNode(X86ISD::VFPROUND, dl, NewVT, Src);
35416     Results.push_back(V);
35417     if (IsStrict)
35418       Results.push_back(V.getValue(1));
35419     return;
35420   }
35421   case ISD::FP_EXTEND:
35422   case ISD::STRICT_FP_EXTEND: {
35423     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
35424     // No other ValueType for FP_EXTEND should reach this point.
35425     assert(N->getValueType(0) == MVT::v2f32 &&
35426            "Do not know how to legalize this Node");
35427     if (!Subtarget.hasFP16() || !Subtarget.hasVLX())
35428       return;
35429     bool IsStrict = N->isStrictFPOpcode();
35430     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
35431     SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f16)
35432                            : DAG.getUNDEF(MVT::v2f16);
35433     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f16, Src, Ext);
35434     if (IsStrict)
35435       V = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::v4f32, MVT::Other},
35436                       {N->getOperand(0), V});
35437     else
35438       V = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, V);
35439     Results.push_back(V);
35440     if (IsStrict)
35441       Results.push_back(V.getValue(1));
35442     return;
35443   }
35444   case ISD::INTRINSIC_W_CHAIN: {
35445     unsigned IntNo = N->getConstantOperandVal(1);
35446     switch (IntNo) {
35447     default : llvm_unreachable("Do not know how to custom type "
35448                                "legalize this intrinsic operation!");
35449     case Intrinsic::x86_rdtsc:
35450       return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
35451                                      Results);
35452     case Intrinsic::x86_rdtscp:
35453       return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
35454                                      Results);
35455     case Intrinsic::x86_rdpmc:
35456       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
35457                                   Results);
35458       return;
35459     case Intrinsic::x86_rdpru:
35460       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPRU, X86::ECX, Subtarget,
35461         Results);
35462       return;
35463     case Intrinsic::x86_xgetbv:
35464       expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
35465                                   Results);
35466       return;
35467     }
35468   }
35469   case ISD::READCYCLECOUNTER: {
35470     return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
35471   }
35472   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
35473     EVT T = N->getValueType(0);
35474     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
35475     bool Regs64bit = T == MVT::i128;
35476     assert((!Regs64bit || Subtarget.canUseCMPXCHG16B()) &&
35477            "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B");
35478     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
35479     SDValue cpInL, cpInH;
35480     std::tie(cpInL, cpInH) =
35481         DAG.SplitScalar(N->getOperand(2), dl, HalfT, HalfT);
35482     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
35483                              Regs64bit ? X86::RAX : X86::EAX, cpInL, SDValue());
35484     cpInH =
35485         DAG.getCopyToReg(cpInL.getValue(0), dl, Regs64bit ? X86::RDX : X86::EDX,
35486                          cpInH, cpInL.getValue(1));
35487     SDValue swapInL, swapInH;
35488     std::tie(swapInL, swapInH) =
35489         DAG.SplitScalar(N->getOperand(3), dl, HalfT, HalfT);
35490     swapInH =
35491         DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
35492                          swapInH, cpInH.getValue(1));
35493 
35494     // In 64-bit mode we might need the base pointer in RBX, but we can't know
35495     // until later. So we keep the RBX input in a vreg and use a custom
35496     // inserter.
35497     // Since RBX will be a reserved register the register allocator will not
35498     // make sure its value will be properly saved and restored around this
35499     // live-range.
35500     SDValue Result;
35501     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
35502     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
35503     if (Regs64bit) {
35504       SDValue Ops[] = {swapInH.getValue(0), N->getOperand(1), swapInL,
35505                        swapInH.getValue(1)};
35506       Result =
35507           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG16_DAG, dl, Tys, Ops, T, MMO);
35508     } else {
35509       swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl, X86::EBX, swapInL,
35510                                  swapInH.getValue(1));
35511       SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
35512                        swapInL.getValue(1)};
35513       Result =
35514           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, T, MMO);
35515     }
35516 
35517     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
35518                                         Regs64bit ? X86::RAX : X86::EAX,
35519                                         HalfT, Result.getValue(1));
35520     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
35521                                         Regs64bit ? X86::RDX : X86::EDX,
35522                                         HalfT, cpOutL.getValue(2));
35523     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
35524 
35525     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
35526                                         MVT::i32, cpOutH.getValue(2));
35527     SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
35528     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
35529 
35530     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
35531     Results.push_back(Success);
35532     Results.push_back(EFLAGS.getValue(1));
35533     return;
35534   }
35535   case ISD::ATOMIC_LOAD: {
35536     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
35537     bool NoImplicitFloatOps =
35538         DAG.getMachineFunction().getFunction().hasFnAttribute(
35539             Attribute::NoImplicitFloat);
35540     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
35541       auto *Node = cast<AtomicSDNode>(N);
35542       if (Subtarget.hasSSE1()) {
35543         // Use a VZEXT_LOAD which will be selected as MOVQ or XORPS+MOVLPS.
35544         // Then extract the lower 64-bits.
35545         MVT LdVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
35546         SDVTList Tys = DAG.getVTList(LdVT, MVT::Other);
35547         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
35548         SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
35549                                              MVT::i64, Node->getMemOperand());
35550         if (Subtarget.hasSSE2()) {
35551           SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
35552                                     DAG.getIntPtrConstant(0, dl));
35553           Results.push_back(Res);
35554           Results.push_back(Ld.getValue(1));
35555           return;
35556         }
35557         // We use an alternative sequence for SSE1 that extracts as v2f32 and
35558         // then casts to i64. This avoids a 128-bit stack temporary being
35559         // created by type legalization if we were to cast v4f32->v2i64.
35560         SDValue Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Ld,
35561                                   DAG.getIntPtrConstant(0, dl));
35562         Res = DAG.getBitcast(MVT::i64, Res);
35563         Results.push_back(Res);
35564         Results.push_back(Ld.getValue(1));
35565         return;
35566       }
35567       if (Subtarget.hasX87()) {
35568         // First load this into an 80-bit X87 register. This will put the whole
35569         // integer into the significand.
35570         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
35571         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
35572         SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD,
35573                                                  dl, Tys, Ops, MVT::i64,
35574                                                  Node->getMemOperand());
35575         SDValue Chain = Result.getValue(1);
35576 
35577         // Now store the X87 register to a stack temporary and convert to i64.
35578         // This store is not atomic and doesn't need to be.
35579         // FIXME: We don't need a stack temporary if the result of the load
35580         // is already being stored. We could just directly store there.
35581         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
35582         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
35583         MachinePointerInfo MPI =
35584             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
35585         SDValue StoreOps[] = { Chain, Result, StackPtr };
35586         Chain = DAG.getMemIntrinsicNode(
35587             X86ISD::FIST, dl, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
35588             MPI, std::nullopt /*Align*/, MachineMemOperand::MOStore);
35589 
35590         // Finally load the value back from the stack temporary and return it.
35591         // This load is not atomic and doesn't need to be.
35592         // This load will be further type legalized.
35593         Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
35594         Results.push_back(Result);
35595         Results.push_back(Result.getValue(1));
35596         return;
35597       }
35598     }
35599     // TODO: Use MOVLPS when SSE1 is available?
35600     // Delegate to generic TypeLegalization. Situations we can really handle
35601     // should have already been dealt with by AtomicExpandPass.cpp.
35602     break;
35603   }
35604   case ISD::ATOMIC_SWAP:
35605   case ISD::ATOMIC_LOAD_ADD:
35606   case ISD::ATOMIC_LOAD_SUB:
35607   case ISD::ATOMIC_LOAD_AND:
35608   case ISD::ATOMIC_LOAD_OR:
35609   case ISD::ATOMIC_LOAD_XOR:
35610   case ISD::ATOMIC_LOAD_NAND:
35611   case ISD::ATOMIC_LOAD_MIN:
35612   case ISD::ATOMIC_LOAD_MAX:
35613   case ISD::ATOMIC_LOAD_UMIN:
35614   case ISD::ATOMIC_LOAD_UMAX:
35615     // Delegate to generic TypeLegalization. Situations we can really handle
35616     // should have already been dealt with by AtomicExpandPass.cpp.
35617     break;
35618 
35619   case ISD::BITCAST: {
35620     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
35621     EVT DstVT = N->getValueType(0);
35622     EVT SrcVT = N->getOperand(0).getValueType();
35623 
35624     // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
35625     // we can split using the k-register rather than memory.
35626     if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
35627       assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
35628       SDValue Lo, Hi;
35629       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
35630       Lo = DAG.getBitcast(MVT::i32, Lo);
35631       Hi = DAG.getBitcast(MVT::i32, Hi);
35632       SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
35633       Results.push_back(Res);
35634       return;
35635     }
35636 
35637     if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
35638       // FIXME: Use v4f32 for SSE1?
35639       assert(Subtarget.hasSSE2() && "Requires SSE2");
35640       assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&
35641              "Unexpected type action!");
35642       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
35643       SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64,
35644                                 N->getOperand(0));
35645       Res = DAG.getBitcast(WideVT, Res);
35646       Results.push_back(Res);
35647       return;
35648     }
35649 
35650     return;
35651   }
35652   case ISD::MGATHER: {
35653     EVT VT = N->getValueType(0);
35654     if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
35655         (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
35656       auto *Gather = cast<MaskedGatherSDNode>(N);
35657       SDValue Index = Gather->getIndex();
35658       if (Index.getValueType() != MVT::v2i64)
35659         return;
35660       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
35661              "Unexpected type action!");
35662       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
35663       SDValue Mask = Gather->getMask();
35664       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
35665       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
35666                                      Gather->getPassThru(),
35667                                      DAG.getUNDEF(VT));
35668       if (!Subtarget.hasVLX()) {
35669         // We need to widen the mask, but the instruction will only use 2
35670         // of its elements. So we can use undef.
35671         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
35672                            DAG.getUNDEF(MVT::v2i1));
35673         Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
35674       }
35675       SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
35676                         Gather->getBasePtr(), Index, Gather->getScale() };
35677       SDValue Res = DAG.getMemIntrinsicNode(
35678           X86ISD::MGATHER, dl, DAG.getVTList(WideVT, MVT::Other), Ops,
35679           Gather->getMemoryVT(), Gather->getMemOperand());
35680       Results.push_back(Res);
35681       Results.push_back(Res.getValue(1));
35682       return;
35683     }
35684     return;
35685   }
35686   case ISD::LOAD: {
35687     // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
35688     // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
35689     // cast since type legalization will try to use an i64 load.
35690     MVT VT = N->getSimpleValueType(0);
35691     assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
35692     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
35693            "Unexpected type action!");
35694     if (!ISD::isNON_EXTLoad(N))
35695       return;
35696     auto *Ld = cast<LoadSDNode>(N);
35697     if (Subtarget.hasSSE2()) {
35698       MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
35699       SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
35700                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
35701                                 Ld->getMemOperand()->getFlags());
35702       SDValue Chain = Res.getValue(1);
35703       MVT VecVT = MVT::getVectorVT(LdVT, 2);
35704       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
35705       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
35706       Res = DAG.getBitcast(WideVT, Res);
35707       Results.push_back(Res);
35708       Results.push_back(Chain);
35709       return;
35710     }
35711     assert(Subtarget.hasSSE1() && "Expected SSE");
35712     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
35713     SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
35714     SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
35715                                           MVT::i64, Ld->getMemOperand());
35716     Results.push_back(Res);
35717     Results.push_back(Res.getValue(1));
35718     return;
35719   }
35720   case ISD::ADDRSPACECAST: {
35721     SDValue V = LowerADDRSPACECAST(SDValue(N,0), DAG);
35722     Results.push_back(V);
35723     return;
35724   }
35725   case ISD::BITREVERSE: {
35726     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
35727     assert(Subtarget.hasXOP() && "Expected XOP");
35728     // We can use VPPERM by copying to a vector register and back. We'll need
35729     // to move the scalar in two i32 pieces.
35730     Results.push_back(LowerBITREVERSE(SDValue(N, 0), Subtarget, DAG));
35731     return;
35732   }
35733   case ISD::EXTRACT_VECTOR_ELT: {
35734     // f16 = extract vXf16 %vec, i64 %idx
35735     assert(N->getSimpleValueType(0) == MVT::f16 &&
35736            "Unexpected Value type of EXTRACT_VECTOR_ELT!");
35737     assert(Subtarget.hasFP16() && "Expected FP16");
35738     SDValue VecOp = N->getOperand(0);
35739     EVT ExtVT = VecOp.getValueType().changeVectorElementTypeToInteger();
35740     SDValue Split = DAG.getBitcast(ExtVT, N->getOperand(0));
35741     Split = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Split,
35742                         N->getOperand(1));
35743     Split = DAG.getBitcast(MVT::f16, Split);
35744     Results.push_back(Split);
35745     return;
35746   }
35747   }
35748 }
35749 
35750 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
35751   switch ((X86ISD::NodeType)Opcode) {
35752   case X86ISD::FIRST_NUMBER:       break;
35753 #define NODE_NAME_CASE(NODE) case X86ISD::NODE: return "X86ISD::" #NODE;
35754   NODE_NAME_CASE(BSF)
35755   NODE_NAME_CASE(BSR)
35756   NODE_NAME_CASE(FSHL)
35757   NODE_NAME_CASE(FSHR)
35758   NODE_NAME_CASE(FAND)
35759   NODE_NAME_CASE(FANDN)
35760   NODE_NAME_CASE(FOR)
35761   NODE_NAME_CASE(FXOR)
35762   NODE_NAME_CASE(FILD)
35763   NODE_NAME_CASE(FIST)
35764   NODE_NAME_CASE(FP_TO_INT_IN_MEM)
35765   NODE_NAME_CASE(FLD)
35766   NODE_NAME_CASE(FST)
35767   NODE_NAME_CASE(CALL)
35768   NODE_NAME_CASE(CALL_RVMARKER)
35769   NODE_NAME_CASE(BT)
35770   NODE_NAME_CASE(CMP)
35771   NODE_NAME_CASE(FCMP)
35772   NODE_NAME_CASE(STRICT_FCMP)
35773   NODE_NAME_CASE(STRICT_FCMPS)
35774   NODE_NAME_CASE(COMI)
35775   NODE_NAME_CASE(UCOMI)
35776   NODE_NAME_CASE(CMPM)
35777   NODE_NAME_CASE(CMPMM)
35778   NODE_NAME_CASE(STRICT_CMPM)
35779   NODE_NAME_CASE(CMPMM_SAE)
35780   NODE_NAME_CASE(SETCC)
35781   NODE_NAME_CASE(SETCC_CARRY)
35782   NODE_NAME_CASE(FSETCC)
35783   NODE_NAME_CASE(FSETCCM)
35784   NODE_NAME_CASE(FSETCCM_SAE)
35785   NODE_NAME_CASE(CMOV)
35786   NODE_NAME_CASE(BRCOND)
35787   NODE_NAME_CASE(RET_GLUE)
35788   NODE_NAME_CASE(IRET)
35789   NODE_NAME_CASE(REP_STOS)
35790   NODE_NAME_CASE(REP_MOVS)
35791   NODE_NAME_CASE(GlobalBaseReg)
35792   NODE_NAME_CASE(Wrapper)
35793   NODE_NAME_CASE(WrapperRIP)
35794   NODE_NAME_CASE(MOVQ2DQ)
35795   NODE_NAME_CASE(MOVDQ2Q)
35796   NODE_NAME_CASE(MMX_MOVD2W)
35797   NODE_NAME_CASE(MMX_MOVW2D)
35798   NODE_NAME_CASE(PEXTRB)
35799   NODE_NAME_CASE(PEXTRW)
35800   NODE_NAME_CASE(INSERTPS)
35801   NODE_NAME_CASE(PINSRB)
35802   NODE_NAME_CASE(PINSRW)
35803   NODE_NAME_CASE(PSHUFB)
35804   NODE_NAME_CASE(ANDNP)
35805   NODE_NAME_CASE(BLENDI)
35806   NODE_NAME_CASE(BLENDV)
35807   NODE_NAME_CASE(HADD)
35808   NODE_NAME_CASE(HSUB)
35809   NODE_NAME_CASE(FHADD)
35810   NODE_NAME_CASE(FHSUB)
35811   NODE_NAME_CASE(CONFLICT)
35812   NODE_NAME_CASE(FMAX)
35813   NODE_NAME_CASE(FMAXS)
35814   NODE_NAME_CASE(FMAX_SAE)
35815   NODE_NAME_CASE(FMAXS_SAE)
35816   NODE_NAME_CASE(FMIN)
35817   NODE_NAME_CASE(FMINS)
35818   NODE_NAME_CASE(FMIN_SAE)
35819   NODE_NAME_CASE(FMINS_SAE)
35820   NODE_NAME_CASE(FMAXC)
35821   NODE_NAME_CASE(FMINC)
35822   NODE_NAME_CASE(FRSQRT)
35823   NODE_NAME_CASE(FRCP)
35824   NODE_NAME_CASE(EXTRQI)
35825   NODE_NAME_CASE(INSERTQI)
35826   NODE_NAME_CASE(TLSADDR)
35827   NODE_NAME_CASE(TLSBASEADDR)
35828   NODE_NAME_CASE(TLSCALL)
35829   NODE_NAME_CASE(EH_SJLJ_SETJMP)
35830   NODE_NAME_CASE(EH_SJLJ_LONGJMP)
35831   NODE_NAME_CASE(EH_SJLJ_SETUP_DISPATCH)
35832   NODE_NAME_CASE(EH_RETURN)
35833   NODE_NAME_CASE(TC_RETURN)
35834   NODE_NAME_CASE(FNSTCW16m)
35835   NODE_NAME_CASE(FLDCW16m)
35836   NODE_NAME_CASE(FNSTENVm)
35837   NODE_NAME_CASE(FLDENVm)
35838   NODE_NAME_CASE(LCMPXCHG_DAG)
35839   NODE_NAME_CASE(LCMPXCHG8_DAG)
35840   NODE_NAME_CASE(LCMPXCHG16_DAG)
35841   NODE_NAME_CASE(LCMPXCHG16_SAVE_RBX_DAG)
35842   NODE_NAME_CASE(LADD)
35843   NODE_NAME_CASE(LSUB)
35844   NODE_NAME_CASE(LOR)
35845   NODE_NAME_CASE(LXOR)
35846   NODE_NAME_CASE(LAND)
35847   NODE_NAME_CASE(LBTS)
35848   NODE_NAME_CASE(LBTC)
35849   NODE_NAME_CASE(LBTR)
35850   NODE_NAME_CASE(LBTS_RM)
35851   NODE_NAME_CASE(LBTC_RM)
35852   NODE_NAME_CASE(LBTR_RM)
35853   NODE_NAME_CASE(AADD)
35854   NODE_NAME_CASE(AOR)
35855   NODE_NAME_CASE(AXOR)
35856   NODE_NAME_CASE(AAND)
35857   NODE_NAME_CASE(VZEXT_MOVL)
35858   NODE_NAME_CASE(VZEXT_LOAD)
35859   NODE_NAME_CASE(VEXTRACT_STORE)
35860   NODE_NAME_CASE(VTRUNC)
35861   NODE_NAME_CASE(VTRUNCS)
35862   NODE_NAME_CASE(VTRUNCUS)
35863   NODE_NAME_CASE(VMTRUNC)
35864   NODE_NAME_CASE(VMTRUNCS)
35865   NODE_NAME_CASE(VMTRUNCUS)
35866   NODE_NAME_CASE(VTRUNCSTORES)
35867   NODE_NAME_CASE(VTRUNCSTOREUS)
35868   NODE_NAME_CASE(VMTRUNCSTORES)
35869   NODE_NAME_CASE(VMTRUNCSTOREUS)
35870   NODE_NAME_CASE(VFPEXT)
35871   NODE_NAME_CASE(STRICT_VFPEXT)
35872   NODE_NAME_CASE(VFPEXT_SAE)
35873   NODE_NAME_CASE(VFPEXTS)
35874   NODE_NAME_CASE(VFPEXTS_SAE)
35875   NODE_NAME_CASE(VFPROUND)
35876   NODE_NAME_CASE(STRICT_VFPROUND)
35877   NODE_NAME_CASE(VMFPROUND)
35878   NODE_NAME_CASE(VFPROUND_RND)
35879   NODE_NAME_CASE(VFPROUNDS)
35880   NODE_NAME_CASE(VFPROUNDS_RND)
35881   NODE_NAME_CASE(VSHLDQ)
35882   NODE_NAME_CASE(VSRLDQ)
35883   NODE_NAME_CASE(VSHL)
35884   NODE_NAME_CASE(VSRL)
35885   NODE_NAME_CASE(VSRA)
35886   NODE_NAME_CASE(VSHLI)
35887   NODE_NAME_CASE(VSRLI)
35888   NODE_NAME_CASE(VSRAI)
35889   NODE_NAME_CASE(VSHLV)
35890   NODE_NAME_CASE(VSRLV)
35891   NODE_NAME_CASE(VSRAV)
35892   NODE_NAME_CASE(VROTLI)
35893   NODE_NAME_CASE(VROTRI)
35894   NODE_NAME_CASE(VPPERM)
35895   NODE_NAME_CASE(CMPP)
35896   NODE_NAME_CASE(STRICT_CMPP)
35897   NODE_NAME_CASE(PCMPEQ)
35898   NODE_NAME_CASE(PCMPGT)
35899   NODE_NAME_CASE(PHMINPOS)
35900   NODE_NAME_CASE(ADD)
35901   NODE_NAME_CASE(SUB)
35902   NODE_NAME_CASE(ADC)
35903   NODE_NAME_CASE(SBB)
35904   NODE_NAME_CASE(SMUL)
35905   NODE_NAME_CASE(UMUL)
35906   NODE_NAME_CASE(OR)
35907   NODE_NAME_CASE(XOR)
35908   NODE_NAME_CASE(AND)
35909   NODE_NAME_CASE(BEXTR)
35910   NODE_NAME_CASE(BEXTRI)
35911   NODE_NAME_CASE(BZHI)
35912   NODE_NAME_CASE(PDEP)
35913   NODE_NAME_CASE(PEXT)
35914   NODE_NAME_CASE(MUL_IMM)
35915   NODE_NAME_CASE(MOVMSK)
35916   NODE_NAME_CASE(PTEST)
35917   NODE_NAME_CASE(TESTP)
35918   NODE_NAME_CASE(KORTEST)
35919   NODE_NAME_CASE(KTEST)
35920   NODE_NAME_CASE(KADD)
35921   NODE_NAME_CASE(KSHIFTL)
35922   NODE_NAME_CASE(KSHIFTR)
35923   NODE_NAME_CASE(PACKSS)
35924   NODE_NAME_CASE(PACKUS)
35925   NODE_NAME_CASE(PALIGNR)
35926   NODE_NAME_CASE(VALIGN)
35927   NODE_NAME_CASE(VSHLD)
35928   NODE_NAME_CASE(VSHRD)
35929   NODE_NAME_CASE(VSHLDV)
35930   NODE_NAME_CASE(VSHRDV)
35931   NODE_NAME_CASE(PSHUFD)
35932   NODE_NAME_CASE(PSHUFHW)
35933   NODE_NAME_CASE(PSHUFLW)
35934   NODE_NAME_CASE(SHUFP)
35935   NODE_NAME_CASE(SHUF128)
35936   NODE_NAME_CASE(MOVLHPS)
35937   NODE_NAME_CASE(MOVHLPS)
35938   NODE_NAME_CASE(MOVDDUP)
35939   NODE_NAME_CASE(MOVSHDUP)
35940   NODE_NAME_CASE(MOVSLDUP)
35941   NODE_NAME_CASE(MOVSD)
35942   NODE_NAME_CASE(MOVSS)
35943   NODE_NAME_CASE(MOVSH)
35944   NODE_NAME_CASE(UNPCKL)
35945   NODE_NAME_CASE(UNPCKH)
35946   NODE_NAME_CASE(VBROADCAST)
35947   NODE_NAME_CASE(VBROADCAST_LOAD)
35948   NODE_NAME_CASE(VBROADCASTM)
35949   NODE_NAME_CASE(SUBV_BROADCAST_LOAD)
35950   NODE_NAME_CASE(VPERMILPV)
35951   NODE_NAME_CASE(VPERMILPI)
35952   NODE_NAME_CASE(VPERM2X128)
35953   NODE_NAME_CASE(VPERMV)
35954   NODE_NAME_CASE(VPERMV3)
35955   NODE_NAME_CASE(VPERMI)
35956   NODE_NAME_CASE(VPTERNLOG)
35957   NODE_NAME_CASE(VFIXUPIMM)
35958   NODE_NAME_CASE(VFIXUPIMM_SAE)
35959   NODE_NAME_CASE(VFIXUPIMMS)
35960   NODE_NAME_CASE(VFIXUPIMMS_SAE)
35961   NODE_NAME_CASE(VRANGE)
35962   NODE_NAME_CASE(VRANGE_SAE)
35963   NODE_NAME_CASE(VRANGES)
35964   NODE_NAME_CASE(VRANGES_SAE)
35965   NODE_NAME_CASE(PMULUDQ)
35966   NODE_NAME_CASE(PMULDQ)
35967   NODE_NAME_CASE(PSADBW)
35968   NODE_NAME_CASE(DBPSADBW)
35969   NODE_NAME_CASE(VASTART_SAVE_XMM_REGS)
35970   NODE_NAME_CASE(VAARG_64)
35971   NODE_NAME_CASE(VAARG_X32)
35972   NODE_NAME_CASE(DYN_ALLOCA)
35973   NODE_NAME_CASE(MFENCE)
35974   NODE_NAME_CASE(SEG_ALLOCA)
35975   NODE_NAME_CASE(PROBED_ALLOCA)
35976   NODE_NAME_CASE(RDRAND)
35977   NODE_NAME_CASE(RDSEED)
35978   NODE_NAME_CASE(RDPKRU)
35979   NODE_NAME_CASE(WRPKRU)
35980   NODE_NAME_CASE(VPMADDUBSW)
35981   NODE_NAME_CASE(VPMADDWD)
35982   NODE_NAME_CASE(VPSHA)
35983   NODE_NAME_CASE(VPSHL)
35984   NODE_NAME_CASE(VPCOM)
35985   NODE_NAME_CASE(VPCOMU)
35986   NODE_NAME_CASE(VPERMIL2)
35987   NODE_NAME_CASE(FMSUB)
35988   NODE_NAME_CASE(STRICT_FMSUB)
35989   NODE_NAME_CASE(FNMADD)
35990   NODE_NAME_CASE(STRICT_FNMADD)
35991   NODE_NAME_CASE(FNMSUB)
35992   NODE_NAME_CASE(STRICT_FNMSUB)
35993   NODE_NAME_CASE(FMADDSUB)
35994   NODE_NAME_CASE(FMSUBADD)
35995   NODE_NAME_CASE(FMADD_RND)
35996   NODE_NAME_CASE(FNMADD_RND)
35997   NODE_NAME_CASE(FMSUB_RND)
35998   NODE_NAME_CASE(FNMSUB_RND)
35999   NODE_NAME_CASE(FMADDSUB_RND)
36000   NODE_NAME_CASE(FMSUBADD_RND)
36001   NODE_NAME_CASE(VFMADDC)
36002   NODE_NAME_CASE(VFMADDC_RND)
36003   NODE_NAME_CASE(VFCMADDC)
36004   NODE_NAME_CASE(VFCMADDC_RND)
36005   NODE_NAME_CASE(VFMULC)
36006   NODE_NAME_CASE(VFMULC_RND)
36007   NODE_NAME_CASE(VFCMULC)
36008   NODE_NAME_CASE(VFCMULC_RND)
36009   NODE_NAME_CASE(VFMULCSH)
36010   NODE_NAME_CASE(VFMULCSH_RND)
36011   NODE_NAME_CASE(VFCMULCSH)
36012   NODE_NAME_CASE(VFCMULCSH_RND)
36013   NODE_NAME_CASE(VFMADDCSH)
36014   NODE_NAME_CASE(VFMADDCSH_RND)
36015   NODE_NAME_CASE(VFCMADDCSH)
36016   NODE_NAME_CASE(VFCMADDCSH_RND)
36017   NODE_NAME_CASE(VPMADD52H)
36018   NODE_NAME_CASE(VPMADD52L)
36019   NODE_NAME_CASE(VRNDSCALE)
36020   NODE_NAME_CASE(STRICT_VRNDSCALE)
36021   NODE_NAME_CASE(VRNDSCALE_SAE)
36022   NODE_NAME_CASE(VRNDSCALES)
36023   NODE_NAME_CASE(VRNDSCALES_SAE)
36024   NODE_NAME_CASE(VREDUCE)
36025   NODE_NAME_CASE(VREDUCE_SAE)
36026   NODE_NAME_CASE(VREDUCES)
36027   NODE_NAME_CASE(VREDUCES_SAE)
36028   NODE_NAME_CASE(VGETMANT)
36029   NODE_NAME_CASE(VGETMANT_SAE)
36030   NODE_NAME_CASE(VGETMANTS)
36031   NODE_NAME_CASE(VGETMANTS_SAE)
36032   NODE_NAME_CASE(PCMPESTR)
36033   NODE_NAME_CASE(PCMPISTR)
36034   NODE_NAME_CASE(XTEST)
36035   NODE_NAME_CASE(COMPRESS)
36036   NODE_NAME_CASE(EXPAND)
36037   NODE_NAME_CASE(SELECTS)
36038   NODE_NAME_CASE(ADDSUB)
36039   NODE_NAME_CASE(RCP14)
36040   NODE_NAME_CASE(RCP14S)
36041   NODE_NAME_CASE(RCP28)
36042   NODE_NAME_CASE(RCP28_SAE)
36043   NODE_NAME_CASE(RCP28S)
36044   NODE_NAME_CASE(RCP28S_SAE)
36045   NODE_NAME_CASE(EXP2)
36046   NODE_NAME_CASE(EXP2_SAE)
36047   NODE_NAME_CASE(RSQRT14)
36048   NODE_NAME_CASE(RSQRT14S)
36049   NODE_NAME_CASE(RSQRT28)
36050   NODE_NAME_CASE(RSQRT28_SAE)
36051   NODE_NAME_CASE(RSQRT28S)
36052   NODE_NAME_CASE(RSQRT28S_SAE)
36053   NODE_NAME_CASE(FADD_RND)
36054   NODE_NAME_CASE(FADDS)
36055   NODE_NAME_CASE(FADDS_RND)
36056   NODE_NAME_CASE(FSUB_RND)
36057   NODE_NAME_CASE(FSUBS)
36058   NODE_NAME_CASE(FSUBS_RND)
36059   NODE_NAME_CASE(FMUL_RND)
36060   NODE_NAME_CASE(FMULS)
36061   NODE_NAME_CASE(FMULS_RND)
36062   NODE_NAME_CASE(FDIV_RND)
36063   NODE_NAME_CASE(FDIVS)
36064   NODE_NAME_CASE(FDIVS_RND)
36065   NODE_NAME_CASE(FSQRT_RND)
36066   NODE_NAME_CASE(FSQRTS)
36067   NODE_NAME_CASE(FSQRTS_RND)
36068   NODE_NAME_CASE(FGETEXP)
36069   NODE_NAME_CASE(FGETEXP_SAE)
36070   NODE_NAME_CASE(FGETEXPS)
36071   NODE_NAME_CASE(FGETEXPS_SAE)
36072   NODE_NAME_CASE(SCALEF)
36073   NODE_NAME_CASE(SCALEF_RND)
36074   NODE_NAME_CASE(SCALEFS)
36075   NODE_NAME_CASE(SCALEFS_RND)
36076   NODE_NAME_CASE(MULHRS)
36077   NODE_NAME_CASE(SINT_TO_FP_RND)
36078   NODE_NAME_CASE(UINT_TO_FP_RND)
36079   NODE_NAME_CASE(CVTTP2SI)
36080   NODE_NAME_CASE(CVTTP2UI)
36081   NODE_NAME_CASE(STRICT_CVTTP2SI)
36082   NODE_NAME_CASE(STRICT_CVTTP2UI)
36083   NODE_NAME_CASE(MCVTTP2SI)
36084   NODE_NAME_CASE(MCVTTP2UI)
36085   NODE_NAME_CASE(CVTTP2SI_SAE)
36086   NODE_NAME_CASE(CVTTP2UI_SAE)
36087   NODE_NAME_CASE(CVTTS2SI)
36088   NODE_NAME_CASE(CVTTS2UI)
36089   NODE_NAME_CASE(CVTTS2SI_SAE)
36090   NODE_NAME_CASE(CVTTS2UI_SAE)
36091   NODE_NAME_CASE(CVTSI2P)
36092   NODE_NAME_CASE(CVTUI2P)
36093   NODE_NAME_CASE(STRICT_CVTSI2P)
36094   NODE_NAME_CASE(STRICT_CVTUI2P)
36095   NODE_NAME_CASE(MCVTSI2P)
36096   NODE_NAME_CASE(MCVTUI2P)
36097   NODE_NAME_CASE(VFPCLASS)
36098   NODE_NAME_CASE(VFPCLASSS)
36099   NODE_NAME_CASE(MULTISHIFT)
36100   NODE_NAME_CASE(SCALAR_SINT_TO_FP)
36101   NODE_NAME_CASE(SCALAR_SINT_TO_FP_RND)
36102   NODE_NAME_CASE(SCALAR_UINT_TO_FP)
36103   NODE_NAME_CASE(SCALAR_UINT_TO_FP_RND)
36104   NODE_NAME_CASE(CVTPS2PH)
36105   NODE_NAME_CASE(STRICT_CVTPS2PH)
36106   NODE_NAME_CASE(CVTPS2PH_SAE)
36107   NODE_NAME_CASE(MCVTPS2PH)
36108   NODE_NAME_CASE(MCVTPS2PH_SAE)
36109   NODE_NAME_CASE(CVTPH2PS)
36110   NODE_NAME_CASE(STRICT_CVTPH2PS)
36111   NODE_NAME_CASE(CVTPH2PS_SAE)
36112   NODE_NAME_CASE(CVTP2SI)
36113   NODE_NAME_CASE(CVTP2UI)
36114   NODE_NAME_CASE(MCVTP2SI)
36115   NODE_NAME_CASE(MCVTP2UI)
36116   NODE_NAME_CASE(CVTP2SI_RND)
36117   NODE_NAME_CASE(CVTP2UI_RND)
36118   NODE_NAME_CASE(CVTS2SI)
36119   NODE_NAME_CASE(CVTS2UI)
36120   NODE_NAME_CASE(CVTS2SI_RND)
36121   NODE_NAME_CASE(CVTS2UI_RND)
36122   NODE_NAME_CASE(CVTNE2PS2BF16)
36123   NODE_NAME_CASE(CVTNEPS2BF16)
36124   NODE_NAME_CASE(MCVTNEPS2BF16)
36125   NODE_NAME_CASE(DPBF16PS)
36126   NODE_NAME_CASE(LWPINS)
36127   NODE_NAME_CASE(MGATHER)
36128   NODE_NAME_CASE(MSCATTER)
36129   NODE_NAME_CASE(VPDPBUSD)
36130   NODE_NAME_CASE(VPDPBUSDS)
36131   NODE_NAME_CASE(VPDPWSSD)
36132   NODE_NAME_CASE(VPDPWSSDS)
36133   NODE_NAME_CASE(VPSHUFBITQMB)
36134   NODE_NAME_CASE(GF2P8MULB)
36135   NODE_NAME_CASE(GF2P8AFFINEQB)
36136   NODE_NAME_CASE(GF2P8AFFINEINVQB)
36137   NODE_NAME_CASE(NT_CALL)
36138   NODE_NAME_CASE(NT_BRIND)
36139   NODE_NAME_CASE(UMWAIT)
36140   NODE_NAME_CASE(TPAUSE)
36141   NODE_NAME_CASE(ENQCMD)
36142   NODE_NAME_CASE(ENQCMDS)
36143   NODE_NAME_CASE(VP2INTERSECT)
36144   NODE_NAME_CASE(VPDPBSUD)
36145   NODE_NAME_CASE(VPDPBSUDS)
36146   NODE_NAME_CASE(VPDPBUUD)
36147   NODE_NAME_CASE(VPDPBUUDS)
36148   NODE_NAME_CASE(VPDPBSSD)
36149   NODE_NAME_CASE(VPDPBSSDS)
36150   NODE_NAME_CASE(AESENC128KL)
36151   NODE_NAME_CASE(AESDEC128KL)
36152   NODE_NAME_CASE(AESENC256KL)
36153   NODE_NAME_CASE(AESDEC256KL)
36154   NODE_NAME_CASE(AESENCWIDE128KL)
36155   NODE_NAME_CASE(AESDECWIDE128KL)
36156   NODE_NAME_CASE(AESENCWIDE256KL)
36157   NODE_NAME_CASE(AESDECWIDE256KL)
36158   NODE_NAME_CASE(CMPCCXADD)
36159   NODE_NAME_CASE(TESTUI)
36160   NODE_NAME_CASE(FP80_ADD)
36161   NODE_NAME_CASE(STRICT_FP80_ADD)
36162   }
36163   return nullptr;
36164 #undef NODE_NAME_CASE
36165 }
36166 
36167 /// Return true if the addressing mode represented by AM is legal for this
36168 /// target, for a load/store of the specified type.
36169 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
36170                                               const AddrMode &AM, Type *Ty,
36171                                               unsigned AS,
36172                                               Instruction *I) const {
36173   // X86 supports extremely general addressing modes.
36174   CodeModel::Model M = getTargetMachine().getCodeModel();
36175 
36176   // X86 allows a sign-extended 32-bit immediate field as a displacement.
36177   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
36178     return false;
36179 
36180   if (AM.BaseGV) {
36181     unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
36182 
36183     // If a reference to this global requires an extra load, we can't fold it.
36184     if (isGlobalStubReference(GVFlags))
36185       return false;
36186 
36187     // If BaseGV requires a register for the PIC base, we cannot also have a
36188     // BaseReg specified.
36189     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
36190       return false;
36191 
36192     // If lower 4G is not available, then we must use rip-relative addressing.
36193     if ((M != CodeModel::Small || isPositionIndependent()) &&
36194         Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
36195       return false;
36196   }
36197 
36198   switch (AM.Scale) {
36199   case 0:
36200   case 1:
36201   case 2:
36202   case 4:
36203   case 8:
36204     // These scales always work.
36205     break;
36206   case 3:
36207   case 5:
36208   case 9:
36209     // These scales are formed with basereg+scalereg.  Only accept if there is
36210     // no basereg yet.
36211     if (AM.HasBaseReg)
36212       return false;
36213     break;
36214   default:  // Other stuff never works.
36215     return false;
36216   }
36217 
36218   return true;
36219 }
36220 
36221 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
36222   unsigned Bits = Ty->getScalarSizeInBits();
36223 
36224   // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
36225   // Splitting for v32i8/v16i16 on XOP+AVX2 targets is still preferred.
36226   if (Subtarget.hasXOP() &&
36227       (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
36228     return false;
36229 
36230   // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
36231   // shifts just as cheap as scalar ones.
36232   if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
36233     return false;
36234 
36235   // AVX512BW has shifts such as vpsllvw.
36236   if (Subtarget.hasBWI() && Bits == 16)
36237     return false;
36238 
36239   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
36240   // fully general vector.
36241   return true;
36242 }
36243 
36244 bool X86TargetLowering::isBinOp(unsigned Opcode) const {
36245   switch (Opcode) {
36246   // These are non-commutative binops.
36247   // TODO: Add more X86ISD opcodes once we have test coverage.
36248   case X86ISD::ANDNP:
36249   case X86ISD::PCMPGT:
36250   case X86ISD::FMAX:
36251   case X86ISD::FMIN:
36252   case X86ISD::FANDN:
36253   case X86ISD::VPSHA:
36254   case X86ISD::VPSHL:
36255   case X86ISD::VSHLV:
36256   case X86ISD::VSRLV:
36257   case X86ISD::VSRAV:
36258     return true;
36259   }
36260 
36261   return TargetLoweringBase::isBinOp(Opcode);
36262 }
36263 
36264 bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
36265   switch (Opcode) {
36266   // TODO: Add more X86ISD opcodes once we have test coverage.
36267   case X86ISD::PCMPEQ:
36268   case X86ISD::PMULDQ:
36269   case X86ISD::PMULUDQ:
36270   case X86ISD::FMAXC:
36271   case X86ISD::FMINC:
36272   case X86ISD::FAND:
36273   case X86ISD::FOR:
36274   case X86ISD::FXOR:
36275     return true;
36276   }
36277 
36278   return TargetLoweringBase::isCommutativeBinOp(Opcode);
36279 }
36280 
36281 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
36282   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
36283     return false;
36284   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
36285   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
36286   return NumBits1 > NumBits2;
36287 }
36288 
36289 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
36290   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
36291     return false;
36292 
36293   if (!isTypeLegal(EVT::getEVT(Ty1)))
36294     return false;
36295 
36296   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
36297 
36298   // Assuming the caller doesn't have a zeroext or signext return parameter,
36299   // truncation all the way down to i1 is valid.
36300   return true;
36301 }
36302 
36303 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
36304   return isInt<32>(Imm);
36305 }
36306 
36307 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
36308   // Can also use sub to handle negated immediates.
36309   return isInt<32>(Imm);
36310 }
36311 
36312 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
36313   return isInt<32>(Imm);
36314 }
36315 
36316 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
36317   if (!VT1.isScalarInteger() || !VT2.isScalarInteger())
36318     return false;
36319   unsigned NumBits1 = VT1.getSizeInBits();
36320   unsigned NumBits2 = VT2.getSizeInBits();
36321   return NumBits1 > NumBits2;
36322 }
36323 
36324 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
36325   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
36326   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
36327 }
36328 
36329 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
36330   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
36331   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
36332 }
36333 
36334 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
36335   EVT VT1 = Val.getValueType();
36336   if (isZExtFree(VT1, VT2))
36337     return true;
36338 
36339   if (Val.getOpcode() != ISD::LOAD)
36340     return false;
36341 
36342   if (!VT1.isSimple() || !VT1.isInteger() ||
36343       !VT2.isSimple() || !VT2.isInteger())
36344     return false;
36345 
36346   switch (VT1.getSimpleVT().SimpleTy) {
36347   default: break;
36348   case MVT::i8:
36349   case MVT::i16:
36350   case MVT::i32:
36351     // X86 has 8, 16, and 32-bit zero-extending loads.
36352     return true;
36353   }
36354 
36355   return false;
36356 }
36357 
36358 bool X86TargetLowering::shouldSinkOperands(Instruction *I,
36359                                            SmallVectorImpl<Use *> &Ops) const {
36360   using namespace llvm::PatternMatch;
36361 
36362   FixedVectorType *VTy = dyn_cast<FixedVectorType>(I->getType());
36363   if (!VTy)
36364     return false;
36365 
36366   if (I->getOpcode() == Instruction::Mul &&
36367       VTy->getElementType()->isIntegerTy(64)) {
36368     for (auto &Op : I->operands()) {
36369       // Make sure we are not already sinking this operand
36370       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
36371         continue;
36372 
36373       // Look for PMULDQ pattern where the input is a sext_inreg from vXi32 or
36374       // the PMULUDQ pattern where the input is a zext_inreg from vXi32.
36375       if (Subtarget.hasSSE41() &&
36376           match(Op.get(), m_AShr(m_Shl(m_Value(), m_SpecificInt(32)),
36377                                  m_SpecificInt(32)))) {
36378         Ops.push_back(&cast<Instruction>(Op)->getOperandUse(0));
36379         Ops.push_back(&Op);
36380       } else if (Subtarget.hasSSE2() &&
36381                  match(Op.get(),
36382                        m_And(m_Value(), m_SpecificInt(UINT64_C(0xffffffff))))) {
36383         Ops.push_back(&Op);
36384       }
36385     }
36386 
36387     return !Ops.empty();
36388   }
36389 
36390   // A uniform shift amount in a vector shift or funnel shift may be much
36391   // cheaper than a generic variable vector shift, so make that pattern visible
36392   // to SDAG by sinking the shuffle instruction next to the shift.
36393   int ShiftAmountOpNum = -1;
36394   if (I->isShift())
36395     ShiftAmountOpNum = 1;
36396   else if (auto *II = dyn_cast<IntrinsicInst>(I)) {
36397     if (II->getIntrinsicID() == Intrinsic::fshl ||
36398         II->getIntrinsicID() == Intrinsic::fshr)
36399       ShiftAmountOpNum = 2;
36400   }
36401 
36402   if (ShiftAmountOpNum == -1)
36403     return false;
36404 
36405   auto *Shuf = dyn_cast<ShuffleVectorInst>(I->getOperand(ShiftAmountOpNum));
36406   if (Shuf && getSplatIndex(Shuf->getShuffleMask()) >= 0 &&
36407       isVectorShiftByScalarCheap(I->getType())) {
36408     Ops.push_back(&I->getOperandUse(ShiftAmountOpNum));
36409     return true;
36410   }
36411 
36412   return false;
36413 }
36414 
36415 bool X86TargetLowering::shouldConvertPhiType(Type *From, Type *To) const {
36416   if (!Subtarget.is64Bit())
36417     return false;
36418   return TargetLowering::shouldConvertPhiType(From, To);
36419 }
36420 
36421 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
36422   if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
36423     return false;
36424 
36425   EVT SrcVT = ExtVal.getOperand(0).getValueType();
36426 
36427   // There is no extending load for vXi1.
36428   if (SrcVT.getScalarType() == MVT::i1)
36429     return false;
36430 
36431   return true;
36432 }
36433 
36434 bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
36435                                                    EVT VT) const {
36436   if (!Subtarget.hasAnyFMA())
36437     return false;
36438 
36439   VT = VT.getScalarType();
36440 
36441   if (!VT.isSimple())
36442     return false;
36443 
36444   switch (VT.getSimpleVT().SimpleTy) {
36445   case MVT::f16:
36446     return Subtarget.hasFP16();
36447   case MVT::f32:
36448   case MVT::f64:
36449     return true;
36450   default:
36451     break;
36452   }
36453 
36454   return false;
36455 }
36456 
36457 bool X86TargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
36458   // i16 instructions are longer (0x66 prefix) and potentially slower.
36459   return !(SrcVT == MVT::i32 && DestVT == MVT::i16);
36460 }
36461 
36462 bool X86TargetLowering::shouldFoldSelectWithIdentityConstant(unsigned Opcode,
36463                                                              EVT VT) const {
36464   // TODO: This is too general. There are cases where pre-AVX512 codegen would
36465   //       benefit. The transform may also be profitable for scalar code.
36466   if (!Subtarget.hasAVX512())
36467     return false;
36468   if (!Subtarget.hasVLX() && !VT.is512BitVector())
36469     return false;
36470   if (!VT.isVector() || VT.getScalarType() == MVT::i1)
36471     return false;
36472 
36473   return true;
36474 }
36475 
36476 /// Targets can use this to indicate that they only support *some*
36477 /// VECTOR_SHUFFLE operations, those with specific masks.
36478 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
36479 /// are assumed to be legal.
36480 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
36481   if (!VT.isSimple())
36482     return false;
36483 
36484   // Not for i1 vectors
36485   if (VT.getSimpleVT().getScalarType() == MVT::i1)
36486     return false;
36487 
36488   // Very little shuffling can be done for 64-bit vectors right now.
36489   if (VT.getSimpleVT().getSizeInBits() == 64)
36490     return false;
36491 
36492   // We only care that the types being shuffled are legal. The lowering can
36493   // handle any possible shuffle mask that results.
36494   return isTypeLegal(VT.getSimpleVT());
36495 }
36496 
36497 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
36498                                                EVT VT) const {
36499   // Don't convert an 'and' into a shuffle that we don't directly support.
36500   // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
36501   if (!Subtarget.hasAVX2())
36502     if (VT == MVT::v32i8 || VT == MVT::v16i16)
36503       return false;
36504 
36505   // Just delegate to the generic legality, clear masks aren't special.
36506   return isShuffleMaskLegal(Mask, VT);
36507 }
36508 
36509 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
36510   // If the subtarget is using thunks, we need to not generate jump tables.
36511   if (Subtarget.useIndirectThunkBranches())
36512     return false;
36513 
36514   // Otherwise, fallback on the generic logic.
36515   return TargetLowering::areJTsAllowed(Fn);
36516 }
36517 
36518 MVT X86TargetLowering::getPreferredSwitchConditionType(LLVMContext &Context,
36519                                                        EVT ConditionVT) const {
36520   // Avoid 8 and 16 bit types because they increase the chance for unnecessary
36521   // zero-extensions.
36522   if (ConditionVT.getSizeInBits() < 32)
36523     return MVT::i32;
36524   return TargetLoweringBase::getPreferredSwitchConditionType(Context,
36525                                                              ConditionVT);
36526 }
36527 
36528 //===----------------------------------------------------------------------===//
36529 //                           X86 Scheduler Hooks
36530 //===----------------------------------------------------------------------===//
36531 
36532 // Returns true if EFLAG is consumed after this iterator in the rest of the
36533 // basic block or any successors of the basic block.
36534 static bool isEFLAGSLiveAfter(MachineBasicBlock::iterator Itr,
36535                               MachineBasicBlock *BB) {
36536   // Scan forward through BB for a use/def of EFLAGS.
36537   for (const MachineInstr &mi : llvm::make_range(std::next(Itr), BB->end())) {
36538     if (mi.readsRegister(X86::EFLAGS))
36539       return true;
36540     // If we found a def, we can stop searching.
36541     if (mi.definesRegister(X86::EFLAGS))
36542       return false;
36543   }
36544 
36545   // If we hit the end of the block, check whether EFLAGS is live into a
36546   // successor.
36547   for (MachineBasicBlock *Succ : BB->successors())
36548     if (Succ->isLiveIn(X86::EFLAGS))
36549       return true;
36550 
36551   return false;
36552 }
36553 
36554 /// Utility function to emit xbegin specifying the start of an RTM region.
36555 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
36556                                      const TargetInstrInfo *TII) {
36557   const MIMetadata MIMD(MI);
36558 
36559   const BasicBlock *BB = MBB->getBasicBlock();
36560   MachineFunction::iterator I = ++MBB->getIterator();
36561 
36562   // For the v = xbegin(), we generate
36563   //
36564   // thisMBB:
36565   //  xbegin sinkMBB
36566   //
36567   // mainMBB:
36568   //  s0 = -1
36569   //
36570   // fallBB:
36571   //  eax = # XABORT_DEF
36572   //  s1 = eax
36573   //
36574   // sinkMBB:
36575   //  v = phi(s0/mainBB, s1/fallBB)
36576 
36577   MachineBasicBlock *thisMBB = MBB;
36578   MachineFunction *MF = MBB->getParent();
36579   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
36580   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
36581   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
36582   MF->insert(I, mainMBB);
36583   MF->insert(I, fallMBB);
36584   MF->insert(I, sinkMBB);
36585 
36586   if (isEFLAGSLiveAfter(MI, MBB)) {
36587     mainMBB->addLiveIn(X86::EFLAGS);
36588     fallMBB->addLiveIn(X86::EFLAGS);
36589     sinkMBB->addLiveIn(X86::EFLAGS);
36590   }
36591 
36592   // Transfer the remainder of BB and its successor edges to sinkMBB.
36593   sinkMBB->splice(sinkMBB->begin(), MBB,
36594                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
36595   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
36596 
36597   MachineRegisterInfo &MRI = MF->getRegInfo();
36598   Register DstReg = MI.getOperand(0).getReg();
36599   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
36600   Register mainDstReg = MRI.createVirtualRegister(RC);
36601   Register fallDstReg = MRI.createVirtualRegister(RC);
36602 
36603   // thisMBB:
36604   //  xbegin fallMBB
36605   //  # fallthrough to mainMBB
36606   //  # abortion to fallMBB
36607   BuildMI(thisMBB, MIMD, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
36608   thisMBB->addSuccessor(mainMBB);
36609   thisMBB->addSuccessor(fallMBB);
36610 
36611   // mainMBB:
36612   //  mainDstReg := -1
36613   BuildMI(mainMBB, MIMD, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
36614   BuildMI(mainMBB, MIMD, TII->get(X86::JMP_1)).addMBB(sinkMBB);
36615   mainMBB->addSuccessor(sinkMBB);
36616 
36617   // fallMBB:
36618   //  ; pseudo instruction to model hardware's definition from XABORT
36619   //  EAX := XABORT_DEF
36620   //  fallDstReg := EAX
36621   BuildMI(fallMBB, MIMD, TII->get(X86::XABORT_DEF));
36622   BuildMI(fallMBB, MIMD, TII->get(TargetOpcode::COPY), fallDstReg)
36623       .addReg(X86::EAX);
36624   fallMBB->addSuccessor(sinkMBB);
36625 
36626   // sinkMBB:
36627   //  DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
36628   BuildMI(*sinkMBB, sinkMBB->begin(), MIMD, TII->get(X86::PHI), DstReg)
36629       .addReg(mainDstReg).addMBB(mainMBB)
36630       .addReg(fallDstReg).addMBB(fallMBB);
36631 
36632   MI.eraseFromParent();
36633   return sinkMBB;
36634 }
36635 
36636 MachineBasicBlock *
36637 X86TargetLowering::EmitVAARGWithCustomInserter(MachineInstr &MI,
36638                                                MachineBasicBlock *MBB) const {
36639   // Emit va_arg instruction on X86-64.
36640 
36641   // Operands to this pseudo-instruction:
36642   // 0  ) Output        : destination address (reg)
36643   // 1-5) Input         : va_list address (addr, i64mem)
36644   // 6  ) ArgSize       : Size (in bytes) of vararg type
36645   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
36646   // 8  ) Align         : Alignment of type
36647   // 9  ) EFLAGS (implicit-def)
36648 
36649   assert(MI.getNumOperands() == 10 && "VAARG should have 10 operands!");
36650   static_assert(X86::AddrNumOperands == 5, "VAARG assumes 5 address operands");
36651 
36652   Register DestReg = MI.getOperand(0).getReg();
36653   MachineOperand &Base = MI.getOperand(1);
36654   MachineOperand &Scale = MI.getOperand(2);
36655   MachineOperand &Index = MI.getOperand(3);
36656   MachineOperand &Disp = MI.getOperand(4);
36657   MachineOperand &Segment = MI.getOperand(5);
36658   unsigned ArgSize = MI.getOperand(6).getImm();
36659   unsigned ArgMode = MI.getOperand(7).getImm();
36660   Align Alignment = Align(MI.getOperand(8).getImm());
36661 
36662   MachineFunction *MF = MBB->getParent();
36663 
36664   // Memory Reference
36665   assert(MI.hasOneMemOperand() && "Expected VAARG to have one memoperand");
36666 
36667   MachineMemOperand *OldMMO = MI.memoperands().front();
36668 
36669   // Clone the MMO into two separate MMOs for loading and storing
36670   MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
36671       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
36672   MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
36673       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
36674 
36675   // Machine Information
36676   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
36677   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
36678   const TargetRegisterClass *AddrRegClass =
36679       getRegClassFor(getPointerTy(MBB->getParent()->getDataLayout()));
36680   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
36681   const MIMetadata MIMD(MI);
36682 
36683   // struct va_list {
36684   //   i32   gp_offset
36685   //   i32   fp_offset
36686   //   i64   overflow_area (address)
36687   //   i64   reg_save_area (address)
36688   // }
36689   // sizeof(va_list) = 24
36690   // alignment(va_list) = 8
36691 
36692   unsigned TotalNumIntRegs = 6;
36693   unsigned TotalNumXMMRegs = 8;
36694   bool UseGPOffset = (ArgMode == 1);
36695   bool UseFPOffset = (ArgMode == 2);
36696   unsigned MaxOffset = TotalNumIntRegs * 8 +
36697                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
36698 
36699   /* Align ArgSize to a multiple of 8 */
36700   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
36701   bool NeedsAlign = (Alignment > 8);
36702 
36703   MachineBasicBlock *thisMBB = MBB;
36704   MachineBasicBlock *overflowMBB;
36705   MachineBasicBlock *offsetMBB;
36706   MachineBasicBlock *endMBB;
36707 
36708   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
36709   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
36710   unsigned OffsetReg = 0;
36711 
36712   if (!UseGPOffset && !UseFPOffset) {
36713     // If we only pull from the overflow region, we don't create a branch.
36714     // We don't need to alter control flow.
36715     OffsetDestReg = 0; // unused
36716     OverflowDestReg = DestReg;
36717 
36718     offsetMBB = nullptr;
36719     overflowMBB = thisMBB;
36720     endMBB = thisMBB;
36721   } else {
36722     // First emit code to check if gp_offset (or fp_offset) is below the bound.
36723     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
36724     // If not, pull from overflow_area. (branch to overflowMBB)
36725     //
36726     //       thisMBB
36727     //         |     .
36728     //         |        .
36729     //     offsetMBB   overflowMBB
36730     //         |        .
36731     //         |     .
36732     //        endMBB
36733 
36734     // Registers for the PHI in endMBB
36735     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
36736     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
36737 
36738     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
36739     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
36740     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
36741     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
36742 
36743     MachineFunction::iterator MBBIter = ++MBB->getIterator();
36744 
36745     // Insert the new basic blocks
36746     MF->insert(MBBIter, offsetMBB);
36747     MF->insert(MBBIter, overflowMBB);
36748     MF->insert(MBBIter, endMBB);
36749 
36750     // Transfer the remainder of MBB and its successor edges to endMBB.
36751     endMBB->splice(endMBB->begin(), thisMBB,
36752                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
36753     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
36754 
36755     // Make offsetMBB and overflowMBB successors of thisMBB
36756     thisMBB->addSuccessor(offsetMBB);
36757     thisMBB->addSuccessor(overflowMBB);
36758 
36759     // endMBB is a successor of both offsetMBB and overflowMBB
36760     offsetMBB->addSuccessor(endMBB);
36761     overflowMBB->addSuccessor(endMBB);
36762 
36763     // Load the offset value into a register
36764     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
36765     BuildMI(thisMBB, MIMD, TII->get(X86::MOV32rm), OffsetReg)
36766         .add(Base)
36767         .add(Scale)
36768         .add(Index)
36769         .addDisp(Disp, UseFPOffset ? 4 : 0)
36770         .add(Segment)
36771         .setMemRefs(LoadOnlyMMO);
36772 
36773     // Check if there is enough room left to pull this argument.
36774     BuildMI(thisMBB, MIMD, TII->get(X86::CMP32ri))
36775       .addReg(OffsetReg)
36776       .addImm(MaxOffset + 8 - ArgSizeA8);
36777 
36778     // Branch to "overflowMBB" if offset >= max
36779     // Fall through to "offsetMBB" otherwise
36780     BuildMI(thisMBB, MIMD, TII->get(X86::JCC_1))
36781       .addMBB(overflowMBB).addImm(X86::COND_AE);
36782   }
36783 
36784   // In offsetMBB, emit code to use the reg_save_area.
36785   if (offsetMBB) {
36786     assert(OffsetReg != 0);
36787 
36788     // Read the reg_save_area address.
36789     Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
36790     BuildMI(
36791         offsetMBB, MIMD,
36792         TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
36793         RegSaveReg)
36794         .add(Base)
36795         .add(Scale)
36796         .add(Index)
36797         .addDisp(Disp, Subtarget.isTarget64BitLP64() ? 16 : 12)
36798         .add(Segment)
36799         .setMemRefs(LoadOnlyMMO);
36800 
36801     if (Subtarget.isTarget64BitLP64()) {
36802       // Zero-extend the offset
36803       Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
36804       BuildMI(offsetMBB, MIMD, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
36805           .addImm(0)
36806           .addReg(OffsetReg)
36807           .addImm(X86::sub_32bit);
36808 
36809       // Add the offset to the reg_save_area to get the final address.
36810       BuildMI(offsetMBB, MIMD, TII->get(X86::ADD64rr), OffsetDestReg)
36811           .addReg(OffsetReg64)
36812           .addReg(RegSaveReg);
36813     } else {
36814       // Add the offset to the reg_save_area to get the final address.
36815       BuildMI(offsetMBB, MIMD, TII->get(X86::ADD32rr), OffsetDestReg)
36816           .addReg(OffsetReg)
36817           .addReg(RegSaveReg);
36818     }
36819 
36820     // Compute the offset for the next argument
36821     Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
36822     BuildMI(offsetMBB, MIMD, TII->get(X86::ADD32ri), NextOffsetReg)
36823       .addReg(OffsetReg)
36824       .addImm(UseFPOffset ? 16 : 8);
36825 
36826     // Store it back into the va_list.
36827     BuildMI(offsetMBB, MIMD, TII->get(X86::MOV32mr))
36828         .add(Base)
36829         .add(Scale)
36830         .add(Index)
36831         .addDisp(Disp, UseFPOffset ? 4 : 0)
36832         .add(Segment)
36833         .addReg(NextOffsetReg)
36834         .setMemRefs(StoreOnlyMMO);
36835 
36836     // Jump to endMBB
36837     BuildMI(offsetMBB, MIMD, TII->get(X86::JMP_1))
36838       .addMBB(endMBB);
36839   }
36840 
36841   //
36842   // Emit code to use overflow area
36843   //
36844 
36845   // Load the overflow_area address into a register.
36846   Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
36847   BuildMI(overflowMBB, MIMD,
36848           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
36849           OverflowAddrReg)
36850       .add(Base)
36851       .add(Scale)
36852       .add(Index)
36853       .addDisp(Disp, 8)
36854       .add(Segment)
36855       .setMemRefs(LoadOnlyMMO);
36856 
36857   // If we need to align it, do so. Otherwise, just copy the address
36858   // to OverflowDestReg.
36859   if (NeedsAlign) {
36860     // Align the overflow address
36861     Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
36862 
36863     // aligned_addr = (addr + (align-1)) & ~(align-1)
36864     BuildMI(
36865         overflowMBB, MIMD,
36866         TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
36867         TmpReg)
36868         .addReg(OverflowAddrReg)
36869         .addImm(Alignment.value() - 1);
36870 
36871     BuildMI(
36872         overflowMBB, MIMD,
36873         TII->get(Subtarget.isTarget64BitLP64() ? X86::AND64ri32 : X86::AND32ri),
36874         OverflowDestReg)
36875         .addReg(TmpReg)
36876         .addImm(~(uint64_t)(Alignment.value() - 1));
36877   } else {
36878     BuildMI(overflowMBB, MIMD, TII->get(TargetOpcode::COPY), OverflowDestReg)
36879       .addReg(OverflowAddrReg);
36880   }
36881 
36882   // Compute the next overflow address after this argument.
36883   // (the overflow address should be kept 8-byte aligned)
36884   Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
36885   BuildMI(
36886       overflowMBB, MIMD,
36887       TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
36888       NextAddrReg)
36889       .addReg(OverflowDestReg)
36890       .addImm(ArgSizeA8);
36891 
36892   // Store the new overflow address.
36893   BuildMI(overflowMBB, MIMD,
36894           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64mr : X86::MOV32mr))
36895       .add(Base)
36896       .add(Scale)
36897       .add(Index)
36898       .addDisp(Disp, 8)
36899       .add(Segment)
36900       .addReg(NextAddrReg)
36901       .setMemRefs(StoreOnlyMMO);
36902 
36903   // If we branched, emit the PHI to the front of endMBB.
36904   if (offsetMBB) {
36905     BuildMI(*endMBB, endMBB->begin(), MIMD,
36906             TII->get(X86::PHI), DestReg)
36907       .addReg(OffsetDestReg).addMBB(offsetMBB)
36908       .addReg(OverflowDestReg).addMBB(overflowMBB);
36909   }
36910 
36911   // Erase the pseudo instruction
36912   MI.eraseFromParent();
36913 
36914   return endMBB;
36915 }
36916 
36917 // The EFLAGS operand of SelectItr might be missing a kill marker
36918 // because there were multiple uses of EFLAGS, and ISel didn't know
36919 // which to mark. Figure out whether SelectItr should have had a
36920 // kill marker, and set it if it should. Returns the correct kill
36921 // marker value.
36922 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
36923                                      MachineBasicBlock* BB,
36924                                      const TargetRegisterInfo* TRI) {
36925   if (isEFLAGSLiveAfter(SelectItr, BB))
36926     return false;
36927 
36928   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
36929   // out. SelectMI should have a kill flag on EFLAGS.
36930   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
36931   return true;
36932 }
36933 
36934 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
36935 // together with other CMOV pseudo-opcodes into a single basic-block with
36936 // conditional jump around it.
36937 static bool isCMOVPseudo(MachineInstr &MI) {
36938   switch (MI.getOpcode()) {
36939   case X86::CMOV_FR16:
36940   case X86::CMOV_FR16X:
36941   case X86::CMOV_FR32:
36942   case X86::CMOV_FR32X:
36943   case X86::CMOV_FR64:
36944   case X86::CMOV_FR64X:
36945   case X86::CMOV_GR8:
36946   case X86::CMOV_GR16:
36947   case X86::CMOV_GR32:
36948   case X86::CMOV_RFP32:
36949   case X86::CMOV_RFP64:
36950   case X86::CMOV_RFP80:
36951   case X86::CMOV_VR64:
36952   case X86::CMOV_VR128:
36953   case X86::CMOV_VR128X:
36954   case X86::CMOV_VR256:
36955   case X86::CMOV_VR256X:
36956   case X86::CMOV_VR512:
36957   case X86::CMOV_VK1:
36958   case X86::CMOV_VK2:
36959   case X86::CMOV_VK4:
36960   case X86::CMOV_VK8:
36961   case X86::CMOV_VK16:
36962   case X86::CMOV_VK32:
36963   case X86::CMOV_VK64:
36964     return true;
36965 
36966   default:
36967     return false;
36968   }
36969 }
36970 
36971 // Helper function, which inserts PHI functions into SinkMBB:
36972 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
36973 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
36974 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
36975 // the last PHI function inserted.
36976 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
36977     MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
36978     MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
36979     MachineBasicBlock *SinkMBB) {
36980   MachineFunction *MF = TrueMBB->getParent();
36981   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
36982   const MIMetadata MIMD(*MIItBegin);
36983 
36984   X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
36985   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
36986 
36987   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
36988 
36989   // As we are creating the PHIs, we have to be careful if there is more than
36990   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
36991   // PHIs have to reference the individual true/false inputs from earlier PHIs.
36992   // That also means that PHI construction must work forward from earlier to
36993   // later, and that the code must maintain a mapping from earlier PHI's
36994   // destination registers, and the registers that went into the PHI.
36995   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
36996   MachineInstrBuilder MIB;
36997 
36998   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
36999     Register DestReg = MIIt->getOperand(0).getReg();
37000     Register Op1Reg = MIIt->getOperand(1).getReg();
37001     Register Op2Reg = MIIt->getOperand(2).getReg();
37002 
37003     // If this CMOV we are generating is the opposite condition from
37004     // the jump we generated, then we have to swap the operands for the
37005     // PHI that is going to be generated.
37006     if (MIIt->getOperand(3).getImm() == OppCC)
37007       std::swap(Op1Reg, Op2Reg);
37008 
37009     if (RegRewriteTable.contains(Op1Reg))
37010       Op1Reg = RegRewriteTable[Op1Reg].first;
37011 
37012     if (RegRewriteTable.contains(Op2Reg))
37013       Op2Reg = RegRewriteTable[Op2Reg].second;
37014 
37015     MIB =
37016         BuildMI(*SinkMBB, SinkInsertionPoint, MIMD, TII->get(X86::PHI), DestReg)
37017             .addReg(Op1Reg)
37018             .addMBB(FalseMBB)
37019             .addReg(Op2Reg)
37020             .addMBB(TrueMBB);
37021 
37022     // Add this PHI to the rewrite table.
37023     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
37024   }
37025 
37026   return MIB;
37027 }
37028 
37029 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
37030 MachineBasicBlock *
37031 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
37032                                              MachineInstr &SecondCascadedCMOV,
37033                                              MachineBasicBlock *ThisMBB) const {
37034   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
37035   const MIMetadata MIMD(FirstCMOV);
37036 
37037   // We lower cascaded CMOVs such as
37038   //
37039   //   (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
37040   //
37041   // to two successive branches.
37042   //
37043   // Without this, we would add a PHI between the two jumps, which ends up
37044   // creating a few copies all around. For instance, for
37045   //
37046   //    (sitofp (zext (fcmp une)))
37047   //
37048   // we would generate:
37049   //
37050   //         ucomiss %xmm1, %xmm0
37051   //         movss  <1.0f>, %xmm0
37052   //         movaps  %xmm0, %xmm1
37053   //         jne     .LBB5_2
37054   //         xorps   %xmm1, %xmm1
37055   // .LBB5_2:
37056   //         jp      .LBB5_4
37057   //         movaps  %xmm1, %xmm0
37058   // .LBB5_4:
37059   //         retq
37060   //
37061   // because this custom-inserter would have generated:
37062   //
37063   //   A
37064   //   | \
37065   //   |  B
37066   //   | /
37067   //   C
37068   //   | \
37069   //   |  D
37070   //   | /
37071   //   E
37072   //
37073   // A: X = ...; Y = ...
37074   // B: empty
37075   // C: Z = PHI [X, A], [Y, B]
37076   // D: empty
37077   // E: PHI [X, C], [Z, D]
37078   //
37079   // If we lower both CMOVs in a single step, we can instead generate:
37080   //
37081   //   A
37082   //   | \
37083   //   |  C
37084   //   | /|
37085   //   |/ |
37086   //   |  |
37087   //   |  D
37088   //   | /
37089   //   E
37090   //
37091   // A: X = ...; Y = ...
37092   // D: empty
37093   // E: PHI [X, A], [X, C], [Y, D]
37094   //
37095   // Which, in our sitofp/fcmp example, gives us something like:
37096   //
37097   //         ucomiss %xmm1, %xmm0
37098   //         movss  <1.0f>, %xmm0
37099   //         jne     .LBB5_4
37100   //         jp      .LBB5_4
37101   //         xorps   %xmm0, %xmm0
37102   // .LBB5_4:
37103   //         retq
37104   //
37105 
37106   // We lower cascaded CMOV into two successive branches to the same block.
37107   // EFLAGS is used by both, so mark it as live in the second.
37108   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
37109   MachineFunction *F = ThisMBB->getParent();
37110   MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
37111   MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
37112   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
37113 
37114   MachineFunction::iterator It = ++ThisMBB->getIterator();
37115   F->insert(It, FirstInsertedMBB);
37116   F->insert(It, SecondInsertedMBB);
37117   F->insert(It, SinkMBB);
37118 
37119   // For a cascaded CMOV, we lower it to two successive branches to
37120   // the same block (SinkMBB).  EFLAGS is used by both, so mark it as live in
37121   // the FirstInsertedMBB.
37122   FirstInsertedMBB->addLiveIn(X86::EFLAGS);
37123 
37124   // If the EFLAGS register isn't dead in the terminator, then claim that it's
37125   // live into the sink and copy blocks.
37126   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
37127   if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
37128       !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
37129     SecondInsertedMBB->addLiveIn(X86::EFLAGS);
37130     SinkMBB->addLiveIn(X86::EFLAGS);
37131   }
37132 
37133   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
37134   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
37135                   std::next(MachineBasicBlock::iterator(FirstCMOV)),
37136                   ThisMBB->end());
37137   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
37138 
37139   // Fallthrough block for ThisMBB.
37140   ThisMBB->addSuccessor(FirstInsertedMBB);
37141   // The true block target of the first branch is always SinkMBB.
37142   ThisMBB->addSuccessor(SinkMBB);
37143   // Fallthrough block for FirstInsertedMBB.
37144   FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
37145   // The true block for the branch of FirstInsertedMBB.
37146   FirstInsertedMBB->addSuccessor(SinkMBB);
37147   // This is fallthrough.
37148   SecondInsertedMBB->addSuccessor(SinkMBB);
37149 
37150   // Create the conditional branch instructions.
37151   X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
37152   BuildMI(ThisMBB, MIMD, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
37153 
37154   X86::CondCode SecondCC =
37155       X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
37156   BuildMI(FirstInsertedMBB, MIMD, TII->get(X86::JCC_1))
37157       .addMBB(SinkMBB)
37158       .addImm(SecondCC);
37159 
37160   //  SinkMBB:
37161   //   %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
37162   Register DestReg = SecondCascadedCMOV.getOperand(0).getReg();
37163   Register Op1Reg = FirstCMOV.getOperand(1).getReg();
37164   Register Op2Reg = FirstCMOV.getOperand(2).getReg();
37165   MachineInstrBuilder MIB =
37166       BuildMI(*SinkMBB, SinkMBB->begin(), MIMD, TII->get(X86::PHI), DestReg)
37167           .addReg(Op1Reg)
37168           .addMBB(SecondInsertedMBB)
37169           .addReg(Op2Reg)
37170           .addMBB(ThisMBB);
37171 
37172   // The second SecondInsertedMBB provides the same incoming value as the
37173   // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
37174   MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
37175 
37176   // Now remove the CMOVs.
37177   FirstCMOV.eraseFromParent();
37178   SecondCascadedCMOV.eraseFromParent();
37179 
37180   return SinkMBB;
37181 }
37182 
37183 MachineBasicBlock *
37184 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
37185                                      MachineBasicBlock *ThisMBB) const {
37186   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
37187   const MIMetadata MIMD(MI);
37188 
37189   // To "insert" a SELECT_CC instruction, we actually have to insert the
37190   // diamond control-flow pattern.  The incoming instruction knows the
37191   // destination vreg to set, the condition code register to branch on, the
37192   // true/false values to select between and a branch opcode to use.
37193 
37194   //  ThisMBB:
37195   //  ...
37196   //   TrueVal = ...
37197   //   cmpTY ccX, r1, r2
37198   //   bCC copy1MBB
37199   //   fallthrough --> FalseMBB
37200 
37201   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
37202   // as described above, by inserting a BB, and then making a PHI at the join
37203   // point to select the true and false operands of the CMOV in the PHI.
37204   //
37205   // The code also handles two different cases of multiple CMOV opcodes
37206   // in a row.
37207   //
37208   // Case 1:
37209   // In this case, there are multiple CMOVs in a row, all which are based on
37210   // the same condition setting (or the exact opposite condition setting).
37211   // In this case we can lower all the CMOVs using a single inserted BB, and
37212   // then make a number of PHIs at the join point to model the CMOVs. The only
37213   // trickiness here, is that in a case like:
37214   //
37215   // t2 = CMOV cond1 t1, f1
37216   // t3 = CMOV cond1 t2, f2
37217   //
37218   // when rewriting this into PHIs, we have to perform some renaming on the
37219   // temps since you cannot have a PHI operand refer to a PHI result earlier
37220   // in the same block.  The "simple" but wrong lowering would be:
37221   //
37222   // t2 = PHI t1(BB1), f1(BB2)
37223   // t3 = PHI t2(BB1), f2(BB2)
37224   //
37225   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
37226   // renaming is to note that on the path through BB1, t2 is really just a
37227   // copy of t1, and do that renaming, properly generating:
37228   //
37229   // t2 = PHI t1(BB1), f1(BB2)
37230   // t3 = PHI t1(BB1), f2(BB2)
37231   //
37232   // Case 2:
37233   // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
37234   // function - EmitLoweredCascadedSelect.
37235 
37236   X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
37237   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
37238   MachineInstr *LastCMOV = &MI;
37239   MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
37240 
37241   // Check for case 1, where there are multiple CMOVs with the same condition
37242   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
37243   // number of jumps the most.
37244 
37245   if (isCMOVPseudo(MI)) {
37246     // See if we have a string of CMOVS with the same condition. Skip over
37247     // intervening debug insts.
37248     while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
37249            (NextMIIt->getOperand(3).getImm() == CC ||
37250             NextMIIt->getOperand(3).getImm() == OppCC)) {
37251       LastCMOV = &*NextMIIt;
37252       NextMIIt = next_nodbg(NextMIIt, ThisMBB->end());
37253     }
37254   }
37255 
37256   // This checks for case 2, but only do this if we didn't already find
37257   // case 1, as indicated by LastCMOV == MI.
37258   if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
37259       NextMIIt->getOpcode() == MI.getOpcode() &&
37260       NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
37261       NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
37262       NextMIIt->getOperand(1).isKill()) {
37263     return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
37264   }
37265 
37266   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
37267   MachineFunction *F = ThisMBB->getParent();
37268   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
37269   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
37270 
37271   MachineFunction::iterator It = ++ThisMBB->getIterator();
37272   F->insert(It, FalseMBB);
37273   F->insert(It, SinkMBB);
37274 
37275   // If the EFLAGS register isn't dead in the terminator, then claim that it's
37276   // live into the sink and copy blocks.
37277   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
37278   if (!LastCMOV->killsRegister(X86::EFLAGS) &&
37279       !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
37280     FalseMBB->addLiveIn(X86::EFLAGS);
37281     SinkMBB->addLiveIn(X86::EFLAGS);
37282   }
37283 
37284   // Transfer any debug instructions inside the CMOV sequence to the sunk block.
37285   auto DbgRange = llvm::make_range(MachineBasicBlock::iterator(MI),
37286                                    MachineBasicBlock::iterator(LastCMOV));
37287   for (MachineInstr &MI : llvm::make_early_inc_range(DbgRange))
37288     if (MI.isDebugInstr())
37289       SinkMBB->push_back(MI.removeFromParent());
37290 
37291   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
37292   SinkMBB->splice(SinkMBB->end(), ThisMBB,
37293                   std::next(MachineBasicBlock::iterator(LastCMOV)),
37294                   ThisMBB->end());
37295   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
37296 
37297   // Fallthrough block for ThisMBB.
37298   ThisMBB->addSuccessor(FalseMBB);
37299   // The true block target of the first (or only) branch is always a SinkMBB.
37300   ThisMBB->addSuccessor(SinkMBB);
37301   // Fallthrough block for FalseMBB.
37302   FalseMBB->addSuccessor(SinkMBB);
37303 
37304   // Create the conditional branch instruction.
37305   BuildMI(ThisMBB, MIMD, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
37306 
37307   //  SinkMBB:
37308   //   %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
37309   //  ...
37310   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
37311   MachineBasicBlock::iterator MIItEnd =
37312       std::next(MachineBasicBlock::iterator(LastCMOV));
37313   createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
37314 
37315   // Now remove the CMOV(s).
37316   ThisMBB->erase(MIItBegin, MIItEnd);
37317 
37318   return SinkMBB;
37319 }
37320 
37321 static unsigned getSUBriOpcode(bool IsLP64) {
37322   if (IsLP64)
37323     return X86::SUB64ri32;
37324   else
37325     return X86::SUB32ri;
37326 }
37327 
37328 MachineBasicBlock *
37329 X86TargetLowering::EmitLoweredProbedAlloca(MachineInstr &MI,
37330                                            MachineBasicBlock *MBB) const {
37331   MachineFunction *MF = MBB->getParent();
37332   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
37333   const X86FrameLowering &TFI = *Subtarget.getFrameLowering();
37334   const MIMetadata MIMD(MI);
37335   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
37336 
37337   const unsigned ProbeSize = getStackProbeSize(*MF);
37338 
37339   MachineRegisterInfo &MRI = MF->getRegInfo();
37340   MachineBasicBlock *testMBB = MF->CreateMachineBasicBlock(LLVM_BB);
37341   MachineBasicBlock *tailMBB = MF->CreateMachineBasicBlock(LLVM_BB);
37342   MachineBasicBlock *blockMBB = MF->CreateMachineBasicBlock(LLVM_BB);
37343 
37344   MachineFunction::iterator MBBIter = ++MBB->getIterator();
37345   MF->insert(MBBIter, testMBB);
37346   MF->insert(MBBIter, blockMBB);
37347   MF->insert(MBBIter, tailMBB);
37348 
37349   Register sizeVReg = MI.getOperand(1).getReg();
37350 
37351   Register physSPReg = TFI.Uses64BitFramePtr ? X86::RSP : X86::ESP;
37352 
37353   Register TmpStackPtr = MRI.createVirtualRegister(
37354       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
37355   Register FinalStackPtr = MRI.createVirtualRegister(
37356       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
37357 
37358   BuildMI(*MBB, {MI}, MIMD, TII->get(TargetOpcode::COPY), TmpStackPtr)
37359       .addReg(physSPReg);
37360   {
37361     const unsigned Opc = TFI.Uses64BitFramePtr ? X86::SUB64rr : X86::SUB32rr;
37362     BuildMI(*MBB, {MI}, MIMD, TII->get(Opc), FinalStackPtr)
37363         .addReg(TmpStackPtr)
37364         .addReg(sizeVReg);
37365   }
37366 
37367   // test rsp size
37368 
37369   BuildMI(testMBB, MIMD,
37370           TII->get(TFI.Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
37371       .addReg(FinalStackPtr)
37372       .addReg(physSPReg);
37373 
37374   BuildMI(testMBB, MIMD, TII->get(X86::JCC_1))
37375       .addMBB(tailMBB)
37376       .addImm(X86::COND_GE);
37377   testMBB->addSuccessor(blockMBB);
37378   testMBB->addSuccessor(tailMBB);
37379 
37380   // Touch the block then extend it. This is done on the opposite side of
37381   // static probe where we allocate then touch, to avoid the need of probing the
37382   // tail of the static alloca. Possible scenarios are:
37383   //
37384   //       + ---- <- ------------ <- ------------- <- ------------ +
37385   //       |                                                       |
37386   // [free probe] -> [page alloc] -> [alloc probe] -> [tail alloc] + -> [dyn probe] -> [page alloc] -> [dyn probe] -> [tail alloc] +
37387   //                                                               |                                                               |
37388   //                                                               + <- ----------- <- ------------ <- ----------- <- ------------ +
37389   //
37390   // The property we want to enforce is to never have more than [page alloc] between two probes.
37391 
37392   const unsigned XORMIOpc =
37393       TFI.Uses64BitFramePtr ? X86::XOR64mi32 : X86::XOR32mi;
37394   addRegOffset(BuildMI(blockMBB, MIMD, TII->get(XORMIOpc)), physSPReg, false, 0)
37395       .addImm(0);
37396 
37397   BuildMI(blockMBB, MIMD, TII->get(getSUBriOpcode(TFI.Uses64BitFramePtr)),
37398           physSPReg)
37399       .addReg(physSPReg)
37400       .addImm(ProbeSize);
37401 
37402   BuildMI(blockMBB, MIMD, TII->get(X86::JMP_1)).addMBB(testMBB);
37403   blockMBB->addSuccessor(testMBB);
37404 
37405   // Replace original instruction by the expected stack ptr
37406   BuildMI(tailMBB, MIMD, TII->get(TargetOpcode::COPY),
37407           MI.getOperand(0).getReg())
37408       .addReg(FinalStackPtr);
37409 
37410   tailMBB->splice(tailMBB->end(), MBB,
37411                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
37412   tailMBB->transferSuccessorsAndUpdatePHIs(MBB);
37413   MBB->addSuccessor(testMBB);
37414 
37415   // Delete the original pseudo instruction.
37416   MI.eraseFromParent();
37417 
37418   // And we're done.
37419   return tailMBB;
37420 }
37421 
37422 MachineBasicBlock *
37423 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
37424                                         MachineBasicBlock *BB) const {
37425   MachineFunction *MF = BB->getParent();
37426   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
37427   const MIMetadata MIMD(MI);
37428   const BasicBlock *LLVM_BB = BB->getBasicBlock();
37429 
37430   assert(MF->shouldSplitStack());
37431 
37432   const bool Is64Bit = Subtarget.is64Bit();
37433   const bool IsLP64 = Subtarget.isTarget64BitLP64();
37434 
37435   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
37436   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
37437 
37438   // BB:
37439   //  ... [Till the alloca]
37440   // If stacklet is not large enough, jump to mallocMBB
37441   //
37442   // bumpMBB:
37443   //  Allocate by subtracting from RSP
37444   //  Jump to continueMBB
37445   //
37446   // mallocMBB:
37447   //  Allocate by call to runtime
37448   //
37449   // continueMBB:
37450   //  ...
37451   //  [rest of original BB]
37452   //
37453 
37454   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
37455   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
37456   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
37457 
37458   MachineRegisterInfo &MRI = MF->getRegInfo();
37459   const TargetRegisterClass *AddrRegClass =
37460       getRegClassFor(getPointerTy(MF->getDataLayout()));
37461 
37462   Register mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
37463            bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
37464            tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
37465            SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
37466            sizeVReg = MI.getOperand(1).getReg(),
37467            physSPReg =
37468                IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
37469 
37470   MachineFunction::iterator MBBIter = ++BB->getIterator();
37471 
37472   MF->insert(MBBIter, bumpMBB);
37473   MF->insert(MBBIter, mallocMBB);
37474   MF->insert(MBBIter, continueMBB);
37475 
37476   continueMBB->splice(continueMBB->begin(), BB,
37477                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
37478   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
37479 
37480   // Add code to the main basic block to check if the stack limit has been hit,
37481   // and if so, jump to mallocMBB otherwise to bumpMBB.
37482   BuildMI(BB, MIMD, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
37483   BuildMI(BB, MIMD, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
37484     .addReg(tmpSPVReg).addReg(sizeVReg);
37485   BuildMI(BB, MIMD, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
37486     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
37487     .addReg(SPLimitVReg);
37488   BuildMI(BB, MIMD, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
37489 
37490   // bumpMBB simply decreases the stack pointer, since we know the current
37491   // stacklet has enough space.
37492   BuildMI(bumpMBB, MIMD, TII->get(TargetOpcode::COPY), physSPReg)
37493     .addReg(SPLimitVReg);
37494   BuildMI(bumpMBB, MIMD, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
37495     .addReg(SPLimitVReg);
37496   BuildMI(bumpMBB, MIMD, TII->get(X86::JMP_1)).addMBB(continueMBB);
37497 
37498   // Calls into a routine in libgcc to allocate more space from the heap.
37499   const uint32_t *RegMask =
37500       Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
37501   if (IsLP64) {
37502     BuildMI(mallocMBB, MIMD, TII->get(X86::MOV64rr), X86::RDI)
37503       .addReg(sizeVReg);
37504     BuildMI(mallocMBB, MIMD, TII->get(X86::CALL64pcrel32))
37505       .addExternalSymbol("__morestack_allocate_stack_space")
37506       .addRegMask(RegMask)
37507       .addReg(X86::RDI, RegState::Implicit)
37508       .addReg(X86::RAX, RegState::ImplicitDefine);
37509   } else if (Is64Bit) {
37510     BuildMI(mallocMBB, MIMD, TII->get(X86::MOV32rr), X86::EDI)
37511       .addReg(sizeVReg);
37512     BuildMI(mallocMBB, MIMD, TII->get(X86::CALL64pcrel32))
37513       .addExternalSymbol("__morestack_allocate_stack_space")
37514       .addRegMask(RegMask)
37515       .addReg(X86::EDI, RegState::Implicit)
37516       .addReg(X86::EAX, RegState::ImplicitDefine);
37517   } else {
37518     BuildMI(mallocMBB, MIMD, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
37519       .addImm(12);
37520     BuildMI(mallocMBB, MIMD, TII->get(X86::PUSH32r)).addReg(sizeVReg);
37521     BuildMI(mallocMBB, MIMD, TII->get(X86::CALLpcrel32))
37522       .addExternalSymbol("__morestack_allocate_stack_space")
37523       .addRegMask(RegMask)
37524       .addReg(X86::EAX, RegState::ImplicitDefine);
37525   }
37526 
37527   if (!Is64Bit)
37528     BuildMI(mallocMBB, MIMD, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
37529       .addImm(16);
37530 
37531   BuildMI(mallocMBB, MIMD, TII->get(TargetOpcode::COPY), mallocPtrVReg)
37532     .addReg(IsLP64 ? X86::RAX : X86::EAX);
37533   BuildMI(mallocMBB, MIMD, TII->get(X86::JMP_1)).addMBB(continueMBB);
37534 
37535   // Set up the CFG correctly.
37536   BB->addSuccessor(bumpMBB);
37537   BB->addSuccessor(mallocMBB);
37538   mallocMBB->addSuccessor(continueMBB);
37539   bumpMBB->addSuccessor(continueMBB);
37540 
37541   // Take care of the PHI nodes.
37542   BuildMI(*continueMBB, continueMBB->begin(), MIMD, TII->get(X86::PHI),
37543           MI.getOperand(0).getReg())
37544       .addReg(mallocPtrVReg)
37545       .addMBB(mallocMBB)
37546       .addReg(bumpSPPtrVReg)
37547       .addMBB(bumpMBB);
37548 
37549   // Delete the original pseudo instruction.
37550   MI.eraseFromParent();
37551 
37552   // And we're done.
37553   return continueMBB;
37554 }
37555 
37556 MachineBasicBlock *
37557 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
37558                                        MachineBasicBlock *BB) const {
37559   MachineFunction *MF = BB->getParent();
37560   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
37561   MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
37562   const MIMetadata MIMD(MI);
37563 
37564   assert(!isAsynchronousEHPersonality(
37565              classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
37566          "SEH does not use catchret!");
37567 
37568   // Only 32-bit EH needs to worry about manually restoring stack pointers.
37569   if (!Subtarget.is32Bit())
37570     return BB;
37571 
37572   // C++ EH creates a new target block to hold the restore code, and wires up
37573   // the new block to the return destination with a normal JMP_4.
37574   MachineBasicBlock *RestoreMBB =
37575       MF->CreateMachineBasicBlock(BB->getBasicBlock());
37576   assert(BB->succ_size() == 1);
37577   MF->insert(std::next(BB->getIterator()), RestoreMBB);
37578   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
37579   BB->addSuccessor(RestoreMBB);
37580   MI.getOperand(0).setMBB(RestoreMBB);
37581 
37582   // Marking this as an EH pad but not a funclet entry block causes PEI to
37583   // restore stack pointers in the block.
37584   RestoreMBB->setIsEHPad(true);
37585 
37586   auto RestoreMBBI = RestoreMBB->begin();
37587   BuildMI(*RestoreMBB, RestoreMBBI, MIMD, TII.get(X86::JMP_4)).addMBB(TargetMBB);
37588   return BB;
37589 }
37590 
37591 MachineBasicBlock *
37592 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
37593                                       MachineBasicBlock *BB) const {
37594   // So, here we replace TLSADDR with the sequence:
37595   // adjust_stackdown -> TLSADDR -> adjust_stackup.
37596   // We need this because TLSADDR is lowered into calls
37597   // inside MC, therefore without the two markers shrink-wrapping
37598   // may push the prologue/epilogue pass them.
37599   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
37600   const MIMetadata MIMD(MI);
37601   MachineFunction &MF = *BB->getParent();
37602 
37603   // Emit CALLSEQ_START right before the instruction.
37604   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
37605   MachineInstrBuilder CallseqStart =
37606       BuildMI(MF, MIMD, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
37607   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
37608 
37609   // Emit CALLSEQ_END right after the instruction.
37610   // We don't call erase from parent because we want to keep the
37611   // original instruction around.
37612   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
37613   MachineInstrBuilder CallseqEnd =
37614       BuildMI(MF, MIMD, TII.get(AdjStackUp)).addImm(0).addImm(0);
37615   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
37616 
37617   return BB;
37618 }
37619 
37620 MachineBasicBlock *
37621 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
37622                                       MachineBasicBlock *BB) const {
37623   // This is pretty easy.  We're taking the value that we received from
37624   // our load from the relocation, sticking it in either RDI (x86-64)
37625   // or EAX and doing an indirect call.  The return value will then
37626   // be in the normal return register.
37627   MachineFunction *F = BB->getParent();
37628   const X86InstrInfo *TII = Subtarget.getInstrInfo();
37629   const MIMetadata MIMD(MI);
37630 
37631   assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
37632   assert(MI.getOperand(3).isGlobal() && "This should be a global");
37633 
37634   // Get a register mask for the lowered call.
37635   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
37636   // proper register mask.
37637   const uint32_t *RegMask =
37638       Subtarget.is64Bit() ?
37639       Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
37640       Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
37641   if (Subtarget.is64Bit()) {
37642     MachineInstrBuilder MIB =
37643         BuildMI(*BB, MI, MIMD, TII->get(X86::MOV64rm), X86::RDI)
37644             .addReg(X86::RIP)
37645             .addImm(0)
37646             .addReg(0)
37647             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
37648                               MI.getOperand(3).getTargetFlags())
37649             .addReg(0);
37650     MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL64m));
37651     addDirectMem(MIB, X86::RDI);
37652     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
37653   } else if (!isPositionIndependent()) {
37654     MachineInstrBuilder MIB =
37655         BuildMI(*BB, MI, MIMD, TII->get(X86::MOV32rm), X86::EAX)
37656             .addReg(0)
37657             .addImm(0)
37658             .addReg(0)
37659             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
37660                               MI.getOperand(3).getTargetFlags())
37661             .addReg(0);
37662     MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL32m));
37663     addDirectMem(MIB, X86::EAX);
37664     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
37665   } else {
37666     MachineInstrBuilder MIB =
37667         BuildMI(*BB, MI, MIMD, TII->get(X86::MOV32rm), X86::EAX)
37668             .addReg(TII->getGlobalBaseReg(F))
37669             .addImm(0)
37670             .addReg(0)
37671             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
37672                               MI.getOperand(3).getTargetFlags())
37673             .addReg(0);
37674     MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL32m));
37675     addDirectMem(MIB, X86::EAX);
37676     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
37677   }
37678 
37679   MI.eraseFromParent(); // The pseudo instruction is gone now.
37680   return BB;
37681 }
37682 
37683 static unsigned getOpcodeForIndirectThunk(unsigned RPOpc) {
37684   switch (RPOpc) {
37685   case X86::INDIRECT_THUNK_CALL32:
37686     return X86::CALLpcrel32;
37687   case X86::INDIRECT_THUNK_CALL64:
37688     return X86::CALL64pcrel32;
37689   case X86::INDIRECT_THUNK_TCRETURN32:
37690     return X86::TCRETURNdi;
37691   case X86::INDIRECT_THUNK_TCRETURN64:
37692     return X86::TCRETURNdi64;
37693   }
37694   llvm_unreachable("not indirect thunk opcode");
37695 }
37696 
37697 static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
37698                                           unsigned Reg) {
37699   if (Subtarget.useRetpolineExternalThunk()) {
37700     // When using an external thunk for retpolines, we pick names that match the
37701     // names GCC happens to use as well. This helps simplify the implementation
37702     // of the thunks for kernels where they have no easy ability to create
37703     // aliases and are doing non-trivial configuration of the thunk's body. For
37704     // example, the Linux kernel will do boot-time hot patching of the thunk
37705     // bodies and cannot easily export aliases of these to loaded modules.
37706     //
37707     // Note that at any point in the future, we may need to change the semantics
37708     // of how we implement retpolines and at that time will likely change the
37709     // name of the called thunk. Essentially, there is no hard guarantee that
37710     // LLVM will generate calls to specific thunks, we merely make a best-effort
37711     // attempt to help out kernels and other systems where duplicating the
37712     // thunks is costly.
37713     switch (Reg) {
37714     case X86::EAX:
37715       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
37716       return "__x86_indirect_thunk_eax";
37717     case X86::ECX:
37718       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
37719       return "__x86_indirect_thunk_ecx";
37720     case X86::EDX:
37721       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
37722       return "__x86_indirect_thunk_edx";
37723     case X86::EDI:
37724       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
37725       return "__x86_indirect_thunk_edi";
37726     case X86::R11:
37727       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
37728       return "__x86_indirect_thunk_r11";
37729     }
37730     llvm_unreachable("unexpected reg for external indirect thunk");
37731   }
37732 
37733   if (Subtarget.useRetpolineIndirectCalls() ||
37734       Subtarget.useRetpolineIndirectBranches()) {
37735     // When targeting an internal COMDAT thunk use an LLVM-specific name.
37736     switch (Reg) {
37737     case X86::EAX:
37738       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
37739       return "__llvm_retpoline_eax";
37740     case X86::ECX:
37741       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
37742       return "__llvm_retpoline_ecx";
37743     case X86::EDX:
37744       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
37745       return "__llvm_retpoline_edx";
37746     case X86::EDI:
37747       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
37748       return "__llvm_retpoline_edi";
37749     case X86::R11:
37750       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
37751       return "__llvm_retpoline_r11";
37752     }
37753     llvm_unreachable("unexpected reg for retpoline");
37754   }
37755 
37756   if (Subtarget.useLVIControlFlowIntegrity()) {
37757     assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
37758     return "__llvm_lvi_thunk_r11";
37759   }
37760   llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature");
37761 }
37762 
37763 MachineBasicBlock *
37764 X86TargetLowering::EmitLoweredIndirectThunk(MachineInstr &MI,
37765                                             MachineBasicBlock *BB) const {
37766   // Copy the virtual register into the R11 physical register and
37767   // call the retpoline thunk.
37768   const MIMetadata MIMD(MI);
37769   const X86InstrInfo *TII = Subtarget.getInstrInfo();
37770   Register CalleeVReg = MI.getOperand(0).getReg();
37771   unsigned Opc = getOpcodeForIndirectThunk(MI.getOpcode());
37772 
37773   // Find an available scratch register to hold the callee. On 64-bit, we can
37774   // just use R11, but we scan for uses anyway to ensure we don't generate
37775   // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
37776   // already a register use operand to the call to hold the callee. If none
37777   // are available, use EDI instead. EDI is chosen because EBX is the PIC base
37778   // register and ESI is the base pointer to realigned stack frames with VLAs.
37779   SmallVector<unsigned, 3> AvailableRegs;
37780   if (Subtarget.is64Bit())
37781     AvailableRegs.push_back(X86::R11);
37782   else
37783     AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
37784 
37785   // Zero out any registers that are already used.
37786   for (const auto &MO : MI.operands()) {
37787     if (MO.isReg() && MO.isUse())
37788       for (unsigned &Reg : AvailableRegs)
37789         if (Reg == MO.getReg())
37790           Reg = 0;
37791   }
37792 
37793   // Choose the first remaining non-zero available register.
37794   unsigned AvailableReg = 0;
37795   for (unsigned MaybeReg : AvailableRegs) {
37796     if (MaybeReg) {
37797       AvailableReg = MaybeReg;
37798       break;
37799     }
37800   }
37801   if (!AvailableReg)
37802     report_fatal_error("calling convention incompatible with retpoline, no "
37803                        "available registers");
37804 
37805   const char *Symbol = getIndirectThunkSymbol(Subtarget, AvailableReg);
37806 
37807   BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), AvailableReg)
37808       .addReg(CalleeVReg);
37809   MI.getOperand(0).ChangeToES(Symbol);
37810   MI.setDesc(TII->get(Opc));
37811   MachineInstrBuilder(*BB->getParent(), &MI)
37812       .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
37813   return BB;
37814 }
37815 
37816 /// SetJmp implies future control flow change upon calling the corresponding
37817 /// LongJmp.
37818 /// Instead of using the 'return' instruction, the long jump fixes the stack and
37819 /// performs an indirect branch. To do so it uses the registers that were stored
37820 /// in the jump buffer (when calling SetJmp).
37821 /// In case the shadow stack is enabled we need to fix it as well, because some
37822 /// return addresses will be skipped.
37823 /// The function will save the SSP for future fixing in the function
37824 /// emitLongJmpShadowStackFix.
37825 /// \sa emitLongJmpShadowStackFix
37826 /// \param [in] MI The temporary Machine Instruction for the builtin.
37827 /// \param [in] MBB The Machine Basic Block that will be modified.
37828 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
37829                                                  MachineBasicBlock *MBB) const {
37830   const MIMetadata MIMD(MI);
37831   MachineFunction *MF = MBB->getParent();
37832   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
37833   MachineRegisterInfo &MRI = MF->getRegInfo();
37834   MachineInstrBuilder MIB;
37835 
37836   // Memory Reference.
37837   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
37838                                            MI.memoperands_end());
37839 
37840   // Initialize a register with zero.
37841   MVT PVT = getPointerTy(MF->getDataLayout());
37842   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
37843   Register ZReg = MRI.createVirtualRegister(PtrRC);
37844   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
37845   BuildMI(*MBB, MI, MIMD, TII->get(XorRROpc))
37846       .addDef(ZReg)
37847       .addReg(ZReg, RegState::Undef)
37848       .addReg(ZReg, RegState::Undef);
37849 
37850   // Read the current SSP Register value to the zeroed register.
37851   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
37852   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
37853   BuildMI(*MBB, MI, MIMD, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
37854 
37855   // Write the SSP register value to offset 3 in input memory buffer.
37856   unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
37857   MIB = BuildMI(*MBB, MI, MIMD, TII->get(PtrStoreOpc));
37858   const int64_t SSPOffset = 3 * PVT.getStoreSize();
37859   const unsigned MemOpndSlot = 1;
37860   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
37861     if (i == X86::AddrDisp)
37862       MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
37863     else
37864       MIB.add(MI.getOperand(MemOpndSlot + i));
37865   }
37866   MIB.addReg(SSPCopyReg);
37867   MIB.setMemRefs(MMOs);
37868 }
37869 
37870 MachineBasicBlock *
37871 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
37872                                     MachineBasicBlock *MBB) const {
37873   const MIMetadata MIMD(MI);
37874   MachineFunction *MF = MBB->getParent();
37875   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
37876   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
37877   MachineRegisterInfo &MRI = MF->getRegInfo();
37878 
37879   const BasicBlock *BB = MBB->getBasicBlock();
37880   MachineFunction::iterator I = ++MBB->getIterator();
37881 
37882   // Memory Reference
37883   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
37884                                            MI.memoperands_end());
37885 
37886   unsigned DstReg;
37887   unsigned MemOpndSlot = 0;
37888 
37889   unsigned CurOp = 0;
37890 
37891   DstReg = MI.getOperand(CurOp++).getReg();
37892   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
37893   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
37894   (void)TRI;
37895   Register mainDstReg = MRI.createVirtualRegister(RC);
37896   Register restoreDstReg = MRI.createVirtualRegister(RC);
37897 
37898   MemOpndSlot = CurOp;
37899 
37900   MVT PVT = getPointerTy(MF->getDataLayout());
37901   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
37902          "Invalid Pointer Size!");
37903 
37904   // For v = setjmp(buf), we generate
37905   //
37906   // thisMBB:
37907   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
37908   //  SjLjSetup restoreMBB
37909   //
37910   // mainMBB:
37911   //  v_main = 0
37912   //
37913   // sinkMBB:
37914   //  v = phi(main, restore)
37915   //
37916   // restoreMBB:
37917   //  if base pointer being used, load it from frame
37918   //  v_restore = 1
37919 
37920   MachineBasicBlock *thisMBB = MBB;
37921   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
37922   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
37923   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
37924   MF->insert(I, mainMBB);
37925   MF->insert(I, sinkMBB);
37926   MF->push_back(restoreMBB);
37927   restoreMBB->setMachineBlockAddressTaken();
37928 
37929   MachineInstrBuilder MIB;
37930 
37931   // Transfer the remainder of BB and its successor edges to sinkMBB.
37932   sinkMBB->splice(sinkMBB->begin(), MBB,
37933                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
37934   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
37935 
37936   // thisMBB:
37937   unsigned PtrStoreOpc = 0;
37938   unsigned LabelReg = 0;
37939   const int64_t LabelOffset = 1 * PVT.getStoreSize();
37940   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
37941                      !isPositionIndependent();
37942 
37943   // Prepare IP either in reg or imm.
37944   if (!UseImmLabel) {
37945     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
37946     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
37947     LabelReg = MRI.createVirtualRegister(PtrRC);
37948     if (Subtarget.is64Bit()) {
37949       MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::LEA64r), LabelReg)
37950               .addReg(X86::RIP)
37951               .addImm(0)
37952               .addReg(0)
37953               .addMBB(restoreMBB)
37954               .addReg(0);
37955     } else {
37956       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
37957       MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::LEA32r), LabelReg)
37958               .addReg(XII->getGlobalBaseReg(MF))
37959               .addImm(0)
37960               .addReg(0)
37961               .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
37962               .addReg(0);
37963     }
37964   } else
37965     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
37966   // Store IP
37967   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrStoreOpc));
37968   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
37969     if (i == X86::AddrDisp)
37970       MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
37971     else
37972       MIB.add(MI.getOperand(MemOpndSlot + i));
37973   }
37974   if (!UseImmLabel)
37975     MIB.addReg(LabelReg);
37976   else
37977     MIB.addMBB(restoreMBB);
37978   MIB.setMemRefs(MMOs);
37979 
37980   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
37981     emitSetJmpShadowStackFix(MI, thisMBB);
37982   }
37983 
37984   // Setup
37985   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::EH_SjLj_Setup))
37986           .addMBB(restoreMBB);
37987 
37988   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
37989   MIB.addRegMask(RegInfo->getNoPreservedMask());
37990   thisMBB->addSuccessor(mainMBB);
37991   thisMBB->addSuccessor(restoreMBB);
37992 
37993   // mainMBB:
37994   //  EAX = 0
37995   BuildMI(mainMBB, MIMD, TII->get(X86::MOV32r0), mainDstReg);
37996   mainMBB->addSuccessor(sinkMBB);
37997 
37998   // sinkMBB:
37999   BuildMI(*sinkMBB, sinkMBB->begin(), MIMD, TII->get(X86::PHI), DstReg)
38000       .addReg(mainDstReg)
38001       .addMBB(mainMBB)
38002       .addReg(restoreDstReg)
38003       .addMBB(restoreMBB);
38004 
38005   // restoreMBB:
38006   if (RegInfo->hasBasePointer(*MF)) {
38007     const bool Uses64BitFramePtr =
38008         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
38009     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
38010     X86FI->setRestoreBasePointer(MF);
38011     Register FramePtr = RegInfo->getFrameRegister(*MF);
38012     Register BasePtr = RegInfo->getBaseRegister();
38013     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
38014     addRegOffset(BuildMI(restoreMBB, MIMD, TII->get(Opm), BasePtr),
38015                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
38016       .setMIFlag(MachineInstr::FrameSetup);
38017   }
38018   BuildMI(restoreMBB, MIMD, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
38019   BuildMI(restoreMBB, MIMD, TII->get(X86::JMP_1)).addMBB(sinkMBB);
38020   restoreMBB->addSuccessor(sinkMBB);
38021 
38022   MI.eraseFromParent();
38023   return sinkMBB;
38024 }
38025 
38026 /// Fix the shadow stack using the previously saved SSP pointer.
38027 /// \sa emitSetJmpShadowStackFix
38028 /// \param [in] MI The temporary Machine Instruction for the builtin.
38029 /// \param [in] MBB The Machine Basic Block that will be modified.
38030 /// \return The sink MBB that will perform the future indirect branch.
38031 MachineBasicBlock *
38032 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
38033                                              MachineBasicBlock *MBB) const {
38034   const MIMetadata MIMD(MI);
38035   MachineFunction *MF = MBB->getParent();
38036   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
38037   MachineRegisterInfo &MRI = MF->getRegInfo();
38038 
38039   // Memory Reference
38040   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
38041                                            MI.memoperands_end());
38042 
38043   MVT PVT = getPointerTy(MF->getDataLayout());
38044   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
38045 
38046   // checkSspMBB:
38047   //         xor vreg1, vreg1
38048   //         rdssp vreg1
38049   //         test vreg1, vreg1
38050   //         je sinkMBB   # Jump if Shadow Stack is not supported
38051   // fallMBB:
38052   //         mov buf+24/12(%rip), vreg2
38053   //         sub vreg1, vreg2
38054   //         jbe sinkMBB  # No need to fix the Shadow Stack
38055   // fixShadowMBB:
38056   //         shr 3/2, vreg2
38057   //         incssp vreg2  # fix the SSP according to the lower 8 bits
38058   //         shr 8, vreg2
38059   //         je sinkMBB
38060   // fixShadowLoopPrepareMBB:
38061   //         shl vreg2
38062   //         mov 128, vreg3
38063   // fixShadowLoopMBB:
38064   //         incssp vreg3
38065   //         dec vreg2
38066   //         jne fixShadowLoopMBB # Iterate until you finish fixing
38067   //                              # the Shadow Stack
38068   // sinkMBB:
38069 
38070   MachineFunction::iterator I = ++MBB->getIterator();
38071   const BasicBlock *BB = MBB->getBasicBlock();
38072 
38073   MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
38074   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
38075   MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
38076   MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
38077   MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
38078   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
38079   MF->insert(I, checkSspMBB);
38080   MF->insert(I, fallMBB);
38081   MF->insert(I, fixShadowMBB);
38082   MF->insert(I, fixShadowLoopPrepareMBB);
38083   MF->insert(I, fixShadowLoopMBB);
38084   MF->insert(I, sinkMBB);
38085 
38086   // Transfer the remainder of BB and its successor edges to sinkMBB.
38087   sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
38088                   MBB->end());
38089   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
38090 
38091   MBB->addSuccessor(checkSspMBB);
38092 
38093   // Initialize a register with zero.
38094   Register ZReg = MRI.createVirtualRegister(&X86::GR32RegClass);
38095   BuildMI(checkSspMBB, MIMD, TII->get(X86::MOV32r0), ZReg);
38096 
38097   if (PVT == MVT::i64) {
38098     Register TmpZReg = MRI.createVirtualRegister(PtrRC);
38099     BuildMI(checkSspMBB, MIMD, TII->get(X86::SUBREG_TO_REG), TmpZReg)
38100       .addImm(0)
38101       .addReg(ZReg)
38102       .addImm(X86::sub_32bit);
38103     ZReg = TmpZReg;
38104   }
38105 
38106   // Read the current SSP Register value to the zeroed register.
38107   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
38108   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
38109   BuildMI(checkSspMBB, MIMD, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
38110 
38111   // Check whether the result of the SSP register is zero and jump directly
38112   // to the sink.
38113   unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
38114   BuildMI(checkSspMBB, MIMD, TII->get(TestRROpc))
38115       .addReg(SSPCopyReg)
38116       .addReg(SSPCopyReg);
38117   BuildMI(checkSspMBB, MIMD, TII->get(X86::JCC_1))
38118       .addMBB(sinkMBB)
38119       .addImm(X86::COND_E);
38120   checkSspMBB->addSuccessor(sinkMBB);
38121   checkSspMBB->addSuccessor(fallMBB);
38122 
38123   // Reload the previously saved SSP register value.
38124   Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
38125   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
38126   const int64_t SPPOffset = 3 * PVT.getStoreSize();
38127   MachineInstrBuilder MIB =
38128       BuildMI(fallMBB, MIMD, TII->get(PtrLoadOpc), PrevSSPReg);
38129   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
38130     const MachineOperand &MO = MI.getOperand(i);
38131     if (i == X86::AddrDisp)
38132       MIB.addDisp(MO, SPPOffset);
38133     else if (MO.isReg()) // Don't add the whole operand, we don't want to
38134                          // preserve kill flags.
38135       MIB.addReg(MO.getReg());
38136     else
38137       MIB.add(MO);
38138   }
38139   MIB.setMemRefs(MMOs);
38140 
38141   // Subtract the current SSP from the previous SSP.
38142   Register SspSubReg = MRI.createVirtualRegister(PtrRC);
38143   unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
38144   BuildMI(fallMBB, MIMD, TII->get(SubRROpc), SspSubReg)
38145       .addReg(PrevSSPReg)
38146       .addReg(SSPCopyReg);
38147 
38148   // Jump to sink in case PrevSSPReg <= SSPCopyReg.
38149   BuildMI(fallMBB, MIMD, TII->get(X86::JCC_1))
38150       .addMBB(sinkMBB)
38151       .addImm(X86::COND_BE);
38152   fallMBB->addSuccessor(sinkMBB);
38153   fallMBB->addSuccessor(fixShadowMBB);
38154 
38155   // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
38156   unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
38157   unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
38158   Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
38159   BuildMI(fixShadowMBB, MIMD, TII->get(ShrRIOpc), SspFirstShrReg)
38160       .addReg(SspSubReg)
38161       .addImm(Offset);
38162 
38163   // Increase SSP when looking only on the lower 8 bits of the delta.
38164   unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
38165   BuildMI(fixShadowMBB, MIMD, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
38166 
38167   // Reset the lower 8 bits.
38168   Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
38169   BuildMI(fixShadowMBB, MIMD, TII->get(ShrRIOpc), SspSecondShrReg)
38170       .addReg(SspFirstShrReg)
38171       .addImm(8);
38172 
38173   // Jump if the result of the shift is zero.
38174   BuildMI(fixShadowMBB, MIMD, TII->get(X86::JCC_1))
38175       .addMBB(sinkMBB)
38176       .addImm(X86::COND_E);
38177   fixShadowMBB->addSuccessor(sinkMBB);
38178   fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
38179 
38180   // Do a single shift left.
38181   unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64ri : X86::SHL32ri;
38182   Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
38183   BuildMI(fixShadowLoopPrepareMBB, MIMD, TII->get(ShlR1Opc), SspAfterShlReg)
38184       .addReg(SspSecondShrReg)
38185       .addImm(1);
38186 
38187   // Save the value 128 to a register (will be used next with incssp).
38188   Register Value128InReg = MRI.createVirtualRegister(PtrRC);
38189   unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
38190   BuildMI(fixShadowLoopPrepareMBB, MIMD, TII->get(MovRIOpc), Value128InReg)
38191       .addImm(128);
38192   fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
38193 
38194   // Since incssp only looks at the lower 8 bits, we might need to do several
38195   // iterations of incssp until we finish fixing the shadow stack.
38196   Register DecReg = MRI.createVirtualRegister(PtrRC);
38197   Register CounterReg = MRI.createVirtualRegister(PtrRC);
38198   BuildMI(fixShadowLoopMBB, MIMD, TII->get(X86::PHI), CounterReg)
38199       .addReg(SspAfterShlReg)
38200       .addMBB(fixShadowLoopPrepareMBB)
38201       .addReg(DecReg)
38202       .addMBB(fixShadowLoopMBB);
38203 
38204   // Every iteration we increase the SSP by 128.
38205   BuildMI(fixShadowLoopMBB, MIMD, TII->get(IncsspOpc)).addReg(Value128InReg);
38206 
38207   // Every iteration we decrement the counter by 1.
38208   unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
38209   BuildMI(fixShadowLoopMBB, MIMD, TII->get(DecROpc), DecReg).addReg(CounterReg);
38210 
38211   // Jump if the counter is not zero yet.
38212   BuildMI(fixShadowLoopMBB, MIMD, TII->get(X86::JCC_1))
38213       .addMBB(fixShadowLoopMBB)
38214       .addImm(X86::COND_NE);
38215   fixShadowLoopMBB->addSuccessor(sinkMBB);
38216   fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
38217 
38218   return sinkMBB;
38219 }
38220 
38221 MachineBasicBlock *
38222 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
38223                                      MachineBasicBlock *MBB) const {
38224   const MIMetadata MIMD(MI);
38225   MachineFunction *MF = MBB->getParent();
38226   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
38227   MachineRegisterInfo &MRI = MF->getRegInfo();
38228 
38229   // Memory Reference
38230   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
38231                                            MI.memoperands_end());
38232 
38233   MVT PVT = getPointerTy(MF->getDataLayout());
38234   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
38235          "Invalid Pointer Size!");
38236 
38237   const TargetRegisterClass *RC =
38238     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
38239   Register Tmp = MRI.createVirtualRegister(RC);
38240   // Since FP is only updated here but NOT referenced, it's treated as GPR.
38241   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
38242   Register FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
38243   Register SP = RegInfo->getStackRegister();
38244 
38245   MachineInstrBuilder MIB;
38246 
38247   const int64_t LabelOffset = 1 * PVT.getStoreSize();
38248   const int64_t SPOffset = 2 * PVT.getStoreSize();
38249 
38250   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
38251   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
38252 
38253   MachineBasicBlock *thisMBB = MBB;
38254 
38255   // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
38256   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
38257     thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
38258   }
38259 
38260   // Reload FP
38261   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), FP);
38262   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
38263     const MachineOperand &MO = MI.getOperand(i);
38264     if (MO.isReg()) // Don't add the whole operand, we don't want to
38265                     // preserve kill flags.
38266       MIB.addReg(MO.getReg());
38267     else
38268       MIB.add(MO);
38269   }
38270   MIB.setMemRefs(MMOs);
38271 
38272   // Reload IP
38273   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), Tmp);
38274   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
38275     const MachineOperand &MO = MI.getOperand(i);
38276     if (i == X86::AddrDisp)
38277       MIB.addDisp(MO, LabelOffset);
38278     else if (MO.isReg()) // Don't add the whole operand, we don't want to
38279                          // preserve kill flags.
38280       MIB.addReg(MO.getReg());
38281     else
38282       MIB.add(MO);
38283   }
38284   MIB.setMemRefs(MMOs);
38285 
38286   // Reload SP
38287   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), SP);
38288   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
38289     if (i == X86::AddrDisp)
38290       MIB.addDisp(MI.getOperand(i), SPOffset);
38291     else
38292       MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
38293                                  // the last instruction of the expansion.
38294   }
38295   MIB.setMemRefs(MMOs);
38296 
38297   // Jump
38298   BuildMI(*thisMBB, MI, MIMD, TII->get(IJmpOpc)).addReg(Tmp);
38299 
38300   MI.eraseFromParent();
38301   return thisMBB;
38302 }
38303 
38304 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
38305                                                MachineBasicBlock *MBB,
38306                                                MachineBasicBlock *DispatchBB,
38307                                                int FI) const {
38308   const MIMetadata MIMD(MI);
38309   MachineFunction *MF = MBB->getParent();
38310   MachineRegisterInfo *MRI = &MF->getRegInfo();
38311   const X86InstrInfo *TII = Subtarget.getInstrInfo();
38312 
38313   MVT PVT = getPointerTy(MF->getDataLayout());
38314   assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
38315 
38316   unsigned Op = 0;
38317   unsigned VR = 0;
38318 
38319   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
38320                      !isPositionIndependent();
38321 
38322   if (UseImmLabel) {
38323     Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
38324   } else {
38325     const TargetRegisterClass *TRC =
38326         (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
38327     VR = MRI->createVirtualRegister(TRC);
38328     Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
38329 
38330     if (Subtarget.is64Bit())
38331       BuildMI(*MBB, MI, MIMD, TII->get(X86::LEA64r), VR)
38332           .addReg(X86::RIP)
38333           .addImm(1)
38334           .addReg(0)
38335           .addMBB(DispatchBB)
38336           .addReg(0);
38337     else
38338       BuildMI(*MBB, MI, MIMD, TII->get(X86::LEA32r), VR)
38339           .addReg(0) /* TII->getGlobalBaseReg(MF) */
38340           .addImm(1)
38341           .addReg(0)
38342           .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
38343           .addReg(0);
38344   }
38345 
38346   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MIMD, TII->get(Op));
38347   addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
38348   if (UseImmLabel)
38349     MIB.addMBB(DispatchBB);
38350   else
38351     MIB.addReg(VR);
38352 }
38353 
38354 MachineBasicBlock *
38355 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
38356                                          MachineBasicBlock *BB) const {
38357   const MIMetadata MIMD(MI);
38358   MachineFunction *MF = BB->getParent();
38359   MachineRegisterInfo *MRI = &MF->getRegInfo();
38360   const X86InstrInfo *TII = Subtarget.getInstrInfo();
38361   int FI = MF->getFrameInfo().getFunctionContextIndex();
38362 
38363   // Get a mapping of the call site numbers to all of the landing pads they're
38364   // associated with.
38365   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
38366   unsigned MaxCSNum = 0;
38367   for (auto &MBB : *MF) {
38368     if (!MBB.isEHPad())
38369       continue;
38370 
38371     MCSymbol *Sym = nullptr;
38372     for (const auto &MI : MBB) {
38373       if (MI.isDebugInstr())
38374         continue;
38375 
38376       assert(MI.isEHLabel() && "expected EH_LABEL");
38377       Sym = MI.getOperand(0).getMCSymbol();
38378       break;
38379     }
38380 
38381     if (!MF->hasCallSiteLandingPad(Sym))
38382       continue;
38383 
38384     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
38385       CallSiteNumToLPad[CSI].push_back(&MBB);
38386       MaxCSNum = std::max(MaxCSNum, CSI);
38387     }
38388   }
38389 
38390   // Get an ordered list of the machine basic blocks for the jump table.
38391   std::vector<MachineBasicBlock *> LPadList;
38392   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
38393   LPadList.reserve(CallSiteNumToLPad.size());
38394 
38395   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
38396     for (auto &LP : CallSiteNumToLPad[CSI]) {
38397       LPadList.push_back(LP);
38398       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
38399     }
38400   }
38401 
38402   assert(!LPadList.empty() &&
38403          "No landing pad destinations for the dispatch jump table!");
38404 
38405   // Create the MBBs for the dispatch code.
38406 
38407   // Shove the dispatch's address into the return slot in the function context.
38408   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
38409   DispatchBB->setIsEHPad(true);
38410 
38411   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
38412   BuildMI(TrapBB, MIMD, TII->get(X86::TRAP));
38413   DispatchBB->addSuccessor(TrapBB);
38414 
38415   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
38416   DispatchBB->addSuccessor(DispContBB);
38417 
38418   // Insert MBBs.
38419   MF->push_back(DispatchBB);
38420   MF->push_back(DispContBB);
38421   MF->push_back(TrapBB);
38422 
38423   // Insert code into the entry block that creates and registers the function
38424   // context.
38425   SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
38426 
38427   // Create the jump table and associated information
38428   unsigned JTE = getJumpTableEncoding();
38429   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
38430   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
38431 
38432   const X86RegisterInfo &RI = TII->getRegisterInfo();
38433   // Add a register mask with no preserved registers.  This results in all
38434   // registers being marked as clobbered.
38435   if (RI.hasBasePointer(*MF)) {
38436     const bool FPIs64Bit =
38437         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
38438     X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
38439     MFI->setRestoreBasePointer(MF);
38440 
38441     Register FP = RI.getFrameRegister(*MF);
38442     Register BP = RI.getBaseRegister();
38443     unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
38444     addRegOffset(BuildMI(DispatchBB, MIMD, TII->get(Op), BP), FP, true,
38445                  MFI->getRestoreBasePointerOffset())
38446         .addRegMask(RI.getNoPreservedMask());
38447   } else {
38448     BuildMI(DispatchBB, MIMD, TII->get(X86::NOOP))
38449         .addRegMask(RI.getNoPreservedMask());
38450   }
38451 
38452   // IReg is used as an index in a memory operand and therefore can't be SP
38453   Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
38454   addFrameReference(BuildMI(DispatchBB, MIMD, TII->get(X86::MOV32rm), IReg), FI,
38455                     Subtarget.is64Bit() ? 8 : 4);
38456   BuildMI(DispatchBB, MIMD, TII->get(X86::CMP32ri))
38457       .addReg(IReg)
38458       .addImm(LPadList.size());
38459   BuildMI(DispatchBB, MIMD, TII->get(X86::JCC_1))
38460       .addMBB(TrapBB)
38461       .addImm(X86::COND_AE);
38462 
38463   if (Subtarget.is64Bit()) {
38464     Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
38465     Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
38466 
38467     // leaq .LJTI0_0(%rip), BReg
38468     BuildMI(DispContBB, MIMD, TII->get(X86::LEA64r), BReg)
38469         .addReg(X86::RIP)
38470         .addImm(1)
38471         .addReg(0)
38472         .addJumpTableIndex(MJTI)
38473         .addReg(0);
38474     // movzx IReg64, IReg
38475     BuildMI(DispContBB, MIMD, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
38476         .addImm(0)
38477         .addReg(IReg)
38478         .addImm(X86::sub_32bit);
38479 
38480     switch (JTE) {
38481     case MachineJumpTableInfo::EK_BlockAddress:
38482       // jmpq *(BReg,IReg64,8)
38483       BuildMI(DispContBB, MIMD, TII->get(X86::JMP64m))
38484           .addReg(BReg)
38485           .addImm(8)
38486           .addReg(IReg64)
38487           .addImm(0)
38488           .addReg(0);
38489       break;
38490     case MachineJumpTableInfo::EK_LabelDifference32: {
38491       Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
38492       Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
38493       Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
38494 
38495       // movl (BReg,IReg64,4), OReg
38496       BuildMI(DispContBB, MIMD, TII->get(X86::MOV32rm), OReg)
38497           .addReg(BReg)
38498           .addImm(4)
38499           .addReg(IReg64)
38500           .addImm(0)
38501           .addReg(0);
38502       // movsx OReg64, OReg
38503       BuildMI(DispContBB, MIMD, TII->get(X86::MOVSX64rr32), OReg64)
38504           .addReg(OReg);
38505       // addq BReg, OReg64, TReg
38506       BuildMI(DispContBB, MIMD, TII->get(X86::ADD64rr), TReg)
38507           .addReg(OReg64)
38508           .addReg(BReg);
38509       // jmpq *TReg
38510       BuildMI(DispContBB, MIMD, TII->get(X86::JMP64r)).addReg(TReg);
38511       break;
38512     }
38513     default:
38514       llvm_unreachable("Unexpected jump table encoding");
38515     }
38516   } else {
38517     // jmpl *.LJTI0_0(,IReg,4)
38518     BuildMI(DispContBB, MIMD, TII->get(X86::JMP32m))
38519         .addReg(0)
38520         .addImm(4)
38521         .addReg(IReg)
38522         .addJumpTableIndex(MJTI)
38523         .addReg(0);
38524   }
38525 
38526   // Add the jump table entries as successors to the MBB.
38527   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
38528   for (auto &LP : LPadList)
38529     if (SeenMBBs.insert(LP).second)
38530       DispContBB->addSuccessor(LP);
38531 
38532   // N.B. the order the invoke BBs are processed in doesn't matter here.
38533   SmallVector<MachineBasicBlock *, 64> MBBLPads;
38534   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
38535   for (MachineBasicBlock *MBB : InvokeBBs) {
38536     // Remove the landing pad successor from the invoke block and replace it
38537     // with the new dispatch block.
38538     // Keep a copy of Successors since it's modified inside the loop.
38539     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
38540                                                    MBB->succ_rend());
38541     // FIXME: Avoid quadratic complexity.
38542     for (auto *MBBS : Successors) {
38543       if (MBBS->isEHPad()) {
38544         MBB->removeSuccessor(MBBS);
38545         MBBLPads.push_back(MBBS);
38546       }
38547     }
38548 
38549     MBB->addSuccessor(DispatchBB);
38550 
38551     // Find the invoke call and mark all of the callee-saved registers as
38552     // 'implicit defined' so that they're spilled.  This prevents code from
38553     // moving instructions to before the EH block, where they will never be
38554     // executed.
38555     for (auto &II : reverse(*MBB)) {
38556       if (!II.isCall())
38557         continue;
38558 
38559       DenseMap<unsigned, bool> DefRegs;
38560       for (auto &MOp : II.operands())
38561         if (MOp.isReg())
38562           DefRegs[MOp.getReg()] = true;
38563 
38564       MachineInstrBuilder MIB(*MF, &II);
38565       for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
38566         unsigned Reg = SavedRegs[RegIdx];
38567         if (!DefRegs[Reg])
38568           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
38569       }
38570 
38571       break;
38572     }
38573   }
38574 
38575   // Mark all former landing pads as non-landing pads.  The dispatch is the only
38576   // landing pad now.
38577   for (auto &LP : MBBLPads)
38578     LP->setIsEHPad(false);
38579 
38580   // The instruction is gone now.
38581   MI.eraseFromParent();
38582   return BB;
38583 }
38584 
38585 MachineBasicBlock *
38586 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
38587                                                MachineBasicBlock *BB) const {
38588   MachineFunction *MF = BB->getParent();
38589   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
38590   const MIMetadata MIMD(MI);
38591 
38592   auto TMMImmToTMMReg = [](unsigned Imm) {
38593     assert (Imm < 8 && "Illegal tmm index");
38594     return X86::TMM0 + Imm;
38595   };
38596   switch (MI.getOpcode()) {
38597   default: llvm_unreachable("Unexpected instr type to insert");
38598   case X86::TLS_addr32:
38599   case X86::TLS_addr64:
38600   case X86::TLS_addrX32:
38601   case X86::TLS_base_addr32:
38602   case X86::TLS_base_addr64:
38603   case X86::TLS_base_addrX32:
38604     return EmitLoweredTLSAddr(MI, BB);
38605   case X86::INDIRECT_THUNK_CALL32:
38606   case X86::INDIRECT_THUNK_CALL64:
38607   case X86::INDIRECT_THUNK_TCRETURN32:
38608   case X86::INDIRECT_THUNK_TCRETURN64:
38609     return EmitLoweredIndirectThunk(MI, BB);
38610   case X86::CATCHRET:
38611     return EmitLoweredCatchRet(MI, BB);
38612   case X86::SEG_ALLOCA_32:
38613   case X86::SEG_ALLOCA_64:
38614     return EmitLoweredSegAlloca(MI, BB);
38615   case X86::PROBED_ALLOCA_32:
38616   case X86::PROBED_ALLOCA_64:
38617     return EmitLoweredProbedAlloca(MI, BB);
38618   case X86::TLSCall_32:
38619   case X86::TLSCall_64:
38620     return EmitLoweredTLSCall(MI, BB);
38621   case X86::CMOV_FR16:
38622   case X86::CMOV_FR16X:
38623   case X86::CMOV_FR32:
38624   case X86::CMOV_FR32X:
38625   case X86::CMOV_FR64:
38626   case X86::CMOV_FR64X:
38627   case X86::CMOV_GR8:
38628   case X86::CMOV_GR16:
38629   case X86::CMOV_GR32:
38630   case X86::CMOV_RFP32:
38631   case X86::CMOV_RFP64:
38632   case X86::CMOV_RFP80:
38633   case X86::CMOV_VR64:
38634   case X86::CMOV_VR128:
38635   case X86::CMOV_VR128X:
38636   case X86::CMOV_VR256:
38637   case X86::CMOV_VR256X:
38638   case X86::CMOV_VR512:
38639   case X86::CMOV_VK1:
38640   case X86::CMOV_VK2:
38641   case X86::CMOV_VK4:
38642   case X86::CMOV_VK8:
38643   case X86::CMOV_VK16:
38644   case X86::CMOV_VK32:
38645   case X86::CMOV_VK64:
38646     return EmitLoweredSelect(MI, BB);
38647 
38648   case X86::FP80_ADDr:
38649   case X86::FP80_ADDm32: {
38650     // Change the floating point control register to use double extended
38651     // precision when performing the addition.
38652     int OrigCWFrameIdx =
38653         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
38654     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FNSTCW16m)),
38655                       OrigCWFrameIdx);
38656 
38657     // Load the old value of the control word...
38658     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
38659     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOVZX32rm16), OldCW),
38660                       OrigCWFrameIdx);
38661 
38662     // OR 0b11 into bit 8 and 9. 0b11 is the encoding for double extended
38663     // precision.
38664     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
38665     BuildMI(*BB, MI, MIMD, TII->get(X86::OR32ri), NewCW)
38666         .addReg(OldCW, RegState::Kill)
38667         .addImm(0x300);
38668 
38669     // Extract to 16 bits.
38670     Register NewCW16 =
38671         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
38672     BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), NewCW16)
38673         .addReg(NewCW, RegState::Kill, X86::sub_16bit);
38674 
38675     // Prepare memory for FLDCW.
38676     int NewCWFrameIdx =
38677         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
38678     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOV16mr)),
38679                       NewCWFrameIdx)
38680         .addReg(NewCW16, RegState::Kill);
38681 
38682     // Reload the modified control word now...
38683     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
38684                       NewCWFrameIdx);
38685 
38686     // Do the addition.
38687     if (MI.getOpcode() == X86::FP80_ADDr) {
38688       BuildMI(*BB, MI, MIMD, TII->get(X86::ADD_Fp80))
38689           .add(MI.getOperand(0))
38690           .add(MI.getOperand(1))
38691           .add(MI.getOperand(2));
38692     } else {
38693       BuildMI(*BB, MI, MIMD, TII->get(X86::ADD_Fp80m32))
38694           .add(MI.getOperand(0))
38695           .add(MI.getOperand(1))
38696           .add(MI.getOperand(2))
38697           .add(MI.getOperand(3))
38698           .add(MI.getOperand(4))
38699           .add(MI.getOperand(5))
38700           .add(MI.getOperand(6));
38701     }
38702 
38703     // Reload the original control word now.
38704     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
38705                       OrigCWFrameIdx);
38706 
38707     MI.eraseFromParent(); // The pseudo instruction is gone now.
38708     return BB;
38709   }
38710 
38711   case X86::FP32_TO_INT16_IN_MEM:
38712   case X86::FP32_TO_INT32_IN_MEM:
38713   case X86::FP32_TO_INT64_IN_MEM:
38714   case X86::FP64_TO_INT16_IN_MEM:
38715   case X86::FP64_TO_INT32_IN_MEM:
38716   case X86::FP64_TO_INT64_IN_MEM:
38717   case X86::FP80_TO_INT16_IN_MEM:
38718   case X86::FP80_TO_INT32_IN_MEM:
38719   case X86::FP80_TO_INT64_IN_MEM: {
38720     // Change the floating point control register to use "round towards zero"
38721     // mode when truncating to an integer value.
38722     int OrigCWFrameIdx =
38723         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
38724     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FNSTCW16m)),
38725                       OrigCWFrameIdx);
38726 
38727     // Load the old value of the control word...
38728     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
38729     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOVZX32rm16), OldCW),
38730                       OrigCWFrameIdx);
38731 
38732     // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
38733     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
38734     BuildMI(*BB, MI, MIMD, TII->get(X86::OR32ri), NewCW)
38735       .addReg(OldCW, RegState::Kill).addImm(0xC00);
38736 
38737     // Extract to 16 bits.
38738     Register NewCW16 =
38739         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
38740     BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), NewCW16)
38741       .addReg(NewCW, RegState::Kill, X86::sub_16bit);
38742 
38743     // Prepare memory for FLDCW.
38744     int NewCWFrameIdx =
38745         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
38746     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOV16mr)),
38747                       NewCWFrameIdx)
38748       .addReg(NewCW16, RegState::Kill);
38749 
38750     // Reload the modified control word now...
38751     addFrameReference(BuildMI(*BB, MI, MIMD,
38752                               TII->get(X86::FLDCW16m)), NewCWFrameIdx);
38753 
38754     // Get the X86 opcode to use.
38755     unsigned Opc;
38756     switch (MI.getOpcode()) {
38757     default: llvm_unreachable("illegal opcode!");
38758     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
38759     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
38760     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
38761     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
38762     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
38763     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
38764     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
38765     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
38766     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
38767     }
38768 
38769     X86AddressMode AM = getAddressFromInstr(&MI, 0);
38770     addFullAddress(BuildMI(*BB, MI, MIMD, TII->get(Opc)), AM)
38771         .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
38772 
38773     // Reload the original control word now.
38774     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
38775                       OrigCWFrameIdx);
38776 
38777     MI.eraseFromParent(); // The pseudo instruction is gone now.
38778     return BB;
38779   }
38780 
38781   // xbegin
38782   case X86::XBEGIN:
38783     return emitXBegin(MI, BB, Subtarget.getInstrInfo());
38784 
38785   case X86::VAARG_64:
38786   case X86::VAARG_X32:
38787     return EmitVAARGWithCustomInserter(MI, BB);
38788 
38789   case X86::EH_SjLj_SetJmp32:
38790   case X86::EH_SjLj_SetJmp64:
38791     return emitEHSjLjSetJmp(MI, BB);
38792 
38793   case X86::EH_SjLj_LongJmp32:
38794   case X86::EH_SjLj_LongJmp64:
38795     return emitEHSjLjLongJmp(MI, BB);
38796 
38797   case X86::Int_eh_sjlj_setup_dispatch:
38798     return EmitSjLjDispatchBlock(MI, BB);
38799 
38800   case TargetOpcode::STATEPOINT:
38801     // As an implementation detail, STATEPOINT shares the STACKMAP format at
38802     // this point in the process.  We diverge later.
38803     return emitPatchPoint(MI, BB);
38804 
38805   case TargetOpcode::STACKMAP:
38806   case TargetOpcode::PATCHPOINT:
38807     return emitPatchPoint(MI, BB);
38808 
38809   case TargetOpcode::PATCHABLE_EVENT_CALL:
38810   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
38811     return BB;
38812 
38813   case X86::LCMPXCHG8B: {
38814     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
38815     // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
38816     // requires a memory operand. If it happens that current architecture is
38817     // i686 and for current function we need a base pointer
38818     // - which is ESI for i686 - register allocator would not be able to
38819     // allocate registers for an address in form of X(%reg, %reg, Y)
38820     // - there never would be enough unreserved registers during regalloc
38821     // (without the need for base ptr the only option would be X(%edi, %esi, Y).
38822     // We are giving a hand to register allocator by precomputing the address in
38823     // a new vreg using LEA.
38824 
38825     // If it is not i686 or there is no base pointer - nothing to do here.
38826     if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
38827       return BB;
38828 
38829     // Even though this code does not necessarily needs the base pointer to
38830     // be ESI, we check for that. The reason: if this assert fails, there are
38831     // some changes happened in the compiler base pointer handling, which most
38832     // probably have to be addressed somehow here.
38833     assert(TRI->getBaseRegister() == X86::ESI &&
38834            "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
38835            "base pointer in mind");
38836 
38837     MachineRegisterInfo &MRI = MF->getRegInfo();
38838     MVT SPTy = getPointerTy(MF->getDataLayout());
38839     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
38840     Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
38841 
38842     X86AddressMode AM = getAddressFromInstr(&MI, 0);
38843     // Regalloc does not need any help when the memory operand of CMPXCHG8B
38844     // does not use index register.
38845     if (AM.IndexReg == X86::NoRegister)
38846       return BB;
38847 
38848     // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
38849     // four operand definitions that are E[ABCD] registers. We skip them and
38850     // then insert the LEA.
38851     MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
38852     while (RMBBI != BB->rend() && (RMBBI->definesRegister(X86::EAX) ||
38853                                    RMBBI->definesRegister(X86::EBX) ||
38854                                    RMBBI->definesRegister(X86::ECX) ||
38855                                    RMBBI->definesRegister(X86::EDX))) {
38856       ++RMBBI;
38857     }
38858     MachineBasicBlock::iterator MBBI(RMBBI);
38859     addFullAddress(
38860         BuildMI(*BB, *MBBI, MIMD, TII->get(X86::LEA32r), computedAddrVReg), AM);
38861 
38862     setDirectAddressInInstr(&MI, 0, computedAddrVReg);
38863 
38864     return BB;
38865   }
38866   case X86::LCMPXCHG16B_NO_RBX: {
38867     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
38868     Register BasePtr = TRI->getBaseRegister();
38869     if (TRI->hasBasePointer(*MF) &&
38870         (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
38871       if (!BB->isLiveIn(BasePtr))
38872         BB->addLiveIn(BasePtr);
38873       // Save RBX into a virtual register.
38874       Register SaveRBX =
38875           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
38876       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), SaveRBX)
38877           .addReg(X86::RBX);
38878       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
38879       MachineInstrBuilder MIB =
38880           BuildMI(*BB, MI, MIMD, TII->get(X86::LCMPXCHG16B_SAVE_RBX), Dst);
38881       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
38882         MIB.add(MI.getOperand(Idx));
38883       MIB.add(MI.getOperand(X86::AddrNumOperands));
38884       MIB.addReg(SaveRBX);
38885     } else {
38886       // Simple case, just copy the virtual register to RBX.
38887       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::RBX)
38888           .add(MI.getOperand(X86::AddrNumOperands));
38889       MachineInstrBuilder MIB =
38890           BuildMI(*BB, MI, MIMD, TII->get(X86::LCMPXCHG16B));
38891       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
38892         MIB.add(MI.getOperand(Idx));
38893     }
38894     MI.eraseFromParent();
38895     return BB;
38896   }
38897   case X86::MWAITX: {
38898     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
38899     Register BasePtr = TRI->getBaseRegister();
38900     bool IsRBX = (BasePtr == X86::RBX || BasePtr == X86::EBX);
38901     // If no need to save the base pointer, we generate MWAITXrrr,
38902     // else we generate pseudo MWAITX_SAVE_RBX.
38903     if (!IsRBX || !TRI->hasBasePointer(*MF)) {
38904       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::ECX)
38905           .addReg(MI.getOperand(0).getReg());
38906       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EAX)
38907           .addReg(MI.getOperand(1).getReg());
38908       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EBX)
38909           .addReg(MI.getOperand(2).getReg());
38910       BuildMI(*BB, MI, MIMD, TII->get(X86::MWAITXrrr));
38911       MI.eraseFromParent();
38912     } else {
38913       if (!BB->isLiveIn(BasePtr)) {
38914         BB->addLiveIn(BasePtr);
38915       }
38916       // Parameters can be copied into ECX and EAX but not EBX yet.
38917       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::ECX)
38918           .addReg(MI.getOperand(0).getReg());
38919       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EAX)
38920           .addReg(MI.getOperand(1).getReg());
38921       assert(Subtarget.is64Bit() && "Expected 64-bit mode!");
38922       // Save RBX into a virtual register.
38923       Register SaveRBX =
38924           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
38925       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), SaveRBX)
38926           .addReg(X86::RBX);
38927       // Generate mwaitx pseudo.
38928       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
38929       BuildMI(*BB, MI, MIMD, TII->get(X86::MWAITX_SAVE_RBX))
38930           .addDef(Dst) // Destination tied in with SaveRBX.
38931           .addReg(MI.getOperand(2).getReg()) // input value of EBX.
38932           .addUse(SaveRBX);                  // Save of base pointer.
38933       MI.eraseFromParent();
38934     }
38935     return BB;
38936   }
38937   case TargetOpcode::PREALLOCATED_SETUP: {
38938     assert(Subtarget.is32Bit() && "preallocated only used in 32-bit");
38939     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
38940     MFI->setHasPreallocatedCall(true);
38941     int64_t PreallocatedId = MI.getOperand(0).getImm();
38942     size_t StackAdjustment = MFI->getPreallocatedStackSize(PreallocatedId);
38943     assert(StackAdjustment != 0 && "0 stack adjustment");
38944     LLVM_DEBUG(dbgs() << "PREALLOCATED_SETUP stack adjustment "
38945                       << StackAdjustment << "\n");
38946     BuildMI(*BB, MI, MIMD, TII->get(X86::SUB32ri), X86::ESP)
38947         .addReg(X86::ESP)
38948         .addImm(StackAdjustment);
38949     MI.eraseFromParent();
38950     return BB;
38951   }
38952   case TargetOpcode::PREALLOCATED_ARG: {
38953     assert(Subtarget.is32Bit() && "preallocated calls only used in 32-bit");
38954     int64_t PreallocatedId = MI.getOperand(1).getImm();
38955     int64_t ArgIdx = MI.getOperand(2).getImm();
38956     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
38957     size_t ArgOffset = MFI->getPreallocatedArgOffsets(PreallocatedId)[ArgIdx];
38958     LLVM_DEBUG(dbgs() << "PREALLOCATED_ARG arg index " << ArgIdx
38959                       << ", arg offset " << ArgOffset << "\n");
38960     // stack pointer + offset
38961     addRegOffset(BuildMI(*BB, MI, MIMD, TII->get(X86::LEA32r),
38962                          MI.getOperand(0).getReg()),
38963                  X86::ESP, false, ArgOffset);
38964     MI.eraseFromParent();
38965     return BB;
38966   }
38967   case X86::PTDPBSSD:
38968   case X86::PTDPBSUD:
38969   case X86::PTDPBUSD:
38970   case X86::PTDPBUUD:
38971   case X86::PTDPBF16PS:
38972   case X86::PTDPFP16PS: {
38973     unsigned Opc;
38974     switch (MI.getOpcode()) {
38975     default: llvm_unreachable("illegal opcode!");
38976     case X86::PTDPBSSD: Opc = X86::TDPBSSD; break;
38977     case X86::PTDPBSUD: Opc = X86::TDPBSUD; break;
38978     case X86::PTDPBUSD: Opc = X86::TDPBUSD; break;
38979     case X86::PTDPBUUD: Opc = X86::TDPBUUD; break;
38980     case X86::PTDPBF16PS: Opc = X86::TDPBF16PS; break;
38981     case X86::PTDPFP16PS: Opc = X86::TDPFP16PS; break;
38982     }
38983 
38984     MachineInstrBuilder MIB = BuildMI(*BB, MI, MIMD, TII->get(Opc));
38985     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
38986     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
38987     MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
38988     MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
38989 
38990     MI.eraseFromParent(); // The pseudo is gone now.
38991     return BB;
38992   }
38993   case X86::PTILEZERO: {
38994     unsigned Imm = MI.getOperand(0).getImm();
38995     BuildMI(*BB, MI, MIMD, TII->get(X86::TILEZERO), TMMImmToTMMReg(Imm));
38996     MI.eraseFromParent(); // The pseudo is gone now.
38997     return BB;
38998   }
38999   case X86::PTILELOADD:
39000   case X86::PTILELOADDT1:
39001   case X86::PTILESTORED: {
39002     unsigned Opc;
39003     switch (MI.getOpcode()) {
39004     default: llvm_unreachable("illegal opcode!");
39005     case X86::PTILELOADD:   Opc = X86::TILELOADD;   break;
39006     case X86::PTILELOADDT1: Opc = X86::TILELOADDT1; break;
39007     case X86::PTILESTORED:  Opc = X86::TILESTORED;  break;
39008     }
39009 
39010     MachineInstrBuilder MIB = BuildMI(*BB, MI, MIMD, TII->get(Opc));
39011     unsigned CurOp = 0;
39012     if (Opc != X86::TILESTORED)
39013       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
39014                  RegState::Define);
39015 
39016     MIB.add(MI.getOperand(CurOp++)); // base
39017     MIB.add(MI.getOperand(CurOp++)); // scale
39018     MIB.add(MI.getOperand(CurOp++)); // index -- stride
39019     MIB.add(MI.getOperand(CurOp++)); // displacement
39020     MIB.add(MI.getOperand(CurOp++)); // segment
39021 
39022     if (Opc == X86::TILESTORED)
39023       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
39024                  RegState::Undef);
39025 
39026     MI.eraseFromParent(); // The pseudo is gone now.
39027     return BB;
39028   }
39029   case X86::PTCMMIMFP16PS:
39030   case X86::PTCMMRLFP16PS: {
39031     const MIMetadata MIMD(MI);
39032     unsigned Opc;
39033     switch (MI.getOpcode()) {
39034     default: llvm_unreachable("Unexpected instruction!");
39035     case X86::PTCMMIMFP16PS:     Opc = X86::TCMMIMFP16PS;     break;
39036     case X86::PTCMMRLFP16PS:     Opc = X86::TCMMRLFP16PS;     break;
39037     }
39038     MachineInstrBuilder MIB = BuildMI(*BB, MI, MIMD, TII->get(Opc));
39039     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
39040     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
39041     MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
39042     MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
39043     MI.eraseFromParent(); // The pseudo is gone now.
39044     return BB;
39045   }
39046   }
39047 }
39048 
39049 //===----------------------------------------------------------------------===//
39050 //                           X86 Optimization Hooks
39051 //===----------------------------------------------------------------------===//
39052 
39053 bool
39054 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
39055                                                 const APInt &DemandedBits,
39056                                                 const APInt &DemandedElts,
39057                                                 TargetLoweringOpt &TLO) const {
39058   EVT VT = Op.getValueType();
39059   unsigned Opcode = Op.getOpcode();
39060   unsigned EltSize = VT.getScalarSizeInBits();
39061 
39062   if (VT.isVector()) {
39063     // If the constant is only all signbits in the active bits, then we should
39064     // extend it to the entire constant to allow it act as a boolean constant
39065     // vector.
39066     auto NeedsSignExtension = [&](SDValue V, unsigned ActiveBits) {
39067       if (!ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
39068         return false;
39069       for (unsigned i = 0, e = V.getNumOperands(); i != e; ++i) {
39070         if (!DemandedElts[i] || V.getOperand(i).isUndef())
39071           continue;
39072         const APInt &Val = V.getConstantOperandAPInt(i);
39073         if (Val.getBitWidth() > Val.getNumSignBits() &&
39074             Val.trunc(ActiveBits).getNumSignBits() == ActiveBits)
39075           return true;
39076       }
39077       return false;
39078     };
39079     // For vectors - if we have a constant, then try to sign extend.
39080     // TODO: Handle AND cases.
39081     unsigned ActiveBits = DemandedBits.getActiveBits();
39082     if (EltSize > ActiveBits && EltSize > 1 && isTypeLegal(VT) &&
39083         (Opcode == ISD::OR || Opcode == ISD::XOR || Opcode == X86ISD::ANDNP) &&
39084         NeedsSignExtension(Op.getOperand(1), ActiveBits)) {
39085       EVT ExtSVT = EVT::getIntegerVT(*TLO.DAG.getContext(), ActiveBits);
39086       EVT ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtSVT,
39087                                    VT.getVectorNumElements());
39088       SDValue NewC =
39089           TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(Op), VT,
39090                           Op.getOperand(1), TLO.DAG.getValueType(ExtVT));
39091       SDValue NewOp =
39092           TLO.DAG.getNode(Opcode, SDLoc(Op), VT, Op.getOperand(0), NewC);
39093       return TLO.CombineTo(Op, NewOp);
39094     }
39095     return false;
39096   }
39097 
39098   // Only optimize Ands to prevent shrinking a constant that could be
39099   // matched by movzx.
39100   if (Opcode != ISD::AND)
39101     return false;
39102 
39103   // Make sure the RHS really is a constant.
39104   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
39105   if (!C)
39106     return false;
39107 
39108   const APInt &Mask = C->getAPIntValue();
39109 
39110   // Clear all non-demanded bits initially.
39111   APInt ShrunkMask = Mask & DemandedBits;
39112 
39113   // Find the width of the shrunk mask.
39114   unsigned Width = ShrunkMask.getActiveBits();
39115 
39116   // If the mask is all 0s there's nothing to do here.
39117   if (Width == 0)
39118     return false;
39119 
39120   // Find the next power of 2 width, rounding up to a byte.
39121   Width = llvm::bit_ceil(std::max(Width, 8U));
39122   // Truncate the width to size to handle illegal types.
39123   Width = std::min(Width, EltSize);
39124 
39125   // Calculate a possible zero extend mask for this constant.
39126   APInt ZeroExtendMask = APInt::getLowBitsSet(EltSize, Width);
39127 
39128   // If we aren't changing the mask, just return true to keep it and prevent
39129   // the caller from optimizing.
39130   if (ZeroExtendMask == Mask)
39131     return true;
39132 
39133   // Make sure the new mask can be represented by a combination of mask bits
39134   // and non-demanded bits.
39135   if (!ZeroExtendMask.isSubsetOf(Mask | ~DemandedBits))
39136     return false;
39137 
39138   // Replace the constant with the zero extend mask.
39139   SDLoc DL(Op);
39140   SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
39141   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
39142   return TLO.CombineTo(Op, NewOp);
39143 }
39144 
39145 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
39146                                                       KnownBits &Known,
39147                                                       const APInt &DemandedElts,
39148                                                       const SelectionDAG &DAG,
39149                                                       unsigned Depth) const {
39150   unsigned BitWidth = Known.getBitWidth();
39151   unsigned NumElts = DemandedElts.getBitWidth();
39152   unsigned Opc = Op.getOpcode();
39153   EVT VT = Op.getValueType();
39154   assert((Opc >= ISD::BUILTIN_OP_END ||
39155           Opc == ISD::INTRINSIC_WO_CHAIN ||
39156           Opc == ISD::INTRINSIC_W_CHAIN ||
39157           Opc == ISD::INTRINSIC_VOID) &&
39158          "Should use MaskedValueIsZero if you don't know whether Op"
39159          " is a target node!");
39160 
39161   Known.resetAll();
39162   switch (Opc) {
39163   default: break;
39164   case X86ISD::MUL_IMM: {
39165     KnownBits Known2;
39166     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
39167     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
39168     Known = KnownBits::mul(Known, Known2);
39169     break;
39170   }
39171   case X86ISD::SETCC:
39172     Known.Zero.setBitsFrom(1);
39173     break;
39174   case X86ISD::MOVMSK: {
39175     unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
39176     Known.Zero.setBitsFrom(NumLoBits);
39177     break;
39178   }
39179   case X86ISD::PEXTRB:
39180   case X86ISD::PEXTRW: {
39181     SDValue Src = Op.getOperand(0);
39182     EVT SrcVT = Src.getValueType();
39183     APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
39184                                             Op.getConstantOperandVal(1));
39185     Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
39186     Known = Known.anyextOrTrunc(BitWidth);
39187     Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
39188     break;
39189   }
39190   case X86ISD::VSRAI:
39191   case X86ISD::VSHLI:
39192   case X86ISD::VSRLI: {
39193     unsigned ShAmt = Op.getConstantOperandVal(1);
39194     if (ShAmt >= VT.getScalarSizeInBits()) {
39195       // Out of range logical bit shifts are guaranteed to be zero.
39196       // Out of range arithmetic bit shifts splat the sign bit.
39197       if (Opc != X86ISD::VSRAI) {
39198         Known.setAllZero();
39199         break;
39200       }
39201 
39202       ShAmt = VT.getScalarSizeInBits() - 1;
39203     }
39204 
39205     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
39206     if (Opc == X86ISD::VSHLI) {
39207       Known.Zero <<= ShAmt;
39208       Known.One <<= ShAmt;
39209       // Low bits are known zero.
39210       Known.Zero.setLowBits(ShAmt);
39211     } else if (Opc == X86ISD::VSRLI) {
39212       Known.Zero.lshrInPlace(ShAmt);
39213       Known.One.lshrInPlace(ShAmt);
39214       // High bits are known zero.
39215       Known.Zero.setHighBits(ShAmt);
39216     } else {
39217       Known.Zero.ashrInPlace(ShAmt);
39218       Known.One.ashrInPlace(ShAmt);
39219     }
39220     break;
39221   }
39222   case X86ISD::PACKUS: {
39223     // PACKUS is just a truncation if the upper half is zero.
39224     APInt DemandedLHS, DemandedRHS;
39225     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
39226 
39227     Known.One = APInt::getAllOnes(BitWidth * 2);
39228     Known.Zero = APInt::getAllOnes(BitWidth * 2);
39229 
39230     KnownBits Known2;
39231     if (!!DemandedLHS) {
39232       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
39233       Known = Known.intersectWith(Known2);
39234     }
39235     if (!!DemandedRHS) {
39236       Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
39237       Known = Known.intersectWith(Known2);
39238     }
39239 
39240     if (Known.countMinLeadingZeros() < BitWidth)
39241       Known.resetAll();
39242     Known = Known.trunc(BitWidth);
39243     break;
39244   }
39245   case X86ISD::VBROADCAST: {
39246     SDValue Src = Op.getOperand(0);
39247     if (!Src.getSimpleValueType().isVector()) {
39248       Known = DAG.computeKnownBits(Src, Depth + 1);
39249       return;
39250     }
39251     break;
39252   }
39253   case X86ISD::AND: {
39254     if (Op.getResNo() == 0) {
39255       KnownBits Known2;
39256       Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
39257       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
39258       Known &= Known2;
39259     }
39260     break;
39261   }
39262   case X86ISD::ANDNP: {
39263     KnownBits Known2;
39264     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
39265     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
39266 
39267     // ANDNP = (~X & Y);
39268     Known.One &= Known2.Zero;
39269     Known.Zero |= Known2.One;
39270     break;
39271   }
39272   case X86ISD::FOR: {
39273     KnownBits Known2;
39274     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
39275     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
39276 
39277     Known |= Known2;
39278     break;
39279   }
39280   case X86ISD::PSADBW: {
39281     assert(VT.getScalarType() == MVT::i64 &&
39282            Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
39283            "Unexpected PSADBW types");
39284 
39285     // PSADBW - fills low 16 bits and zeros upper 48 bits of each i64 result.
39286     Known.Zero.setBitsFrom(16);
39287     break;
39288   }
39289   case X86ISD::PCMPGT:
39290   case X86ISD::PCMPEQ: {
39291     KnownBits KnownLhs =
39292         DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
39293     KnownBits KnownRhs =
39294         DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
39295     std::optional<bool> Res = Opc == X86ISD::PCMPEQ
39296                                   ? KnownBits::eq(KnownLhs, KnownRhs)
39297                                   : KnownBits::sgt(KnownLhs, KnownRhs);
39298     if (Res) {
39299       if (*Res)
39300         Known.setAllOnes();
39301       else
39302         Known.setAllZero();
39303     }
39304     break;
39305   }
39306   case X86ISD::PMULUDQ: {
39307     KnownBits Known2;
39308     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
39309     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
39310 
39311     Known = Known.trunc(BitWidth / 2).zext(BitWidth);
39312     Known2 = Known2.trunc(BitWidth / 2).zext(BitWidth);
39313     Known = KnownBits::mul(Known, Known2);
39314     break;
39315   }
39316   case X86ISD::CMOV: {
39317     Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
39318     // If we don't know any bits, early out.
39319     if (Known.isUnknown())
39320       break;
39321     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
39322 
39323     // Only known if known in both the LHS and RHS.
39324     Known = Known.intersectWith(Known2);
39325     break;
39326   }
39327   case X86ISD::BEXTR:
39328   case X86ISD::BEXTRI: {
39329     SDValue Op0 = Op.getOperand(0);
39330     SDValue Op1 = Op.getOperand(1);
39331 
39332     if (auto* Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
39333       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
39334       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
39335 
39336       // If the length is 0, the result is 0.
39337       if (Length == 0) {
39338         Known.setAllZero();
39339         break;
39340       }
39341 
39342       if ((Shift + Length) <= BitWidth) {
39343         Known = DAG.computeKnownBits(Op0, Depth + 1);
39344         Known = Known.extractBits(Length, Shift);
39345         Known = Known.zextOrTrunc(BitWidth);
39346       }
39347     }
39348     break;
39349   }
39350   case X86ISD::PDEP: {
39351     KnownBits Known2;
39352     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
39353     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
39354     // Zeros are retained from the mask operand. But not ones.
39355     Known.One.clearAllBits();
39356     // The result will have at least as many trailing zeros as the non-mask
39357     // operand since bits can only map to the same or higher bit position.
39358     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
39359     break;
39360   }
39361   case X86ISD::PEXT: {
39362     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
39363     // The result has as many leading zeros as the number of zeroes in the mask.
39364     unsigned Count = Known.Zero.popcount();
39365     Known.Zero = APInt::getHighBitsSet(BitWidth, Count);
39366     Known.One.clearAllBits();
39367     break;
39368   }
39369   case X86ISD::VTRUNC:
39370   case X86ISD::VTRUNCS:
39371   case X86ISD::VTRUNCUS:
39372   case X86ISD::CVTSI2P:
39373   case X86ISD::CVTUI2P:
39374   case X86ISD::CVTP2SI:
39375   case X86ISD::CVTP2UI:
39376   case X86ISD::MCVTP2SI:
39377   case X86ISD::MCVTP2UI:
39378   case X86ISD::CVTTP2SI:
39379   case X86ISD::CVTTP2UI:
39380   case X86ISD::MCVTTP2SI:
39381   case X86ISD::MCVTTP2UI:
39382   case X86ISD::MCVTSI2P:
39383   case X86ISD::MCVTUI2P:
39384   case X86ISD::VFPROUND:
39385   case X86ISD::VMFPROUND:
39386   case X86ISD::CVTPS2PH:
39387   case X86ISD::MCVTPS2PH: {
39388     // Truncations/Conversions - upper elements are known zero.
39389     EVT SrcVT = Op.getOperand(0).getValueType();
39390     if (SrcVT.isVector()) {
39391       unsigned NumSrcElts = SrcVT.getVectorNumElements();
39392       if (NumElts > NumSrcElts && DemandedElts.countr_zero() >= NumSrcElts)
39393         Known.setAllZero();
39394     }
39395     break;
39396   }
39397   case X86ISD::STRICT_CVTTP2SI:
39398   case X86ISD::STRICT_CVTTP2UI:
39399   case X86ISD::STRICT_CVTSI2P:
39400   case X86ISD::STRICT_CVTUI2P:
39401   case X86ISD::STRICT_VFPROUND:
39402   case X86ISD::STRICT_CVTPS2PH: {
39403     // Strict Conversions - upper elements are known zero.
39404     EVT SrcVT = Op.getOperand(1).getValueType();
39405     if (SrcVT.isVector()) {
39406       unsigned NumSrcElts = SrcVT.getVectorNumElements();
39407       if (NumElts > NumSrcElts && DemandedElts.countr_zero() >= NumSrcElts)
39408         Known.setAllZero();
39409     }
39410     break;
39411   }
39412   case X86ISD::MOVQ2DQ: {
39413     // Move from MMX to XMM. Upper half of XMM should be 0.
39414     if (DemandedElts.countr_zero() >= (NumElts / 2))
39415       Known.setAllZero();
39416     break;
39417   }
39418   case X86ISD::VBROADCAST_LOAD: {
39419     APInt UndefElts;
39420     SmallVector<APInt, 16> EltBits;
39421     if (getTargetConstantBitsFromNode(Op, BitWidth, UndefElts, EltBits,
39422                                       /*AllowWholeUndefs*/ false,
39423                                       /*AllowPartialUndefs*/ false)) {
39424       Known.Zero.setAllBits();
39425       Known.One.setAllBits();
39426       for (unsigned I = 0; I != NumElts; ++I) {
39427         if (!DemandedElts[I])
39428           continue;
39429         if (UndefElts[I]) {
39430           Known.resetAll();
39431           break;
39432         }
39433         KnownBits Known2 = KnownBits::makeConstant(EltBits[I]);
39434         Known = Known.intersectWith(Known2);
39435       }
39436       return;
39437     }
39438     break;
39439   }
39440   }
39441 
39442   // Handle target shuffles.
39443   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
39444   if (isTargetShuffle(Opc)) {
39445     SmallVector<int, 64> Mask;
39446     SmallVector<SDValue, 2> Ops;
39447     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
39448       unsigned NumOps = Ops.size();
39449       unsigned NumElts = VT.getVectorNumElements();
39450       if (Mask.size() == NumElts) {
39451         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
39452         Known.Zero.setAllBits(); Known.One.setAllBits();
39453         for (unsigned i = 0; i != NumElts; ++i) {
39454           if (!DemandedElts[i])
39455             continue;
39456           int M = Mask[i];
39457           if (M == SM_SentinelUndef) {
39458             // For UNDEF elements, we don't know anything about the common state
39459             // of the shuffle result.
39460             Known.resetAll();
39461             break;
39462           }
39463           if (M == SM_SentinelZero) {
39464             Known.One.clearAllBits();
39465             continue;
39466           }
39467           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
39468                  "Shuffle index out of range");
39469 
39470           unsigned OpIdx = (unsigned)M / NumElts;
39471           unsigned EltIdx = (unsigned)M % NumElts;
39472           if (Ops[OpIdx].getValueType() != VT) {
39473             // TODO - handle target shuffle ops with different value types.
39474             Known.resetAll();
39475             break;
39476           }
39477           DemandedOps[OpIdx].setBit(EltIdx);
39478         }
39479         // Known bits are the values that are shared by every demanded element.
39480         for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
39481           if (!DemandedOps[i])
39482             continue;
39483           KnownBits Known2 =
39484               DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
39485           Known = Known.intersectWith(Known2);
39486         }
39487       }
39488     }
39489   }
39490 }
39491 
39492 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
39493     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
39494     unsigned Depth) const {
39495   EVT VT = Op.getValueType();
39496   unsigned VTBits = VT.getScalarSizeInBits();
39497   unsigned Opcode = Op.getOpcode();
39498   switch (Opcode) {
39499   case X86ISD::SETCC_CARRY:
39500     // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
39501     return VTBits;
39502 
39503   case X86ISD::VTRUNC: {
39504     SDValue Src = Op.getOperand(0);
39505     MVT SrcVT = Src.getSimpleValueType();
39506     unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
39507     assert(VTBits < NumSrcBits && "Illegal truncation input type");
39508     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
39509     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
39510     if (Tmp > (NumSrcBits - VTBits))
39511       return Tmp - (NumSrcBits - VTBits);
39512     return 1;
39513   }
39514 
39515   case X86ISD::PACKSS: {
39516     // PACKSS is just a truncation if the sign bits extend to the packed size.
39517     APInt DemandedLHS, DemandedRHS;
39518     getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
39519                         DemandedRHS);
39520 
39521     // Helper to detect PACKSSDW(BITCAST(PACKSSDW(X)),BITCAST(PACKSSDW(Y)))
39522     // patterns often used to compact vXi64 allsignbit patterns.
39523     auto NumSignBitsPACKSS = [&](SDValue V, const APInt &Elts) -> unsigned {
39524       SDValue BC = peekThroughBitcasts(V);
39525       if (BC.getOpcode() == X86ISD::PACKSS &&
39526           BC.getScalarValueSizeInBits() == 16 &&
39527           V.getScalarValueSizeInBits() == 32) {
39528         SDValue BC0 = peekThroughBitcasts(BC.getOperand(0));
39529         SDValue BC1 = peekThroughBitcasts(BC.getOperand(1));
39530         if (BC0.getScalarValueSizeInBits() == 64 &&
39531             BC1.getScalarValueSizeInBits() == 64 &&
39532             DAG.ComputeNumSignBits(BC0, Depth + 1) == 64 &&
39533             DAG.ComputeNumSignBits(BC1, Depth + 1) == 64)
39534           return 32;
39535       }
39536       return DAG.ComputeNumSignBits(V, Elts, Depth + 1);
39537     };
39538 
39539     unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
39540     unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
39541     if (!!DemandedLHS)
39542       Tmp0 = NumSignBitsPACKSS(Op.getOperand(0), DemandedLHS);
39543     if (!!DemandedRHS)
39544       Tmp1 = NumSignBitsPACKSS(Op.getOperand(1), DemandedRHS);
39545     unsigned Tmp = std::min(Tmp0, Tmp1);
39546     if (Tmp > (SrcBits - VTBits))
39547       return Tmp - (SrcBits - VTBits);
39548     return 1;
39549   }
39550 
39551   case X86ISD::VBROADCAST: {
39552     SDValue Src = Op.getOperand(0);
39553     if (!Src.getSimpleValueType().isVector())
39554       return DAG.ComputeNumSignBits(Src, Depth + 1);
39555     break;
39556   }
39557 
39558   case X86ISD::VSHLI: {
39559     SDValue Src = Op.getOperand(0);
39560     const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
39561     if (ShiftVal.uge(VTBits))
39562       return VTBits; // Shifted all bits out --> zero.
39563     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
39564     if (ShiftVal.uge(Tmp))
39565       return 1; // Shifted all sign bits out --> unknown.
39566     return Tmp - ShiftVal.getZExtValue();
39567   }
39568 
39569   case X86ISD::VSRAI: {
39570     SDValue Src = Op.getOperand(0);
39571     APInt ShiftVal = Op.getConstantOperandAPInt(1);
39572     if (ShiftVal.uge(VTBits - 1))
39573       return VTBits; // Sign splat.
39574     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
39575     ShiftVal += Tmp;
39576     return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
39577   }
39578 
39579   case X86ISD::FSETCC:
39580     // cmpss/cmpsd return zero/all-bits result values in the bottom element.
39581     if (VT == MVT::f32 || VT == MVT::f64 ||
39582         ((VT == MVT::v4f32 || VT == MVT::v2f64) && DemandedElts == 1))
39583       return VTBits;
39584     break;
39585 
39586   case X86ISD::PCMPGT:
39587   case X86ISD::PCMPEQ:
39588   case X86ISD::CMPP:
39589   case X86ISD::VPCOM:
39590   case X86ISD::VPCOMU:
39591     // Vector compares return zero/all-bits result values.
39592     return VTBits;
39593 
39594   case X86ISD::ANDNP: {
39595     unsigned Tmp0 =
39596         DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
39597     if (Tmp0 == 1) return 1; // Early out.
39598     unsigned Tmp1 =
39599         DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
39600     return std::min(Tmp0, Tmp1);
39601   }
39602 
39603   case X86ISD::CMOV: {
39604     unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
39605     if (Tmp0 == 1) return 1;  // Early out.
39606     unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
39607     return std::min(Tmp0, Tmp1);
39608   }
39609   }
39610 
39611   // Handle target shuffles.
39612   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
39613   if (isTargetShuffle(Opcode)) {
39614     SmallVector<int, 64> Mask;
39615     SmallVector<SDValue, 2> Ops;
39616     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
39617       unsigned NumOps = Ops.size();
39618       unsigned NumElts = VT.getVectorNumElements();
39619       if (Mask.size() == NumElts) {
39620         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
39621         for (unsigned i = 0; i != NumElts; ++i) {
39622           if (!DemandedElts[i])
39623             continue;
39624           int M = Mask[i];
39625           if (M == SM_SentinelUndef) {
39626             // For UNDEF elements, we don't know anything about the common state
39627             // of the shuffle result.
39628             return 1;
39629           } else if (M == SM_SentinelZero) {
39630             // Zero = all sign bits.
39631             continue;
39632           }
39633           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
39634                  "Shuffle index out of range");
39635 
39636           unsigned OpIdx = (unsigned)M / NumElts;
39637           unsigned EltIdx = (unsigned)M % NumElts;
39638           if (Ops[OpIdx].getValueType() != VT) {
39639             // TODO - handle target shuffle ops with different value types.
39640             return 1;
39641           }
39642           DemandedOps[OpIdx].setBit(EltIdx);
39643         }
39644         unsigned Tmp0 = VTBits;
39645         for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
39646           if (!DemandedOps[i])
39647             continue;
39648           unsigned Tmp1 =
39649               DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
39650           Tmp0 = std::min(Tmp0, Tmp1);
39651         }
39652         return Tmp0;
39653       }
39654     }
39655   }
39656 
39657   // Fallback case.
39658   return 1;
39659 }
39660 
39661 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
39662   if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
39663     return N->getOperand(0);
39664   return N;
39665 }
39666 
39667 // Helper to look for a normal load that can be narrowed into a vzload with the
39668 // specified VT and memory VT. Returns SDValue() on failure.
39669 static SDValue narrowLoadToVZLoad(LoadSDNode *LN, MVT MemVT, MVT VT,
39670                                   SelectionDAG &DAG) {
39671   // Can't if the load is volatile or atomic.
39672   if (!LN->isSimple())
39673     return SDValue();
39674 
39675   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39676   SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
39677   return DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, SDLoc(LN), Tys, Ops, MemVT,
39678                                  LN->getPointerInfo(), LN->getOriginalAlign(),
39679                                  LN->getMemOperand()->getFlags());
39680 }
39681 
39682 // Attempt to match a combined shuffle mask against supported unary shuffle
39683 // instructions.
39684 // TODO: Investigate sharing more of this with shuffle lowering.
39685 static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
39686                               bool AllowFloatDomain, bool AllowIntDomain,
39687                               SDValue V1, const SelectionDAG &DAG,
39688                               const X86Subtarget &Subtarget, unsigned &Shuffle,
39689                               MVT &SrcVT, MVT &DstVT) {
39690   unsigned NumMaskElts = Mask.size();
39691   unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
39692 
39693   // Match against a VZEXT_MOVL vXi32 and vXi16 zero-extending instruction.
39694   if (Mask[0] == 0 &&
39695       (MaskEltSize == 32 || (MaskEltSize == 16 && Subtarget.hasFP16()))) {
39696     if ((isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) ||
39697         (V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
39698          isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1))) {
39699       Shuffle = X86ISD::VZEXT_MOVL;
39700       if (MaskEltSize == 16)
39701         SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
39702       else
39703         SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
39704       return true;
39705     }
39706   }
39707 
39708   // Match against a ANY/SIGN/ZERO_EXTEND_VECTOR_INREG instruction.
39709   // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
39710   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
39711                          (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
39712     unsigned MaxScale = 64 / MaskEltSize;
39713     bool UseSign = V1.getScalarValueSizeInBits() == MaskEltSize &&
39714                    DAG.ComputeNumSignBits(V1) == MaskEltSize;
39715     for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
39716       bool MatchAny = true;
39717       bool MatchZero = true;
39718       bool MatchSign = UseSign;
39719       unsigned NumDstElts = NumMaskElts / Scale;
39720       for (unsigned i = 0;
39721            i != NumDstElts && (MatchAny || MatchSign || MatchZero); ++i) {
39722         if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
39723           MatchAny = MatchSign = MatchZero = false;
39724           break;
39725         }
39726         unsigned Pos = (i * Scale) + 1;
39727         unsigned Len = Scale - 1;
39728         MatchAny &= isUndefInRange(Mask, Pos, Len);
39729         MatchZero &= isUndefOrZeroInRange(Mask, Pos, Len);
39730         MatchSign &= isUndefOrEqualInRange(Mask, (int)i, Pos, Len);
39731       }
39732       if (MatchAny || MatchSign || MatchZero) {
39733         assert((MatchSign || MatchZero) &&
39734                "Failed to match sext/zext but matched aext?");
39735         unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
39736         MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType()
39737                                           : MVT::getIntegerVT(MaskEltSize);
39738         SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
39739 
39740         Shuffle = unsigned(
39741             MatchAny ? ISD::ANY_EXTEND
39742                      : (MatchSign ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND));
39743         if (SrcVT.getVectorNumElements() != NumDstElts)
39744           Shuffle = DAG.getOpcode_EXTEND_VECTOR_INREG(Shuffle);
39745 
39746         DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
39747         DstVT = MVT::getVectorVT(DstVT, NumDstElts);
39748         return true;
39749       }
39750     }
39751   }
39752 
39753   // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
39754   if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2()) ||
39755        (MaskEltSize == 16 && Subtarget.hasFP16())) &&
39756       isUndefOrEqual(Mask[0], 0) &&
39757       isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
39758     Shuffle = X86ISD::VZEXT_MOVL;
39759     if (MaskEltSize == 16)
39760       SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
39761     else
39762       SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
39763     return true;
39764   }
39765 
39766   // Check if we have SSE3 which will let us use MOVDDUP etc. The
39767   // instructions are no slower than UNPCKLPD but has the option to
39768   // fold the input operand into even an unaligned memory load.
39769   if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
39770     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, DAG, V1)) {
39771       Shuffle = X86ISD::MOVDDUP;
39772       SrcVT = DstVT = MVT::v2f64;
39773       return true;
39774     }
39775     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, DAG, V1)) {
39776       Shuffle = X86ISD::MOVSLDUP;
39777       SrcVT = DstVT = MVT::v4f32;
39778       return true;
39779     }
39780     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3}, DAG, V1)) {
39781       Shuffle = X86ISD::MOVSHDUP;
39782       SrcVT = DstVT = MVT::v4f32;
39783       return true;
39784     }
39785   }
39786 
39787   if (MaskVT.is256BitVector() && AllowFloatDomain) {
39788     assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
39789     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, DAG, V1)) {
39790       Shuffle = X86ISD::MOVDDUP;
39791       SrcVT = DstVT = MVT::v4f64;
39792       return true;
39793     }
39794     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, DAG,
39795                                   V1)) {
39796       Shuffle = X86ISD::MOVSLDUP;
39797       SrcVT = DstVT = MVT::v8f32;
39798       return true;
39799     }
39800     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3, 5, 5, 7, 7}, DAG,
39801                                   V1)) {
39802       Shuffle = X86ISD::MOVSHDUP;
39803       SrcVT = DstVT = MVT::v8f32;
39804       return true;
39805     }
39806   }
39807 
39808   if (MaskVT.is512BitVector() && AllowFloatDomain) {
39809     assert(Subtarget.hasAVX512() &&
39810            "AVX512 required for 512-bit vector shuffles");
39811     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, DAG,
39812                                   V1)) {
39813       Shuffle = X86ISD::MOVDDUP;
39814       SrcVT = DstVT = MVT::v8f64;
39815       return true;
39816     }
39817     if (isTargetShuffleEquivalent(
39818             MaskVT, Mask,
39819             {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14}, DAG, V1)) {
39820       Shuffle = X86ISD::MOVSLDUP;
39821       SrcVT = DstVT = MVT::v16f32;
39822       return true;
39823     }
39824     if (isTargetShuffleEquivalent(
39825             MaskVT, Mask,
39826             {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15}, DAG, V1)) {
39827       Shuffle = X86ISD::MOVSHDUP;
39828       SrcVT = DstVT = MVT::v16f32;
39829       return true;
39830     }
39831   }
39832 
39833   return false;
39834 }
39835 
39836 // Attempt to match a combined shuffle mask against supported unary immediate
39837 // permute instructions.
39838 // TODO: Investigate sharing more of this with shuffle lowering.
39839 static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
39840                                      const APInt &Zeroable,
39841                                      bool AllowFloatDomain, bool AllowIntDomain,
39842                                      const SelectionDAG &DAG,
39843                                      const X86Subtarget &Subtarget,
39844                                      unsigned &Shuffle, MVT &ShuffleVT,
39845                                      unsigned &PermuteImm) {
39846   unsigned NumMaskElts = Mask.size();
39847   unsigned InputSizeInBits = MaskVT.getSizeInBits();
39848   unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
39849   MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
39850   bool ContainsZeros = isAnyZero(Mask);
39851 
39852   // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
39853   if (!ContainsZeros && MaskScalarSizeInBits == 64) {
39854     // Check for lane crossing permutes.
39855     if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
39856       // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
39857       if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
39858         Shuffle = X86ISD::VPERMI;
39859         ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
39860         PermuteImm = getV4X86ShuffleImm(Mask);
39861         return true;
39862       }
39863       if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
39864         SmallVector<int, 4> RepeatedMask;
39865         if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
39866           Shuffle = X86ISD::VPERMI;
39867           ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
39868           PermuteImm = getV4X86ShuffleImm(RepeatedMask);
39869           return true;
39870         }
39871       }
39872     } else if (AllowFloatDomain && Subtarget.hasAVX()) {
39873       // VPERMILPD can permute with a non-repeating shuffle.
39874       Shuffle = X86ISD::VPERMILPI;
39875       ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
39876       PermuteImm = 0;
39877       for (int i = 0, e = Mask.size(); i != e; ++i) {
39878         int M = Mask[i];
39879         if (M == SM_SentinelUndef)
39880           continue;
39881         assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
39882         PermuteImm |= (M & 1) << i;
39883       }
39884       return true;
39885     }
39886   }
39887 
39888   // We are checking for shuffle match or shift match. Loop twice so we can
39889   // order which we try and match first depending on target preference.
39890   for (unsigned Order = 0; Order < 2; ++Order) {
39891     if (Subtarget.preferLowerShuffleAsShift() ? (Order == 1) : (Order == 0)) {
39892       // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
39893       // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
39894       // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
39895       if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
39896           !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
39897         SmallVector<int, 4> RepeatedMask;
39898         if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
39899           // Narrow the repeated mask to create 32-bit element permutes.
39900           SmallVector<int, 4> WordMask = RepeatedMask;
39901           if (MaskScalarSizeInBits == 64)
39902             narrowShuffleMaskElts(2, RepeatedMask, WordMask);
39903 
39904           Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
39905           ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
39906           ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
39907           PermuteImm = getV4X86ShuffleImm(WordMask);
39908           return true;
39909         }
39910       }
39911 
39912       // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
39913       if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16 &&
39914           ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
39915            (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
39916            (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
39917         SmallVector<int, 4> RepeatedMask;
39918         if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
39919           ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
39920           ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
39921 
39922           // PSHUFLW: permute lower 4 elements only.
39923           if (isUndefOrInRange(LoMask, 0, 4) &&
39924               isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
39925             Shuffle = X86ISD::PSHUFLW;
39926             ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
39927             PermuteImm = getV4X86ShuffleImm(LoMask);
39928             return true;
39929           }
39930 
39931           // PSHUFHW: permute upper 4 elements only.
39932           if (isUndefOrInRange(HiMask, 4, 8) &&
39933               isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
39934             // Offset the HiMask so that we can create the shuffle immediate.
39935             int OffsetHiMask[4];
39936             for (int i = 0; i != 4; ++i)
39937               OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
39938 
39939             Shuffle = X86ISD::PSHUFHW;
39940             ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
39941             PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
39942             return true;
39943           }
39944         }
39945       }
39946     } else {
39947       // Attempt to match against bit rotates.
39948       if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits < 64 &&
39949           ((MaskVT.is128BitVector() && Subtarget.hasXOP()) ||
39950            Subtarget.hasAVX512())) {
39951         int RotateAmt = matchShuffleAsBitRotate(ShuffleVT, MaskScalarSizeInBits,
39952                                                 Subtarget, Mask);
39953         if (0 < RotateAmt) {
39954           Shuffle = X86ISD::VROTLI;
39955           PermuteImm = (unsigned)RotateAmt;
39956           return true;
39957         }
39958       }
39959     }
39960     // Attempt to match against byte/bit shifts.
39961     if (AllowIntDomain &&
39962         ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
39963          (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
39964          (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
39965       int ShiftAmt =
39966           matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits, Mask, 0,
39967                               Zeroable, Subtarget);
39968       if (0 < ShiftAmt && (!ShuffleVT.is512BitVector() || Subtarget.hasBWI() ||
39969                            32 <= ShuffleVT.getScalarSizeInBits())) {
39970         // Byte shifts can be slower so only match them on second attempt.
39971         if (Order == 0 &&
39972             (Shuffle == X86ISD::VSHLDQ || Shuffle == X86ISD::VSRLDQ))
39973           continue;
39974 
39975         PermuteImm = (unsigned)ShiftAmt;
39976         return true;
39977       }
39978 
39979     }
39980   }
39981 
39982   return false;
39983 }
39984 
39985 // Attempt to match a combined unary shuffle mask against supported binary
39986 // shuffle instructions.
39987 // TODO: Investigate sharing more of this with shuffle lowering.
39988 static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
39989                                bool AllowFloatDomain, bool AllowIntDomain,
39990                                SDValue &V1, SDValue &V2, const SDLoc &DL,
39991                                SelectionDAG &DAG, const X86Subtarget &Subtarget,
39992                                unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
39993                                bool IsUnary) {
39994   unsigned NumMaskElts = Mask.size();
39995   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
39996   unsigned SizeInBits = MaskVT.getSizeInBits();
39997 
39998   if (MaskVT.is128BitVector()) {
39999     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, DAG) &&
40000         AllowFloatDomain) {
40001       V2 = V1;
40002       V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
40003       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
40004       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
40005       return true;
40006     }
40007     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1}, DAG) &&
40008         AllowFloatDomain) {
40009       V2 = V1;
40010       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
40011       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
40012       return true;
40013     }
40014     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 3}, DAG) &&
40015         Subtarget.hasSSE2() && (AllowFloatDomain || !Subtarget.hasSSE41())) {
40016       std::swap(V1, V2);
40017       Shuffle = X86ISD::MOVSD;
40018       SrcVT = DstVT = MVT::v2f64;
40019       return true;
40020     }
40021     if (isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}, DAG) &&
40022         (AllowFloatDomain || !Subtarget.hasSSE41())) {
40023       Shuffle = X86ISD::MOVSS;
40024       SrcVT = DstVT = MVT::v4f32;
40025       return true;
40026     }
40027     if (isTargetShuffleEquivalent(MaskVT, Mask, {8, 1, 2, 3, 4, 5, 6, 7},
40028                                   DAG) &&
40029         Subtarget.hasFP16()) {
40030       Shuffle = X86ISD::MOVSH;
40031       SrcVT = DstVT = MVT::v8f16;
40032       return true;
40033     }
40034   }
40035 
40036   // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
40037   if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
40038       ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
40039       ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
40040     if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
40041                              Subtarget)) {
40042       DstVT = MaskVT;
40043       return true;
40044     }
40045   }
40046   // TODO: Can we handle this inside matchShuffleWithPACK?
40047   if (MaskVT == MVT::v4i32 && Subtarget.hasSSE2() &&
40048       isTargetShuffleEquivalent(MaskVT, Mask, {0, 2, 4, 6}, DAG) &&
40049       V1.getScalarValueSizeInBits() == 64 &&
40050       V2.getScalarValueSizeInBits() == 64) {
40051     // Use (SSE41) PACKUSWD if the leading zerobits goto the lowest 16-bits.
40052     unsigned MinLZV1 = DAG.computeKnownBits(V1).countMinLeadingZeros();
40053     unsigned MinLZV2 = DAG.computeKnownBits(V2).countMinLeadingZeros();
40054     if (Subtarget.hasSSE41() && MinLZV1 >= 48 && MinLZV2 >= 48) {
40055       SrcVT = MVT::v4i32;
40056       DstVT = MVT::v8i16;
40057       Shuffle = X86ISD::PACKUS;
40058       return true;
40059     }
40060     // Use PACKUSBW if the leading zerobits goto the lowest 8-bits.
40061     if (MinLZV1 >= 56 && MinLZV2 >= 56) {
40062       SrcVT = MVT::v8i16;
40063       DstVT = MVT::v16i8;
40064       Shuffle = X86ISD::PACKUS;
40065       return true;
40066     }
40067     // Use PACKSSWD if the signbits extend to the lowest 16-bits.
40068     if (DAG.ComputeNumSignBits(V1) > 48 && DAG.ComputeNumSignBits(V2) > 48) {
40069       SrcVT = MVT::v4i32;
40070       DstVT = MVT::v8i16;
40071       Shuffle = X86ISD::PACKSS;
40072       return true;
40073     }
40074   }
40075 
40076   // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
40077   if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
40078       (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
40079       (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
40080       (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
40081       (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
40082     if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
40083                               Subtarget)) {
40084       SrcVT = DstVT = MaskVT;
40085       if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
40086         SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
40087       return true;
40088     }
40089   }
40090 
40091   // Attempt to match against a OR if we're performing a blend shuffle and the
40092   // non-blended source element is zero in each case.
40093   // TODO: Handle cases where V1/V2 sizes doesn't match SizeInBits.
40094   if (SizeInBits == V1.getValueSizeInBits() &&
40095       SizeInBits == V2.getValueSizeInBits() &&
40096       (EltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
40097       (EltSizeInBits % V2.getScalarValueSizeInBits()) == 0) {
40098     bool IsBlend = true;
40099     unsigned NumV1Elts = V1.getValueType().getVectorNumElements();
40100     unsigned NumV2Elts = V2.getValueType().getVectorNumElements();
40101     unsigned Scale1 = NumV1Elts / NumMaskElts;
40102     unsigned Scale2 = NumV2Elts / NumMaskElts;
40103     APInt DemandedZeroV1 = APInt::getZero(NumV1Elts);
40104     APInt DemandedZeroV2 = APInt::getZero(NumV2Elts);
40105     for (unsigned i = 0; i != NumMaskElts; ++i) {
40106       int M = Mask[i];
40107       if (M == SM_SentinelUndef)
40108         continue;
40109       if (M == SM_SentinelZero) {
40110         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
40111         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
40112         continue;
40113       }
40114       if (M == (int)i) {
40115         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
40116         continue;
40117       }
40118       if (M == (int)(i + NumMaskElts)) {
40119         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
40120         continue;
40121       }
40122       IsBlend = false;
40123       break;
40124     }
40125     if (IsBlend) {
40126       if (DAG.MaskedVectorIsZero(V1, DemandedZeroV1) &&
40127           DAG.MaskedVectorIsZero(V2, DemandedZeroV2)) {
40128         Shuffle = ISD::OR;
40129         SrcVT = DstVT = MaskVT.changeTypeToInteger();
40130         return true;
40131       }
40132       if (NumV1Elts == NumV2Elts && NumV1Elts == NumMaskElts) {
40133         // FIXME: handle mismatched sizes?
40134         // TODO: investigate if `ISD::OR` handling in
40135         // `TargetLowering::SimplifyDemandedVectorElts` can be improved instead.
40136         auto computeKnownBitsElementWise = [&DAG](SDValue V) {
40137           unsigned NumElts = V.getValueType().getVectorNumElements();
40138           KnownBits Known(NumElts);
40139           for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
40140             APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
40141             KnownBits PeepholeKnown = DAG.computeKnownBits(V, Mask);
40142             if (PeepholeKnown.isZero())
40143               Known.Zero.setBit(EltIdx);
40144             if (PeepholeKnown.isAllOnes())
40145               Known.One.setBit(EltIdx);
40146           }
40147           return Known;
40148         };
40149 
40150         KnownBits V1Known = computeKnownBitsElementWise(V1);
40151         KnownBits V2Known = computeKnownBitsElementWise(V2);
40152 
40153         for (unsigned i = 0; i != NumMaskElts && IsBlend; ++i) {
40154           int M = Mask[i];
40155           if (M == SM_SentinelUndef)
40156             continue;
40157           if (M == SM_SentinelZero) {
40158             IsBlend &= V1Known.Zero[i] && V2Known.Zero[i];
40159             continue;
40160           }
40161           if (M == (int)i) {
40162             IsBlend &= V2Known.Zero[i] || V1Known.One[i];
40163             continue;
40164           }
40165           if (M == (int)(i + NumMaskElts)) {
40166             IsBlend &= V1Known.Zero[i] || V2Known.One[i];
40167             continue;
40168           }
40169           llvm_unreachable("will not get here.");
40170         }
40171         if (IsBlend) {
40172           Shuffle = ISD::OR;
40173           SrcVT = DstVT = MaskVT.changeTypeToInteger();
40174           return true;
40175         }
40176       }
40177     }
40178   }
40179 
40180   return false;
40181 }
40182 
40183 static bool matchBinaryPermuteShuffle(
40184     MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
40185     bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
40186     const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
40187     unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
40188   unsigned NumMaskElts = Mask.size();
40189   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
40190 
40191   // Attempt to match against VALIGND/VALIGNQ rotate.
40192   if (AllowIntDomain && (EltSizeInBits == 64 || EltSizeInBits == 32) &&
40193       ((MaskVT.is128BitVector() && Subtarget.hasVLX()) ||
40194        (MaskVT.is256BitVector() && Subtarget.hasVLX()) ||
40195        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
40196     if (!isAnyZero(Mask)) {
40197       int Rotation = matchShuffleAsElementRotate(V1, V2, Mask);
40198       if (0 < Rotation) {
40199         Shuffle = X86ISD::VALIGN;
40200         if (EltSizeInBits == 64)
40201           ShuffleVT = MVT::getVectorVT(MVT::i64, MaskVT.getSizeInBits() / 64);
40202         else
40203           ShuffleVT = MVT::getVectorVT(MVT::i32, MaskVT.getSizeInBits() / 32);
40204         PermuteImm = Rotation;
40205         return true;
40206       }
40207     }
40208   }
40209 
40210   // Attempt to match against PALIGNR byte rotate.
40211   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
40212                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
40213                          (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
40214     int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
40215     if (0 < ByteRotation) {
40216       Shuffle = X86ISD::PALIGNR;
40217       ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
40218       PermuteImm = ByteRotation;
40219       return true;
40220     }
40221   }
40222 
40223   // Attempt to combine to X86ISD::BLENDI.
40224   if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
40225                             (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
40226       (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
40227     uint64_t BlendMask = 0;
40228     bool ForceV1Zero = false, ForceV2Zero = false;
40229     SmallVector<int, 8> TargetMask(Mask);
40230     if (matchShuffleAsBlend(MaskVT, V1, V2, TargetMask, Zeroable, ForceV1Zero,
40231                             ForceV2Zero, BlendMask)) {
40232       if (MaskVT == MVT::v16i16) {
40233         // We can only use v16i16 PBLENDW if the lanes are repeated.
40234         SmallVector<int, 8> RepeatedMask;
40235         if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
40236                                         RepeatedMask)) {
40237           assert(RepeatedMask.size() == 8 &&
40238                  "Repeated mask size doesn't match!");
40239           PermuteImm = 0;
40240           for (int i = 0; i < 8; ++i)
40241             if (RepeatedMask[i] >= 8)
40242               PermuteImm |= 1 << i;
40243           V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
40244           V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
40245           Shuffle = X86ISD::BLENDI;
40246           ShuffleVT = MaskVT;
40247           return true;
40248         }
40249       } else {
40250         V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
40251         V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
40252         PermuteImm = (unsigned)BlendMask;
40253         Shuffle = X86ISD::BLENDI;
40254         ShuffleVT = MaskVT;
40255         return true;
40256       }
40257     }
40258   }
40259 
40260   // Attempt to combine to INSERTPS, but only if it has elements that need to
40261   // be set to zero.
40262   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
40263       MaskVT.is128BitVector() && isAnyZero(Mask) &&
40264       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
40265     Shuffle = X86ISD::INSERTPS;
40266     ShuffleVT = MVT::v4f32;
40267     return true;
40268   }
40269 
40270   // Attempt to combine to SHUFPD.
40271   if (AllowFloatDomain && EltSizeInBits == 64 &&
40272       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
40273        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
40274        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
40275     bool ForceV1Zero = false, ForceV2Zero = false;
40276     if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
40277                                PermuteImm, Mask, Zeroable)) {
40278       V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
40279       V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
40280       Shuffle = X86ISD::SHUFP;
40281       ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
40282       return true;
40283     }
40284   }
40285 
40286   // Attempt to combine to SHUFPS.
40287   if (AllowFloatDomain && EltSizeInBits == 32 &&
40288       ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
40289        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
40290        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
40291     SmallVector<int, 4> RepeatedMask;
40292     if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
40293       // Match each half of the repeated mask, to determine if its just
40294       // referencing one of the vectors, is zeroable or entirely undef.
40295       auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
40296         int M0 = RepeatedMask[Offset];
40297         int M1 = RepeatedMask[Offset + 1];
40298 
40299         if (isUndefInRange(RepeatedMask, Offset, 2)) {
40300           return DAG.getUNDEF(MaskVT);
40301         } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
40302           S0 = (SM_SentinelUndef == M0 ? -1 : 0);
40303           S1 = (SM_SentinelUndef == M1 ? -1 : 1);
40304           return getZeroVector(MaskVT, Subtarget, DAG, DL);
40305         } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
40306           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
40307           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
40308           return V1;
40309         } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
40310           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
40311           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
40312           return V2;
40313         }
40314 
40315         return SDValue();
40316       };
40317 
40318       int ShufMask[4] = {-1, -1, -1, -1};
40319       SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
40320       SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
40321 
40322       if (Lo && Hi) {
40323         V1 = Lo;
40324         V2 = Hi;
40325         Shuffle = X86ISD::SHUFP;
40326         ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
40327         PermuteImm = getV4X86ShuffleImm(ShufMask);
40328         return true;
40329       }
40330     }
40331   }
40332 
40333   // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
40334   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
40335       MaskVT.is128BitVector() &&
40336       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
40337     Shuffle = X86ISD::INSERTPS;
40338     ShuffleVT = MVT::v4f32;
40339     return true;
40340   }
40341 
40342   return false;
40343 }
40344 
40345 static SDValue combineX86ShuffleChainWithExtract(
40346     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
40347     bool HasVariableMask, bool AllowVariableCrossLaneMask,
40348     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
40349     const X86Subtarget &Subtarget);
40350 
40351 /// Combine an arbitrary chain of shuffles into a single instruction if
40352 /// possible.
40353 ///
40354 /// This is the leaf of the recursive combine below. When we have found some
40355 /// chain of single-use x86 shuffle instructions and accumulated the combined
40356 /// shuffle mask represented by them, this will try to pattern match that mask
40357 /// into either a single instruction if there is a special purpose instruction
40358 /// for this operation, or into a PSHUFB instruction which is a fully general
40359 /// instruction but should only be used to replace chains over a certain depth.
40360 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
40361                                       ArrayRef<int> BaseMask, int Depth,
40362                                       bool HasVariableMask,
40363                                       bool AllowVariableCrossLaneMask,
40364                                       bool AllowVariablePerLaneMask,
40365                                       SelectionDAG &DAG,
40366                                       const X86Subtarget &Subtarget) {
40367   assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
40368   assert((Inputs.size() == 1 || Inputs.size() == 2) &&
40369          "Unexpected number of shuffle inputs!");
40370 
40371   SDLoc DL(Root);
40372   MVT RootVT = Root.getSimpleValueType();
40373   unsigned RootSizeInBits = RootVT.getSizeInBits();
40374   unsigned NumRootElts = RootVT.getVectorNumElements();
40375 
40376   // Canonicalize shuffle input op to the requested type.
40377   auto CanonicalizeShuffleInput = [&](MVT VT, SDValue Op) {
40378     if (VT.getSizeInBits() > Op.getValueSizeInBits())
40379       Op = widenSubVector(Op, false, Subtarget, DAG, DL, VT.getSizeInBits());
40380     else if (VT.getSizeInBits() < Op.getValueSizeInBits())
40381       Op = extractSubVector(Op, 0, DAG, DL, VT.getSizeInBits());
40382     return DAG.getBitcast(VT, Op);
40383   };
40384 
40385   // Find the inputs that enter the chain. Note that multiple uses are OK
40386   // here, we're not going to remove the operands we find.
40387   bool UnaryShuffle = (Inputs.size() == 1);
40388   SDValue V1 = peekThroughBitcasts(Inputs[0]);
40389   SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
40390                              : peekThroughBitcasts(Inputs[1]));
40391 
40392   MVT VT1 = V1.getSimpleValueType();
40393   MVT VT2 = V2.getSimpleValueType();
40394   assert((RootSizeInBits % VT1.getSizeInBits()) == 0 &&
40395          (RootSizeInBits % VT2.getSizeInBits()) == 0 && "Vector size mismatch");
40396 
40397   SDValue Res;
40398 
40399   unsigned NumBaseMaskElts = BaseMask.size();
40400   if (NumBaseMaskElts == 1) {
40401     assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
40402     return CanonicalizeShuffleInput(RootVT, V1);
40403   }
40404 
40405   bool OptForSize = DAG.shouldOptForSize();
40406   unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
40407   bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
40408                      (RootVT.isFloatingPoint() && Depth >= 1) ||
40409                      (RootVT.is256BitVector() && !Subtarget.hasAVX2());
40410 
40411   // Don't combine if we are a AVX512/EVEX target and the mask element size
40412   // is different from the root element size - this would prevent writemasks
40413   // from being reused.
40414   bool IsMaskedShuffle = false;
40415   if (RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128)) {
40416     if (Root.hasOneUse() && Root->use_begin()->getOpcode() == ISD::VSELECT &&
40417         Root->use_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
40418       IsMaskedShuffle = true;
40419     }
40420   }
40421 
40422   // If we are shuffling a splat (and not introducing zeros) then we can just
40423   // use it directly. This works for smaller elements as well as they already
40424   // repeat across each mask element.
40425   if (UnaryShuffle && !isAnyZero(BaseMask) &&
40426       V1.getValueSizeInBits() >= RootSizeInBits &&
40427       (BaseMaskEltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
40428       DAG.isSplatValue(V1, /*AllowUndefs*/ false)) {
40429     return CanonicalizeShuffleInput(RootVT, V1);
40430   }
40431 
40432   SmallVector<int, 64> Mask(BaseMask);
40433 
40434   // See if the shuffle is a hidden identity shuffle - repeated args in HOPs
40435   // etc. can be simplified.
40436   if (VT1 == VT2 && VT1.getSizeInBits() == RootSizeInBits && VT1.isVector()) {
40437     SmallVector<int> ScaledMask, IdentityMask;
40438     unsigned NumElts = VT1.getVectorNumElements();
40439     if (Mask.size() <= NumElts &&
40440         scaleShuffleElements(Mask, NumElts, ScaledMask)) {
40441       for (unsigned i = 0; i != NumElts; ++i)
40442         IdentityMask.push_back(i);
40443       if (isTargetShuffleEquivalent(RootVT, ScaledMask, IdentityMask, DAG, V1,
40444                                     V2))
40445         return CanonicalizeShuffleInput(RootVT, V1);
40446     }
40447   }
40448 
40449   // Handle 128/256-bit lane shuffles of 512-bit vectors.
40450   if (RootVT.is512BitVector() &&
40451       (NumBaseMaskElts == 2 || NumBaseMaskElts == 4)) {
40452     // If the upper subvectors are zeroable, then an extract+insert is more
40453     // optimal than using X86ISD::SHUF128. The insertion is free, even if it has
40454     // to zero the upper subvectors.
40455     if (isUndefOrZeroInRange(Mask, 1, NumBaseMaskElts - 1)) {
40456       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
40457         return SDValue(); // Nothing to do!
40458       assert(isInRange(Mask[0], 0, NumBaseMaskElts) &&
40459              "Unexpected lane shuffle");
40460       Res = CanonicalizeShuffleInput(RootVT, V1);
40461       unsigned SubIdx = Mask[0] * (NumRootElts / NumBaseMaskElts);
40462       bool UseZero = isAnyZero(Mask);
40463       Res = extractSubVector(Res, SubIdx, DAG, DL, BaseMaskEltSizeInBits);
40464       return widenSubVector(Res, UseZero, Subtarget, DAG, DL, RootSizeInBits);
40465     }
40466 
40467     // Narrow shuffle mask to v4x128.
40468     SmallVector<int, 4> ScaledMask;
40469     assert((BaseMaskEltSizeInBits % 128) == 0 && "Illegal mask size");
40470     narrowShuffleMaskElts(BaseMaskEltSizeInBits / 128, Mask, ScaledMask);
40471 
40472     // Try to lower to vshuf64x2/vshuf32x4.
40473     auto MatchSHUF128 = [&](MVT ShuffleVT, const SDLoc &DL,
40474                             ArrayRef<int> ScaledMask, SDValue V1, SDValue V2,
40475                             SelectionDAG &DAG) {
40476       unsigned PermMask = 0;
40477       // Insure elements came from the same Op.
40478       SDValue Ops[2] = {DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT)};
40479       for (int i = 0; i < 4; ++i) {
40480         assert(ScaledMask[i] >= -1 && "Illegal shuffle sentinel value");
40481         if (ScaledMask[i] < 0)
40482           continue;
40483 
40484         SDValue Op = ScaledMask[i] >= 4 ? V2 : V1;
40485         unsigned OpIndex = i / 2;
40486         if (Ops[OpIndex].isUndef())
40487           Ops[OpIndex] = Op;
40488         else if (Ops[OpIndex] != Op)
40489           return SDValue();
40490 
40491         // Convert the 128-bit shuffle mask selection values into 128-bit
40492         // selection bits defined by a vshuf64x2 instruction's immediate control
40493         // byte.
40494         PermMask |= (ScaledMask[i] % 4) << (i * 2);
40495       }
40496 
40497       return DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
40498                          CanonicalizeShuffleInput(ShuffleVT, Ops[0]),
40499                          CanonicalizeShuffleInput(ShuffleVT, Ops[1]),
40500                          DAG.getTargetConstant(PermMask, DL, MVT::i8));
40501     };
40502 
40503     // FIXME: Is there a better way to do this? is256BitLaneRepeatedShuffleMask
40504     // doesn't work because our mask is for 128 bits and we don't have an MVT
40505     // to match that.
40506     bool PreferPERMQ = UnaryShuffle && isUndefOrInRange(ScaledMask[0], 0, 2) &&
40507                        isUndefOrInRange(ScaledMask[1], 0, 2) &&
40508                        isUndefOrInRange(ScaledMask[2], 2, 4) &&
40509                        isUndefOrInRange(ScaledMask[3], 2, 4) &&
40510                        (ScaledMask[0] < 0 || ScaledMask[2] < 0 ||
40511                         ScaledMask[0] == (ScaledMask[2] % 2)) &&
40512                        (ScaledMask[1] < 0 || ScaledMask[3] < 0 ||
40513                         ScaledMask[1] == (ScaledMask[3] % 2));
40514 
40515     if (!isAnyZero(ScaledMask) && !PreferPERMQ) {
40516       if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
40517         return SDValue(); // Nothing to do!
40518       MVT ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
40519       if (SDValue V = MatchSHUF128(ShuffleVT, DL, ScaledMask, V1, V2, DAG))
40520         return DAG.getBitcast(RootVT, V);
40521     }
40522   }
40523 
40524   // Handle 128-bit lane shuffles of 256-bit vectors.
40525   if (RootVT.is256BitVector() && NumBaseMaskElts == 2) {
40526     // If the upper half is zeroable, then an extract+insert is more optimal
40527     // than using X86ISD::VPERM2X128. The insertion is free, even if it has to
40528     // zero the upper half.
40529     if (isUndefOrZero(Mask[1])) {
40530       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
40531         return SDValue(); // Nothing to do!
40532       assert(isInRange(Mask[0], 0, 2) && "Unexpected lane shuffle");
40533       Res = CanonicalizeShuffleInput(RootVT, V1);
40534       Res = extract128BitVector(Res, Mask[0] * (NumRootElts / 2), DAG, DL);
40535       return widenSubVector(Res, Mask[1] == SM_SentinelZero, Subtarget, DAG, DL,
40536                             256);
40537     }
40538 
40539     // If we're inserting the low subvector, an insert-subvector 'concat'
40540     // pattern is quicker than VPERM2X128.
40541     // TODO: Add AVX2 support instead of VPERMQ/VPERMPD.
40542     if (BaseMask[0] == 0 && (BaseMask[1] == 0 || BaseMask[1] == 2) &&
40543         !Subtarget.hasAVX2()) {
40544       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
40545         return SDValue(); // Nothing to do!
40546       SDValue Lo = CanonicalizeShuffleInput(RootVT, V1);
40547       SDValue Hi = CanonicalizeShuffleInput(RootVT, BaseMask[1] == 0 ? V1 : V2);
40548       Hi = extractSubVector(Hi, 0, DAG, DL, 128);
40549       return insertSubVector(Lo, Hi, NumRootElts / 2, DAG, DL, 128);
40550     }
40551 
40552     if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
40553       return SDValue(); // Nothing to do!
40554 
40555     // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
40556     // we need to use the zeroing feature.
40557     // Prefer blends for sequential shuffles unless we are optimizing for size.
40558     if (UnaryShuffle &&
40559         !(Subtarget.hasAVX2() && isUndefOrInRange(Mask, 0, 2)) &&
40560         (OptForSize || !isSequentialOrUndefOrZeroInRange(Mask, 0, 2, 0))) {
40561       unsigned PermMask = 0;
40562       PermMask |= ((Mask[0] < 0 ? 0x8 : (Mask[0] & 1)) << 0);
40563       PermMask |= ((Mask[1] < 0 ? 0x8 : (Mask[1] & 1)) << 4);
40564       return DAG.getNode(
40565           X86ISD::VPERM2X128, DL, RootVT, CanonicalizeShuffleInput(RootVT, V1),
40566           DAG.getUNDEF(RootVT), DAG.getTargetConstant(PermMask, DL, MVT::i8));
40567     }
40568 
40569     if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
40570       return SDValue(); // Nothing to do!
40571 
40572     // TODO - handle AVX512VL cases with X86ISD::SHUF128.
40573     if (!UnaryShuffle && !IsMaskedShuffle) {
40574       assert(llvm::all_of(Mask, [](int M) { return 0 <= M && M < 4; }) &&
40575              "Unexpected shuffle sentinel value");
40576       // Prefer blends to X86ISD::VPERM2X128.
40577       if (!((Mask[0] == 0 && Mask[1] == 3) || (Mask[0] == 2 && Mask[1] == 1))) {
40578         unsigned PermMask = 0;
40579         PermMask |= ((Mask[0] & 3) << 0);
40580         PermMask |= ((Mask[1] & 3) << 4);
40581         SDValue LHS = isInRange(Mask[0], 0, 2) ? V1 : V2;
40582         SDValue RHS = isInRange(Mask[1], 0, 2) ? V1 : V2;
40583         return DAG.getNode(X86ISD::VPERM2X128, DL, RootVT,
40584                           CanonicalizeShuffleInput(RootVT, LHS),
40585                           CanonicalizeShuffleInput(RootVT, RHS),
40586                           DAG.getTargetConstant(PermMask, DL, MVT::i8));
40587       }
40588     }
40589   }
40590 
40591   // For masks that have been widened to 128-bit elements or more,
40592   // narrow back down to 64-bit elements.
40593   if (BaseMaskEltSizeInBits > 64) {
40594     assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
40595     int MaskScale = BaseMaskEltSizeInBits / 64;
40596     SmallVector<int, 64> ScaledMask;
40597     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
40598     Mask = std::move(ScaledMask);
40599   }
40600 
40601   // For masked shuffles, we're trying to match the root width for better
40602   // writemask folding, attempt to scale the mask.
40603   // TODO - variable shuffles might need this to be widened again.
40604   if (IsMaskedShuffle && NumRootElts > Mask.size()) {
40605     assert((NumRootElts % Mask.size()) == 0 && "Illegal mask size");
40606     int MaskScale = NumRootElts / Mask.size();
40607     SmallVector<int, 64> ScaledMask;
40608     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
40609     Mask = std::move(ScaledMask);
40610   }
40611 
40612   unsigned NumMaskElts = Mask.size();
40613   unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
40614 
40615   // Determine the effective mask value type.
40616   FloatDomain &= (32 <= MaskEltSizeInBits);
40617   MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
40618                            : MVT::getIntegerVT(MaskEltSizeInBits);
40619   MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
40620 
40621   // Only allow legal mask types.
40622   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
40623     return SDValue();
40624 
40625   // Attempt to match the mask against known shuffle patterns.
40626   MVT ShuffleSrcVT, ShuffleVT;
40627   unsigned Shuffle, PermuteImm;
40628 
40629   // Which shuffle domains are permitted?
40630   // Permit domain crossing at higher combine depths.
40631   // TODO: Should we indicate which domain is preferred if both are allowed?
40632   bool AllowFloatDomain = FloatDomain || (Depth >= 3);
40633   bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
40634                         (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
40635 
40636   // Determine zeroable mask elements.
40637   APInt KnownUndef, KnownZero;
40638   resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
40639   APInt Zeroable = KnownUndef | KnownZero;
40640 
40641   if (UnaryShuffle) {
40642     // Attempt to match against broadcast-from-vector.
40643     // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
40644     if ((Subtarget.hasAVX2() ||
40645          (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits)) &&
40646         (!IsMaskedShuffle || NumRootElts == NumMaskElts)) {
40647       if (isUndefOrEqual(Mask, 0)) {
40648         if (V1.getValueType() == MaskVT &&
40649             V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
40650             X86::mayFoldLoad(V1.getOperand(0), Subtarget)) {
40651           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
40652             return SDValue(); // Nothing to do!
40653           Res = V1.getOperand(0);
40654           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
40655           return DAG.getBitcast(RootVT, Res);
40656         }
40657         if (Subtarget.hasAVX2()) {
40658           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
40659             return SDValue(); // Nothing to do!
40660           Res = CanonicalizeShuffleInput(MaskVT, V1);
40661           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
40662           return DAG.getBitcast(RootVT, Res);
40663         }
40664       }
40665     }
40666 
40667     if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, V1,
40668                           DAG, Subtarget, Shuffle, ShuffleSrcVT, ShuffleVT) &&
40669         (!IsMaskedShuffle ||
40670          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
40671       if (Depth == 0 && Root.getOpcode() == Shuffle)
40672         return SDValue(); // Nothing to do!
40673       Res = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
40674       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
40675       return DAG.getBitcast(RootVT, Res);
40676     }
40677 
40678     if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
40679                                  AllowIntDomain, DAG, Subtarget, Shuffle, ShuffleVT,
40680                                  PermuteImm) &&
40681         (!IsMaskedShuffle ||
40682          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
40683       if (Depth == 0 && Root.getOpcode() == Shuffle)
40684         return SDValue(); // Nothing to do!
40685       Res = CanonicalizeShuffleInput(ShuffleVT, V1);
40686       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
40687                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
40688       return DAG.getBitcast(RootVT, Res);
40689     }
40690   }
40691 
40692   // Attempt to combine to INSERTPS, but only if the inserted element has come
40693   // from a scalar.
40694   // TODO: Handle other insertions here as well?
40695   if (!UnaryShuffle && AllowFloatDomain && RootSizeInBits == 128 &&
40696       Subtarget.hasSSE41() &&
40697       !isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}, DAG)) {
40698     if (MaskEltSizeInBits == 32) {
40699       SDValue SrcV1 = V1, SrcV2 = V2;
40700       if (matchShuffleAsInsertPS(SrcV1, SrcV2, PermuteImm, Zeroable, Mask,
40701                                  DAG) &&
40702           SrcV2.getOpcode() == ISD::SCALAR_TO_VECTOR) {
40703         if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
40704           return SDValue(); // Nothing to do!
40705         Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
40706                           CanonicalizeShuffleInput(MVT::v4f32, SrcV1),
40707                           CanonicalizeShuffleInput(MVT::v4f32, SrcV2),
40708                           DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
40709         return DAG.getBitcast(RootVT, Res);
40710       }
40711     }
40712     if (MaskEltSizeInBits == 64 &&
40713         isTargetShuffleEquivalent(MaskVT, Mask, {0, 2}, DAG) &&
40714         V2.getOpcode() == ISD::SCALAR_TO_VECTOR &&
40715         V2.getScalarValueSizeInBits() <= 32) {
40716       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
40717         return SDValue(); // Nothing to do!
40718       PermuteImm = (/*DstIdx*/ 2 << 4) | (/*SrcIdx*/ 0 << 0);
40719       Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
40720                         CanonicalizeShuffleInput(MVT::v4f32, V1),
40721                         CanonicalizeShuffleInput(MVT::v4f32, V2),
40722                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
40723       return DAG.getBitcast(RootVT, Res);
40724     }
40725   }
40726 
40727   SDValue NewV1 = V1; // Save operands in case early exit happens.
40728   SDValue NewV2 = V2;
40729   if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
40730                          NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
40731                          ShuffleVT, UnaryShuffle) &&
40732       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
40733     if (Depth == 0 && Root.getOpcode() == Shuffle)
40734       return SDValue(); // Nothing to do!
40735     NewV1 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
40736     NewV2 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV2);
40737     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
40738     return DAG.getBitcast(RootVT, Res);
40739   }
40740 
40741   NewV1 = V1; // Save operands in case early exit happens.
40742   NewV2 = V2;
40743   if (matchBinaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
40744                                 AllowIntDomain, NewV1, NewV2, DL, DAG,
40745                                 Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
40746       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
40747     if (Depth == 0 && Root.getOpcode() == Shuffle)
40748       return SDValue(); // Nothing to do!
40749     NewV1 = CanonicalizeShuffleInput(ShuffleVT, NewV1);
40750     NewV2 = CanonicalizeShuffleInput(ShuffleVT, NewV2);
40751     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
40752                       DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
40753     return DAG.getBitcast(RootVT, Res);
40754   }
40755 
40756   // Typically from here on, we need an integer version of MaskVT.
40757   MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
40758   IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
40759 
40760   // Annoyingly, SSE4A instructions don't map into the above match helpers.
40761   if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
40762     uint64_t BitLen, BitIdx;
40763     if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
40764                             Zeroable)) {
40765       if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
40766         return SDValue(); // Nothing to do!
40767       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
40768       Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
40769                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
40770                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
40771       return DAG.getBitcast(RootVT, Res);
40772     }
40773 
40774     if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
40775       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
40776         return SDValue(); // Nothing to do!
40777       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
40778       V2 = CanonicalizeShuffleInput(IntMaskVT, V2);
40779       Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
40780                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
40781                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
40782       return DAG.getBitcast(RootVT, Res);
40783     }
40784   }
40785 
40786   // Match shuffle against TRUNCATE patterns.
40787   if (AllowIntDomain && MaskEltSizeInBits < 64 && Subtarget.hasAVX512()) {
40788     // Match against a VTRUNC instruction, accounting for src/dst sizes.
40789     if (matchShuffleAsVTRUNC(ShuffleSrcVT, ShuffleVT, IntMaskVT, Mask, Zeroable,
40790                              Subtarget)) {
40791       bool IsTRUNCATE = ShuffleVT.getVectorNumElements() ==
40792                         ShuffleSrcVT.getVectorNumElements();
40793       unsigned Opc =
40794           IsTRUNCATE ? (unsigned)ISD::TRUNCATE : (unsigned)X86ISD::VTRUNC;
40795       if (Depth == 0 && Root.getOpcode() == Opc)
40796         return SDValue(); // Nothing to do!
40797       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
40798       Res = DAG.getNode(Opc, DL, ShuffleVT, V1);
40799       if (ShuffleVT.getSizeInBits() < RootSizeInBits)
40800         Res = widenSubVector(Res, true, Subtarget, DAG, DL, RootSizeInBits);
40801       return DAG.getBitcast(RootVT, Res);
40802     }
40803 
40804     // Do we need a more general binary truncation pattern?
40805     if (RootSizeInBits < 512 &&
40806         ((RootVT.is256BitVector() && Subtarget.useAVX512Regs()) ||
40807          (RootVT.is128BitVector() && Subtarget.hasVLX())) &&
40808         (MaskEltSizeInBits > 8 || Subtarget.hasBWI()) &&
40809         isSequentialOrUndefInRange(Mask, 0, NumMaskElts, 0, 2)) {
40810       // Bail if this was already a truncation or PACK node.
40811       // We sometimes fail to match PACK if we demand known undef elements.
40812       if (Depth == 0 && (Root.getOpcode() == ISD::TRUNCATE ||
40813                          Root.getOpcode() == X86ISD::PACKSS ||
40814                          Root.getOpcode() == X86ISD::PACKUS))
40815         return SDValue(); // Nothing to do!
40816       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
40817       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts / 2);
40818       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
40819       V2 = CanonicalizeShuffleInput(ShuffleSrcVT, V2);
40820       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
40821       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts);
40822       Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShuffleSrcVT, V1, V2);
40823       Res = DAG.getNode(ISD::TRUNCATE, DL, IntMaskVT, Res);
40824       return DAG.getBitcast(RootVT, Res);
40825     }
40826   }
40827 
40828   // Don't try to re-form single instruction chains under any circumstances now
40829   // that we've done encoding canonicalization for them.
40830   if (Depth < 1)
40831     return SDValue();
40832 
40833   // Depth threshold above which we can efficiently use variable mask shuffles.
40834   int VariableCrossLaneShuffleDepth =
40835       Subtarget.hasFastVariableCrossLaneShuffle() ? 1 : 2;
40836   int VariablePerLaneShuffleDepth =
40837       Subtarget.hasFastVariablePerLaneShuffle() ? 1 : 2;
40838   AllowVariableCrossLaneMask &=
40839       (Depth >= VariableCrossLaneShuffleDepth) || HasVariableMask;
40840   AllowVariablePerLaneMask &=
40841       (Depth >= VariablePerLaneShuffleDepth) || HasVariableMask;
40842   // VPERMI2W/VPERMI2B are 3 uops on Skylake and Icelake so we require a
40843   // higher depth before combining them.
40844   bool AllowBWIVPERMV3 =
40845       (Depth >= (VariableCrossLaneShuffleDepth + 2) || HasVariableMask);
40846 
40847   bool MaskContainsZeros = isAnyZero(Mask);
40848 
40849   if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
40850     // If we have a single input lane-crossing shuffle then lower to VPERMV.
40851     if (UnaryShuffle && AllowVariableCrossLaneMask && !MaskContainsZeros) {
40852       if (Subtarget.hasAVX2() &&
40853           (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) {
40854         SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
40855         Res = CanonicalizeShuffleInput(MaskVT, V1);
40856         Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
40857         return DAG.getBitcast(RootVT, Res);
40858       }
40859       // AVX512 variants (non-VLX will pad to 512-bit shuffles).
40860       if ((Subtarget.hasAVX512() &&
40861            (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
40862             MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
40863           (Subtarget.hasBWI() &&
40864            (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
40865           (Subtarget.hasVBMI() &&
40866            (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8))) {
40867         V1 = CanonicalizeShuffleInput(MaskVT, V1);
40868         V2 = DAG.getUNDEF(MaskVT);
40869         Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
40870         return DAG.getBitcast(RootVT, Res);
40871       }
40872     }
40873 
40874     // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
40875     // vector as the second source (non-VLX will pad to 512-bit shuffles).
40876     if (UnaryShuffle && AllowVariableCrossLaneMask &&
40877         ((Subtarget.hasAVX512() &&
40878           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
40879            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
40880            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32 ||
40881            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
40882          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
40883           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
40884          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
40885           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
40886       // Adjust shuffle mask - replace SM_SentinelZero with second source index.
40887       for (unsigned i = 0; i != NumMaskElts; ++i)
40888         if (Mask[i] == SM_SentinelZero)
40889           Mask[i] = NumMaskElts + i;
40890       V1 = CanonicalizeShuffleInput(MaskVT, V1);
40891       V2 = getZeroVector(MaskVT, Subtarget, DAG, DL);
40892       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
40893       return DAG.getBitcast(RootVT, Res);
40894     }
40895 
40896     // If that failed and either input is extracted then try to combine as a
40897     // shuffle with the larger type.
40898     if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
40899             Inputs, Root, BaseMask, Depth, HasVariableMask,
40900             AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG,
40901             Subtarget))
40902       return WideShuffle;
40903 
40904     // If we have a dual input lane-crossing shuffle then lower to VPERMV3,
40905     // (non-VLX will pad to 512-bit shuffles).
40906     if (AllowVariableCrossLaneMask && !MaskContainsZeros &&
40907         ((Subtarget.hasAVX512() &&
40908           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
40909            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
40910            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32 ||
40911            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
40912          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
40913           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
40914          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
40915           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
40916       V1 = CanonicalizeShuffleInput(MaskVT, V1);
40917       V2 = CanonicalizeShuffleInput(MaskVT, V2);
40918       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
40919       return DAG.getBitcast(RootVT, Res);
40920     }
40921     return SDValue();
40922   }
40923 
40924   // See if we can combine a single input shuffle with zeros to a bit-mask,
40925   // which is much simpler than any shuffle.
40926   if (UnaryShuffle && MaskContainsZeros && AllowVariablePerLaneMask &&
40927       isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
40928       DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
40929     APInt Zero = APInt::getZero(MaskEltSizeInBits);
40930     APInt AllOnes = APInt::getAllOnes(MaskEltSizeInBits);
40931     APInt UndefElts(NumMaskElts, 0);
40932     SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
40933     for (unsigned i = 0; i != NumMaskElts; ++i) {
40934       int M = Mask[i];
40935       if (M == SM_SentinelUndef) {
40936         UndefElts.setBit(i);
40937         continue;
40938       }
40939       if (M == SM_SentinelZero)
40940         continue;
40941       EltBits[i] = AllOnes;
40942     }
40943     SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
40944     Res = CanonicalizeShuffleInput(MaskVT, V1);
40945     unsigned AndOpcode =
40946         MaskVT.isFloatingPoint() ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
40947     Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
40948     return DAG.getBitcast(RootVT, Res);
40949   }
40950 
40951   // If we have a single input shuffle with different shuffle patterns in the
40952   // the 128-bit lanes use the variable mask to VPERMILPS.
40953   // TODO Combine other mask types at higher depths.
40954   if (UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
40955       ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
40956        (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
40957     SmallVector<SDValue, 16> VPermIdx;
40958     for (int M : Mask) {
40959       SDValue Idx =
40960           M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
40961       VPermIdx.push_back(Idx);
40962     }
40963     SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
40964     Res = CanonicalizeShuffleInput(MaskVT, V1);
40965     Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
40966     return DAG.getBitcast(RootVT, Res);
40967   }
40968 
40969   // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
40970   // to VPERMIL2PD/VPERMIL2PS.
40971   if (AllowVariablePerLaneMask && Subtarget.hasXOP() &&
40972       (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
40973        MaskVT == MVT::v8f32)) {
40974     // VPERMIL2 Operation.
40975     // Bits[3] - Match Bit.
40976     // Bits[2:1] - (Per Lane) PD Shuffle Mask.
40977     // Bits[2:0] - (Per Lane) PS Shuffle Mask.
40978     unsigned NumLanes = MaskVT.getSizeInBits() / 128;
40979     unsigned NumEltsPerLane = NumMaskElts / NumLanes;
40980     SmallVector<int, 8> VPerm2Idx;
40981     unsigned M2ZImm = 0;
40982     for (int M : Mask) {
40983       if (M == SM_SentinelUndef) {
40984         VPerm2Idx.push_back(-1);
40985         continue;
40986       }
40987       if (M == SM_SentinelZero) {
40988         M2ZImm = 2;
40989         VPerm2Idx.push_back(8);
40990         continue;
40991       }
40992       int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
40993       Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
40994       VPerm2Idx.push_back(Index);
40995     }
40996     V1 = CanonicalizeShuffleInput(MaskVT, V1);
40997     V2 = CanonicalizeShuffleInput(MaskVT, V2);
40998     SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
40999     Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
41000                       DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
41001     return DAG.getBitcast(RootVT, Res);
41002   }
41003 
41004   // If we have 3 or more shuffle instructions or a chain involving a variable
41005   // mask, we can replace them with a single PSHUFB instruction profitably.
41006   // Intel's manuals suggest only using PSHUFB if doing so replacing 5
41007   // instructions, but in practice PSHUFB tends to be *very* fast so we're
41008   // more aggressive.
41009   if (UnaryShuffle && AllowVariablePerLaneMask &&
41010       ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
41011        (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
41012        (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
41013     SmallVector<SDValue, 16> PSHUFBMask;
41014     int NumBytes = RootVT.getSizeInBits() / 8;
41015     int Ratio = NumBytes / NumMaskElts;
41016     for (int i = 0; i < NumBytes; ++i) {
41017       int M = Mask[i / Ratio];
41018       if (M == SM_SentinelUndef) {
41019         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
41020         continue;
41021       }
41022       if (M == SM_SentinelZero) {
41023         PSHUFBMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
41024         continue;
41025       }
41026       M = Ratio * M + i % Ratio;
41027       assert((M / 16) == (i / 16) && "Lane crossing detected");
41028       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
41029     }
41030     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
41031     Res = CanonicalizeShuffleInput(ByteVT, V1);
41032     SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
41033     Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
41034     return DAG.getBitcast(RootVT, Res);
41035   }
41036 
41037   // With XOP, if we have a 128-bit binary input shuffle we can always combine
41038   // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
41039   // slower than PSHUFB on targets that support both.
41040   if (AllowVariablePerLaneMask && RootVT.is128BitVector() &&
41041       Subtarget.hasXOP()) {
41042     // VPPERM Mask Operation
41043     // Bits[4:0] - Byte Index (0 - 31)
41044     // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
41045     SmallVector<SDValue, 16> VPPERMMask;
41046     int NumBytes = 16;
41047     int Ratio = NumBytes / NumMaskElts;
41048     for (int i = 0; i < NumBytes; ++i) {
41049       int M = Mask[i / Ratio];
41050       if (M == SM_SentinelUndef) {
41051         VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
41052         continue;
41053       }
41054       if (M == SM_SentinelZero) {
41055         VPPERMMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
41056         continue;
41057       }
41058       M = Ratio * M + i % Ratio;
41059       VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
41060     }
41061     MVT ByteVT = MVT::v16i8;
41062     V1 = CanonicalizeShuffleInput(ByteVT, V1);
41063     V2 = CanonicalizeShuffleInput(ByteVT, V2);
41064     SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
41065     Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
41066     return DAG.getBitcast(RootVT, Res);
41067   }
41068 
41069   // If that failed and either input is extracted then try to combine as a
41070   // shuffle with the larger type.
41071   if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
41072           Inputs, Root, BaseMask, Depth, HasVariableMask,
41073           AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG, Subtarget))
41074     return WideShuffle;
41075 
41076   // If we have a dual input shuffle then lower to VPERMV3,
41077   // (non-VLX will pad to 512-bit shuffles)
41078   if (!UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
41079       ((Subtarget.hasAVX512() &&
41080         (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v8f64 ||
41081          MaskVT == MVT::v2i64 || MaskVT == MVT::v4i64 || MaskVT == MVT::v8i64 ||
41082          MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 || MaskVT == MVT::v8f32 ||
41083          MaskVT == MVT::v8i32 || MaskVT == MVT::v16f32 ||
41084          MaskVT == MVT::v16i32)) ||
41085        (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
41086         (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16 ||
41087          MaskVT == MVT::v32i16)) ||
41088        (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
41089         (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8 ||
41090          MaskVT == MVT::v64i8)))) {
41091     V1 = CanonicalizeShuffleInput(MaskVT, V1);
41092     V2 = CanonicalizeShuffleInput(MaskVT, V2);
41093     Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
41094     return DAG.getBitcast(RootVT, Res);
41095   }
41096 
41097   // Failed to find any combines.
41098   return SDValue();
41099 }
41100 
41101 // Combine an arbitrary chain of shuffles + extract_subvectors into a single
41102 // instruction if possible.
41103 //
41104 // Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
41105 // type size to attempt to combine:
41106 // shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
41107 // -->
41108 // extract_subvector(shuffle(x,y,m2),0)
41109 static SDValue combineX86ShuffleChainWithExtract(
41110     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
41111     bool HasVariableMask, bool AllowVariableCrossLaneMask,
41112     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
41113     const X86Subtarget &Subtarget) {
41114   unsigned NumMaskElts = BaseMask.size();
41115   unsigned NumInputs = Inputs.size();
41116   if (NumInputs == 0)
41117     return SDValue();
41118 
41119   EVT RootVT = Root.getValueType();
41120   unsigned RootSizeInBits = RootVT.getSizeInBits();
41121   unsigned RootEltSizeInBits = RootSizeInBits / NumMaskElts;
41122   assert((RootSizeInBits % NumMaskElts) == 0 && "Unexpected root shuffle mask");
41123 
41124   // Peek through extract_subvector to find widest legal vector.
41125   // TODO: Handle ISD::TRUNCATE
41126   unsigned WideSizeInBits = RootSizeInBits;
41127   for (unsigned I = 0; I != NumInputs; ++I) {
41128     SDValue Input = peekThroughBitcasts(Inputs[I]);
41129     while (Input.getOpcode() == ISD::EXTRACT_SUBVECTOR)
41130       Input = peekThroughBitcasts(Input.getOperand(0));
41131     if (DAG.getTargetLoweringInfo().isTypeLegal(Input.getValueType()) &&
41132         WideSizeInBits < Input.getValueSizeInBits())
41133       WideSizeInBits = Input.getValueSizeInBits();
41134   }
41135 
41136   // Bail if we fail to find a source larger than the existing root.
41137   unsigned Scale = WideSizeInBits / RootSizeInBits;
41138   if (WideSizeInBits <= RootSizeInBits ||
41139       (WideSizeInBits % RootSizeInBits) != 0)
41140     return SDValue();
41141 
41142   // Create new mask for larger type.
41143   SmallVector<int, 64> WideMask(BaseMask);
41144   for (int &M : WideMask) {
41145     if (M < 0)
41146       continue;
41147     M = (M % NumMaskElts) + ((M / NumMaskElts) * Scale * NumMaskElts);
41148   }
41149   WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
41150 
41151   // Attempt to peek through inputs and adjust mask when we extract from an
41152   // upper subvector.
41153   int AdjustedMasks = 0;
41154   SmallVector<SDValue, 4> WideInputs(Inputs.begin(), Inputs.end());
41155   for (unsigned I = 0; I != NumInputs; ++I) {
41156     SDValue &Input = WideInputs[I];
41157     Input = peekThroughBitcasts(Input);
41158     while (Input.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41159            Input.getOperand(0).getValueSizeInBits() <= WideSizeInBits) {
41160       uint64_t Idx = Input.getConstantOperandVal(1);
41161       if (Idx != 0) {
41162         ++AdjustedMasks;
41163         unsigned InputEltSizeInBits = Input.getScalarValueSizeInBits();
41164         Idx = (Idx * InputEltSizeInBits) / RootEltSizeInBits;
41165 
41166         int lo = I * WideMask.size();
41167         int hi = (I + 1) * WideMask.size();
41168         for (int &M : WideMask)
41169           if (lo <= M && M < hi)
41170             M += Idx;
41171       }
41172       Input = peekThroughBitcasts(Input.getOperand(0));
41173     }
41174   }
41175 
41176   // Remove unused/repeated shuffle source ops.
41177   resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
41178   assert(!WideInputs.empty() && "Shuffle with no inputs detected");
41179 
41180   // Bail if we're always extracting from the lowest subvectors,
41181   // combineX86ShuffleChain should match this for the current width, or the
41182   // shuffle still references too many inputs.
41183   if (AdjustedMasks == 0 || WideInputs.size() > 2)
41184     return SDValue();
41185 
41186   // Minor canonicalization of the accumulated shuffle mask to make it easier
41187   // to match below. All this does is detect masks with sequential pairs of
41188   // elements, and shrink them to the half-width mask. It does this in a loop
41189   // so it will reduce the size of the mask to the minimal width mask which
41190   // performs an equivalent shuffle.
41191   while (WideMask.size() > 1) {
41192     SmallVector<int, 64> WidenedMask;
41193     if (!canWidenShuffleElements(WideMask, WidenedMask))
41194       break;
41195     WideMask = std::move(WidenedMask);
41196   }
41197 
41198   // Canonicalization of binary shuffle masks to improve pattern matching by
41199   // commuting the inputs.
41200   if (WideInputs.size() == 2 && canonicalizeShuffleMaskWithCommute(WideMask)) {
41201     ShuffleVectorSDNode::commuteMask(WideMask);
41202     std::swap(WideInputs[0], WideInputs[1]);
41203   }
41204 
41205   // Increase depth for every upper subvector we've peeked through.
41206   Depth += AdjustedMasks;
41207 
41208   // Attempt to combine wider chain.
41209   // TODO: Can we use a better Root?
41210   SDValue WideRoot = WideInputs.front().getValueSizeInBits() >
41211                              WideInputs.back().getValueSizeInBits()
41212                          ? WideInputs.front()
41213                          : WideInputs.back();
41214   assert(WideRoot.getValueSizeInBits() == WideSizeInBits &&
41215          "WideRootSize mismatch");
41216 
41217   if (SDValue WideShuffle =
41218           combineX86ShuffleChain(WideInputs, WideRoot, WideMask, Depth,
41219                                  HasVariableMask, AllowVariableCrossLaneMask,
41220                                  AllowVariablePerLaneMask, DAG, Subtarget)) {
41221     WideShuffle =
41222         extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
41223     return DAG.getBitcast(RootVT, WideShuffle);
41224   }
41225 
41226   return SDValue();
41227 }
41228 
41229 // Canonicalize the combined shuffle mask chain with horizontal ops.
41230 // NOTE: This may update the Ops and Mask.
41231 static SDValue canonicalizeShuffleMaskWithHorizOp(
41232     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
41233     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
41234     const X86Subtarget &Subtarget) {
41235   if (Mask.empty() || Ops.empty())
41236     return SDValue();
41237 
41238   SmallVector<SDValue> BC;
41239   for (SDValue Op : Ops)
41240     BC.push_back(peekThroughBitcasts(Op));
41241 
41242   // All ops must be the same horizop + type.
41243   SDValue BC0 = BC[0];
41244   EVT VT0 = BC0.getValueType();
41245   unsigned Opcode0 = BC0.getOpcode();
41246   if (VT0.getSizeInBits() != RootSizeInBits || llvm::any_of(BC, [&](SDValue V) {
41247         return V.getOpcode() != Opcode0 || V.getValueType() != VT0;
41248       }))
41249     return SDValue();
41250 
41251   bool isHoriz = (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
41252                   Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB);
41253   bool isPack = (Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS);
41254   if (!isHoriz && !isPack)
41255     return SDValue();
41256 
41257   // Do all ops have a single use?
41258   bool OneUseOps = llvm::all_of(Ops, [](SDValue Op) {
41259     return Op.hasOneUse() &&
41260            peekThroughBitcasts(Op) == peekThroughOneUseBitcasts(Op);
41261   });
41262 
41263   int NumElts = VT0.getVectorNumElements();
41264   int NumLanes = VT0.getSizeInBits() / 128;
41265   int NumEltsPerLane = NumElts / NumLanes;
41266   int NumHalfEltsPerLane = NumEltsPerLane / 2;
41267   MVT SrcVT = BC0.getOperand(0).getSimpleValueType();
41268   unsigned EltSizeInBits = RootSizeInBits / Mask.size();
41269 
41270   if (NumEltsPerLane >= 4 &&
41271       (isPack || shouldUseHorizontalOp(Ops.size() == 1, DAG, Subtarget))) {
41272     SmallVector<int> LaneMask, ScaledMask;
41273     if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, LaneMask) &&
41274         scaleShuffleElements(LaneMask, 4, ScaledMask)) {
41275       // See if we can remove the shuffle by resorting the HOP chain so that
41276       // the HOP args are pre-shuffled.
41277       // TODO: Generalize to any sized/depth chain.
41278       // TODO: Add support for PACKSS/PACKUS.
41279       if (isHoriz) {
41280         // Attempt to find a HOP(HOP(X,Y),HOP(Z,W)) source operand.
41281         auto GetHOpSrc = [&](int M) {
41282           if (M == SM_SentinelUndef)
41283             return DAG.getUNDEF(VT0);
41284           if (M == SM_SentinelZero)
41285             return getZeroVector(VT0.getSimpleVT(), Subtarget, DAG, DL);
41286           SDValue Src0 = BC[M / 4];
41287           SDValue Src1 = Src0.getOperand((M % 4) >= 2);
41288           if (Src1.getOpcode() == Opcode0 && Src0->isOnlyUserOf(Src1.getNode()))
41289             return Src1.getOperand(M % 2);
41290           return SDValue();
41291         };
41292         SDValue M0 = GetHOpSrc(ScaledMask[0]);
41293         SDValue M1 = GetHOpSrc(ScaledMask[1]);
41294         SDValue M2 = GetHOpSrc(ScaledMask[2]);
41295         SDValue M3 = GetHOpSrc(ScaledMask[3]);
41296         if (M0 && M1 && M2 && M3) {
41297           SDValue LHS = DAG.getNode(Opcode0, DL, SrcVT, M0, M1);
41298           SDValue RHS = DAG.getNode(Opcode0, DL, SrcVT, M2, M3);
41299           return DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
41300         }
41301       }
41302       // shuffle(hop(x,y),hop(z,w)) -> permute(hop(x,z)) etc.
41303       if (Ops.size() >= 2) {
41304         SDValue LHS, RHS;
41305         auto GetHOpSrc = [&](int M, int &OutM) {
41306           // TODO: Support SM_SentinelZero
41307           if (M < 0)
41308             return M == SM_SentinelUndef;
41309           SDValue Src = BC[M / 4].getOperand((M % 4) >= 2);
41310           if (!LHS || LHS == Src) {
41311             LHS = Src;
41312             OutM = (M % 2);
41313             return true;
41314           }
41315           if (!RHS || RHS == Src) {
41316             RHS = Src;
41317             OutM = (M % 2) + 2;
41318             return true;
41319           }
41320           return false;
41321         };
41322         int PostMask[4] = {-1, -1, -1, -1};
41323         if (GetHOpSrc(ScaledMask[0], PostMask[0]) &&
41324             GetHOpSrc(ScaledMask[1], PostMask[1]) &&
41325             GetHOpSrc(ScaledMask[2], PostMask[2]) &&
41326             GetHOpSrc(ScaledMask[3], PostMask[3])) {
41327           LHS = DAG.getBitcast(SrcVT, LHS);
41328           RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
41329           SDValue Res = DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
41330           // Use SHUFPS for the permute so this will work on SSE2 targets,
41331           // shuffle combining and domain handling will simplify this later on.
41332           MVT ShuffleVT = MVT::getVectorVT(MVT::f32, RootSizeInBits / 32);
41333           Res = DAG.getBitcast(ShuffleVT, Res);
41334           return DAG.getNode(X86ISD::SHUFP, DL, ShuffleVT, Res, Res,
41335                              getV4X86ShuffleImm8ForMask(PostMask, DL, DAG));
41336         }
41337       }
41338     }
41339   }
41340 
41341   if (2 < Ops.size())
41342     return SDValue();
41343 
41344   SDValue BC1 = BC[BC.size() - 1];
41345   if (Mask.size() == VT0.getVectorNumElements()) {
41346     // Canonicalize binary shuffles of horizontal ops that use the
41347     // same sources to an unary shuffle.
41348     // TODO: Try to perform this fold even if the shuffle remains.
41349     if (Ops.size() == 2) {
41350       auto ContainsOps = [](SDValue HOp, SDValue Op) {
41351         return Op == HOp.getOperand(0) || Op == HOp.getOperand(1);
41352       };
41353       // Commute if all BC0's ops are contained in BC1.
41354       if (ContainsOps(BC1, BC0.getOperand(0)) &&
41355           ContainsOps(BC1, BC0.getOperand(1))) {
41356         ShuffleVectorSDNode::commuteMask(Mask);
41357         std::swap(Ops[0], Ops[1]);
41358         std::swap(BC0, BC1);
41359       }
41360 
41361       // If BC1 can be represented by BC0, then convert to unary shuffle.
41362       if (ContainsOps(BC0, BC1.getOperand(0)) &&
41363           ContainsOps(BC0, BC1.getOperand(1))) {
41364         for (int &M : Mask) {
41365           if (M < NumElts) // BC0 element or UNDEF/Zero sentinel.
41366             continue;
41367           int SubLane = ((M % NumEltsPerLane) >= NumHalfEltsPerLane) ? 1 : 0;
41368           M -= NumElts + (SubLane * NumHalfEltsPerLane);
41369           if (BC1.getOperand(SubLane) != BC0.getOperand(0))
41370             M += NumHalfEltsPerLane;
41371         }
41372       }
41373     }
41374 
41375     // Canonicalize unary horizontal ops to only refer to lower halves.
41376     for (int i = 0; i != NumElts; ++i) {
41377       int &M = Mask[i];
41378       if (isUndefOrZero(M))
41379         continue;
41380       if (M < NumElts && BC0.getOperand(0) == BC0.getOperand(1) &&
41381           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
41382         M -= NumHalfEltsPerLane;
41383       if (NumElts <= M && BC1.getOperand(0) == BC1.getOperand(1) &&
41384           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
41385         M -= NumHalfEltsPerLane;
41386     }
41387   }
41388 
41389   // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
41390   // single instruction. Attempt to match a v2X64 repeating shuffle pattern that
41391   // represents the LHS/RHS inputs for the lower/upper halves.
41392   SmallVector<int, 16> TargetMask128, WideMask128;
41393   if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, TargetMask128) &&
41394       scaleShuffleElements(TargetMask128, 2, WideMask128)) {
41395     assert(isUndefOrZeroOrInRange(WideMask128, 0, 4) && "Illegal shuffle");
41396     bool SingleOp = (Ops.size() == 1);
41397     if (isPack || OneUseOps ||
41398         shouldUseHorizontalOp(SingleOp, DAG, Subtarget)) {
41399       SDValue Lo = isInRange(WideMask128[0], 0, 2) ? BC0 : BC1;
41400       SDValue Hi = isInRange(WideMask128[1], 0, 2) ? BC0 : BC1;
41401       Lo = Lo.getOperand(WideMask128[0] & 1);
41402       Hi = Hi.getOperand(WideMask128[1] & 1);
41403       if (SingleOp) {
41404         SDValue Undef = DAG.getUNDEF(SrcVT);
41405         SDValue Zero = getZeroVector(SrcVT, Subtarget, DAG, DL);
41406         Lo = (WideMask128[0] == SM_SentinelZero ? Zero : Lo);
41407         Hi = (WideMask128[1] == SM_SentinelZero ? Zero : Hi);
41408         Lo = (WideMask128[0] == SM_SentinelUndef ? Undef : Lo);
41409         Hi = (WideMask128[1] == SM_SentinelUndef ? Undef : Hi);
41410       }
41411       return DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
41412     }
41413   }
41414 
41415   // If we are post-shuffling a 256-bit hop and not requiring the upper
41416   // elements, then try to narrow to a 128-bit hop directly.
41417   SmallVector<int, 16> WideMask64;
41418   if (Ops.size() == 1 && NumLanes == 2 &&
41419       scaleShuffleElements(Mask, 4, WideMask64) &&
41420       isUndefInRange(WideMask64, 2, 2)) {
41421     int M0 = WideMask64[0];
41422     int M1 = WideMask64[1];
41423     if (isInRange(M0, 0, 4) && isInRange(M1, 0, 4)) {
41424       MVT HalfVT = VT0.getSimpleVT().getHalfNumVectorElementsVT();
41425       unsigned Idx0 = (M0 & 2) ? (SrcVT.getVectorNumElements() / 2) : 0;
41426       unsigned Idx1 = (M1 & 2) ? (SrcVT.getVectorNumElements() / 2) : 0;
41427       SDValue V0 = extract128BitVector(BC[0].getOperand(M0 & 1), Idx0, DAG, DL);
41428       SDValue V1 = extract128BitVector(BC[0].getOperand(M1 & 1), Idx1, DAG, DL);
41429       SDValue Res = DAG.getNode(Opcode0, DL, HalfVT, V0, V1);
41430       return widenSubVector(Res, false, Subtarget, DAG, DL, 256);
41431     }
41432   }
41433 
41434   return SDValue();
41435 }
41436 
41437 // Attempt to constant fold all of the constant source ops.
41438 // Returns true if the entire shuffle is folded to a constant.
41439 // TODO: Extend this to merge multiple constant Ops and update the mask.
41440 static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
41441                                            ArrayRef<int> Mask, SDValue Root,
41442                                            bool HasVariableMask,
41443                                            SelectionDAG &DAG,
41444                                            const X86Subtarget &Subtarget) {
41445   MVT VT = Root.getSimpleValueType();
41446 
41447   unsigned SizeInBits = VT.getSizeInBits();
41448   unsigned NumMaskElts = Mask.size();
41449   unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
41450   unsigned NumOps = Ops.size();
41451 
41452   // Extract constant bits from each source op.
41453   SmallVector<APInt, 16> UndefEltsOps(NumOps);
41454   SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
41455   for (unsigned I = 0; I != NumOps; ++I)
41456     if (!getTargetConstantBitsFromNode(Ops[I], MaskSizeInBits, UndefEltsOps[I],
41457                                        RawBitsOps[I]))
41458       return SDValue();
41459 
41460   // If we're optimizing for size, only fold if at least one of the constants is
41461   // only used once or the combined shuffle has included a variable mask
41462   // shuffle, this is to avoid constant pool bloat.
41463   bool IsOptimizingSize = DAG.shouldOptForSize();
41464   if (IsOptimizingSize && !HasVariableMask &&
41465       llvm::none_of(Ops, [](SDValue SrcOp) { return SrcOp->hasOneUse(); }))
41466     return SDValue();
41467 
41468   // Shuffle the constant bits according to the mask.
41469   SDLoc DL(Root);
41470   APInt UndefElts(NumMaskElts, 0);
41471   APInt ZeroElts(NumMaskElts, 0);
41472   APInt ConstantElts(NumMaskElts, 0);
41473   SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
41474                                         APInt::getZero(MaskSizeInBits));
41475   for (unsigned i = 0; i != NumMaskElts; ++i) {
41476     int M = Mask[i];
41477     if (M == SM_SentinelUndef) {
41478       UndefElts.setBit(i);
41479       continue;
41480     } else if (M == SM_SentinelZero) {
41481       ZeroElts.setBit(i);
41482       continue;
41483     }
41484     assert(0 <= M && M < (int)(NumMaskElts * NumOps));
41485 
41486     unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
41487     unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
41488 
41489     auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
41490     if (SrcUndefElts[SrcMaskIdx]) {
41491       UndefElts.setBit(i);
41492       continue;
41493     }
41494 
41495     auto &SrcEltBits = RawBitsOps[SrcOpIdx];
41496     APInt &Bits = SrcEltBits[SrcMaskIdx];
41497     if (!Bits) {
41498       ZeroElts.setBit(i);
41499       continue;
41500     }
41501 
41502     ConstantElts.setBit(i);
41503     ConstantBitData[i] = Bits;
41504   }
41505   assert((UndefElts | ZeroElts | ConstantElts).isAllOnes());
41506 
41507   // Attempt to create a zero vector.
41508   if ((UndefElts | ZeroElts).isAllOnes())
41509     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG, DL);
41510 
41511   // Create the constant data.
41512   MVT MaskSVT;
41513   if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
41514     MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
41515   else
41516     MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
41517 
41518   MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
41519   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
41520     return SDValue();
41521 
41522   SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
41523   return DAG.getBitcast(VT, CstOp);
41524 }
41525 
41526 namespace llvm {
41527   namespace X86 {
41528     enum {
41529       MaxShuffleCombineDepth = 8
41530     };
41531   } // namespace X86
41532 } // namespace llvm
41533 
41534 /// Fully generic combining of x86 shuffle instructions.
41535 ///
41536 /// This should be the last combine run over the x86 shuffle instructions. Once
41537 /// they have been fully optimized, this will recursively consider all chains
41538 /// of single-use shuffle instructions, build a generic model of the cumulative
41539 /// shuffle operation, and check for simpler instructions which implement this
41540 /// operation. We use this primarily for two purposes:
41541 ///
41542 /// 1) Collapse generic shuffles to specialized single instructions when
41543 ///    equivalent. In most cases, this is just an encoding size win, but
41544 ///    sometimes we will collapse multiple generic shuffles into a single
41545 ///    special-purpose shuffle.
41546 /// 2) Look for sequences of shuffle instructions with 3 or more total
41547 ///    instructions, and replace them with the slightly more expensive SSSE3
41548 ///    PSHUFB instruction if available. We do this as the last combining step
41549 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
41550 ///    a suitable short sequence of other instructions. The PSHUFB will either
41551 ///    use a register or have to read from memory and so is slightly (but only
41552 ///    slightly) more expensive than the other shuffle instructions.
41553 ///
41554 /// Because this is inherently a quadratic operation (for each shuffle in
41555 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
41556 /// This should never be an issue in practice as the shuffle lowering doesn't
41557 /// produce sequences of more than 8 instructions.
41558 ///
41559 /// FIXME: We will currently miss some cases where the redundant shuffling
41560 /// would simplify under the threshold for PSHUFB formation because of
41561 /// combine-ordering. To fix this, we should do the redundant instruction
41562 /// combining in this recursive walk.
41563 static SDValue combineX86ShufflesRecursively(
41564     ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
41565     ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
41566     unsigned MaxDepth, bool HasVariableMask, bool AllowVariableCrossLaneMask,
41567     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
41568     const X86Subtarget &Subtarget) {
41569   assert(!RootMask.empty() &&
41570          (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&
41571          "Illegal shuffle root mask");
41572   MVT RootVT = Root.getSimpleValueType();
41573   assert(RootVT.isVector() && "Shuffles operate on vector types!");
41574   unsigned RootSizeInBits = RootVT.getSizeInBits();
41575 
41576   // Bound the depth of our recursive combine because this is ultimately
41577   // quadratic in nature.
41578   if (Depth >= MaxDepth)
41579     return SDValue();
41580 
41581   // Directly rip through bitcasts to find the underlying operand.
41582   SDValue Op = SrcOps[SrcOpIndex];
41583   Op = peekThroughOneUseBitcasts(Op);
41584 
41585   EVT VT = Op.getValueType();
41586   if (!VT.isVector() || !VT.isSimple())
41587     return SDValue(); // Bail if we hit a non-simple non-vector.
41588 
41589   // FIXME: Just bail on f16 for now.
41590   if (VT.getVectorElementType() == MVT::f16)
41591     return SDValue();
41592 
41593   assert((RootSizeInBits % VT.getSizeInBits()) == 0 &&
41594          "Can only combine shuffles upto size of the root op.");
41595 
41596   // Create a demanded elts mask from the referenced elements of Op.
41597   APInt OpDemandedElts = APInt::getZero(RootMask.size());
41598   for (int M : RootMask) {
41599     int BaseIdx = RootMask.size() * SrcOpIndex;
41600     if (isInRange(M, BaseIdx, BaseIdx + RootMask.size()))
41601       OpDemandedElts.setBit(M - BaseIdx);
41602   }
41603   if (RootSizeInBits != VT.getSizeInBits()) {
41604     // Op is smaller than Root - extract the demanded elts for the subvector.
41605     unsigned Scale = RootSizeInBits / VT.getSizeInBits();
41606     unsigned NumOpMaskElts = RootMask.size() / Scale;
41607     assert((RootMask.size() % Scale) == 0 && "Root mask size mismatch");
41608     assert(OpDemandedElts
41609                .extractBits(RootMask.size() - NumOpMaskElts, NumOpMaskElts)
41610                .isZero() &&
41611            "Out of range elements referenced in root mask");
41612     OpDemandedElts = OpDemandedElts.extractBits(NumOpMaskElts, 0);
41613   }
41614   OpDemandedElts =
41615       APIntOps::ScaleBitMask(OpDemandedElts, VT.getVectorNumElements());
41616 
41617   // Extract target shuffle mask and resolve sentinels and inputs.
41618   SmallVector<int, 64> OpMask;
41619   SmallVector<SDValue, 2> OpInputs;
41620   APInt OpUndef, OpZero;
41621   bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
41622   if (getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
41623                              OpZero, DAG, Depth, false)) {
41624     // Shuffle inputs must not be larger than the shuffle result.
41625     // TODO: Relax this for single input faux shuffles (e.g. trunc).
41626     if (llvm::any_of(OpInputs, [VT](SDValue OpInput) {
41627           return OpInput.getValueSizeInBits() > VT.getSizeInBits();
41628         }))
41629       return SDValue();
41630   } else if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41631              (RootSizeInBits % Op.getOperand(0).getValueSizeInBits()) == 0 &&
41632              !isNullConstant(Op.getOperand(1))) {
41633     SDValue SrcVec = Op.getOperand(0);
41634     int ExtractIdx = Op.getConstantOperandVal(1);
41635     unsigned NumElts = VT.getVectorNumElements();
41636     OpInputs.assign({SrcVec});
41637     OpMask.assign(NumElts, SM_SentinelUndef);
41638     std::iota(OpMask.begin(), OpMask.end(), ExtractIdx);
41639     OpZero = OpUndef = APInt::getZero(NumElts);
41640   } else {
41641     return SDValue();
41642   }
41643 
41644   // If the shuffle result was smaller than the root, we need to adjust the
41645   // mask indices and pad the mask with undefs.
41646   if (RootSizeInBits > VT.getSizeInBits()) {
41647     unsigned NumSubVecs = RootSizeInBits / VT.getSizeInBits();
41648     unsigned OpMaskSize = OpMask.size();
41649     if (OpInputs.size() > 1) {
41650       unsigned PaddedMaskSize = NumSubVecs * OpMaskSize;
41651       for (int &M : OpMask) {
41652         if (M < 0)
41653           continue;
41654         int EltIdx = M % OpMaskSize;
41655         int OpIdx = M / OpMaskSize;
41656         M = (PaddedMaskSize * OpIdx) + EltIdx;
41657       }
41658     }
41659     OpZero = OpZero.zext(NumSubVecs * OpMaskSize);
41660     OpUndef = OpUndef.zext(NumSubVecs * OpMaskSize);
41661     OpMask.append((NumSubVecs - 1) * OpMaskSize, SM_SentinelUndef);
41662   }
41663 
41664   SmallVector<int, 64> Mask;
41665   SmallVector<SDValue, 16> Ops;
41666 
41667   // We don't need to merge masks if the root is empty.
41668   bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
41669   if (EmptyRoot) {
41670     // Only resolve zeros if it will remove an input, otherwise we might end
41671     // up in an infinite loop.
41672     bool ResolveKnownZeros = true;
41673     if (!OpZero.isZero()) {
41674       APInt UsedInputs = APInt::getZero(OpInputs.size());
41675       for (int i = 0, e = OpMask.size(); i != e; ++i) {
41676         int M = OpMask[i];
41677         if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
41678           continue;
41679         UsedInputs.setBit(M / OpMask.size());
41680         if (UsedInputs.isAllOnes()) {
41681           ResolveKnownZeros = false;
41682           break;
41683         }
41684       }
41685     }
41686     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
41687                                       ResolveKnownZeros);
41688 
41689     Mask = OpMask;
41690     Ops.append(OpInputs.begin(), OpInputs.end());
41691   } else {
41692     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
41693 
41694     // Add the inputs to the Ops list, avoiding duplicates.
41695     Ops.append(SrcOps.begin(), SrcOps.end());
41696 
41697     auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
41698       // Attempt to find an existing match.
41699       SDValue InputBC = peekThroughBitcasts(Input);
41700       for (int i = 0, e = Ops.size(); i < e; ++i)
41701         if (InputBC == peekThroughBitcasts(Ops[i]))
41702           return i;
41703       // Match failed - should we replace an existing Op?
41704       if (InsertionPoint >= 0) {
41705         Ops[InsertionPoint] = Input;
41706         return InsertionPoint;
41707       }
41708       // Add to the end of the Ops list.
41709       Ops.push_back(Input);
41710       return Ops.size() - 1;
41711     };
41712 
41713     SmallVector<int, 2> OpInputIdx;
41714     for (SDValue OpInput : OpInputs)
41715       OpInputIdx.push_back(
41716           AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
41717 
41718     assert(((RootMask.size() > OpMask.size() &&
41719              RootMask.size() % OpMask.size() == 0) ||
41720             (OpMask.size() > RootMask.size() &&
41721              OpMask.size() % RootMask.size() == 0) ||
41722             OpMask.size() == RootMask.size()) &&
41723            "The smaller number of elements must divide the larger.");
41724 
41725     // This function can be performance-critical, so we rely on the power-of-2
41726     // knowledge that we have about the mask sizes to replace div/rem ops with
41727     // bit-masks and shifts.
41728     assert(llvm::has_single_bit<uint32_t>(RootMask.size()) &&
41729            "Non-power-of-2 shuffle mask sizes");
41730     assert(llvm::has_single_bit<uint32_t>(OpMask.size()) &&
41731            "Non-power-of-2 shuffle mask sizes");
41732     unsigned RootMaskSizeLog2 = llvm::countr_zero(RootMask.size());
41733     unsigned OpMaskSizeLog2 = llvm::countr_zero(OpMask.size());
41734 
41735     unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
41736     unsigned RootRatio =
41737         std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
41738     unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
41739     assert((RootRatio == 1 || OpRatio == 1) &&
41740            "Must not have a ratio for both incoming and op masks!");
41741 
41742     assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
41743     assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
41744     assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
41745     unsigned RootRatioLog2 = llvm::countr_zero(RootRatio);
41746     unsigned OpRatioLog2 = llvm::countr_zero(OpRatio);
41747 
41748     Mask.resize(MaskWidth, SM_SentinelUndef);
41749 
41750     // Merge this shuffle operation's mask into our accumulated mask. Note that
41751     // this shuffle's mask will be the first applied to the input, followed by
41752     // the root mask to get us all the way to the root value arrangement. The
41753     // reason for this order is that we are recursing up the operation chain.
41754     for (unsigned i = 0; i < MaskWidth; ++i) {
41755       unsigned RootIdx = i >> RootRatioLog2;
41756       if (RootMask[RootIdx] < 0) {
41757         // This is a zero or undef lane, we're done.
41758         Mask[i] = RootMask[RootIdx];
41759         continue;
41760       }
41761 
41762       unsigned RootMaskedIdx =
41763           RootRatio == 1
41764               ? RootMask[RootIdx]
41765               : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
41766 
41767       // Just insert the scaled root mask value if it references an input other
41768       // than the SrcOp we're currently inserting.
41769       if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
41770           (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
41771         Mask[i] = RootMaskedIdx;
41772         continue;
41773       }
41774 
41775       RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
41776       unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
41777       if (OpMask[OpIdx] < 0) {
41778         // The incoming lanes are zero or undef, it doesn't matter which ones we
41779         // are using.
41780         Mask[i] = OpMask[OpIdx];
41781         continue;
41782       }
41783 
41784       // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
41785       unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
41786                                           : (OpMask[OpIdx] << OpRatioLog2) +
41787                                                 (RootMaskedIdx & (OpRatio - 1));
41788 
41789       OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
41790       int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
41791       assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input");
41792       OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
41793 
41794       Mask[i] = OpMaskedIdx;
41795     }
41796   }
41797 
41798   // Peek through vector widenings and set out of bounds mask indices to undef.
41799   // TODO: Can resolveTargetShuffleInputsAndMask do some of this?
41800   for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
41801     SDValue &Op = Ops[I];
41802     if (Op.getOpcode() == ISD::INSERT_SUBVECTOR && Op.getOperand(0).isUndef() &&
41803         isNullConstant(Op.getOperand(2))) {
41804       Op = Op.getOperand(1);
41805       unsigned Scale = RootSizeInBits / Op.getValueSizeInBits();
41806       int Lo = I * Mask.size();
41807       int Hi = (I + 1) * Mask.size();
41808       int NewHi = Lo + (Mask.size() / Scale);
41809       for (int &M : Mask) {
41810         if (Lo <= M && NewHi <= M && M < Hi)
41811           M = SM_SentinelUndef;
41812       }
41813     }
41814   }
41815 
41816   // Peek through any free extract_subvector nodes back to root size.
41817   for (SDValue &Op : Ops)
41818     while (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41819            (RootSizeInBits % Op.getOperand(0).getValueSizeInBits()) == 0 &&
41820            isNullConstant(Op.getOperand(1)))
41821       Op = Op.getOperand(0);
41822 
41823   // Remove unused/repeated shuffle source ops.
41824   resolveTargetShuffleInputsAndMask(Ops, Mask);
41825 
41826   // Handle the all undef/zero/ones cases early.
41827   if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
41828     return DAG.getUNDEF(RootVT);
41829   if (all_of(Mask, [](int Idx) { return Idx < 0; }))
41830     return getZeroVector(RootVT, Subtarget, DAG, SDLoc(Root));
41831   if (Ops.size() == 1 && ISD::isBuildVectorAllOnes(Ops[0].getNode()) &&
41832       !llvm::is_contained(Mask, SM_SentinelZero))
41833     return getOnesVector(RootVT, DAG, SDLoc(Root));
41834 
41835   assert(!Ops.empty() && "Shuffle with no inputs detected");
41836   HasVariableMask |= IsOpVariableMask;
41837 
41838   // Update the list of shuffle nodes that have been combined so far.
41839   SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
41840                                                 SrcNodes.end());
41841   CombinedNodes.push_back(Op.getNode());
41842 
41843   // See if we can recurse into each shuffle source op (if it's a target
41844   // shuffle). The source op should only be generally combined if it either has
41845   // a single use (i.e. current Op) or all its users have already been combined,
41846   // if not then we can still combine but should prevent generation of variable
41847   // shuffles to avoid constant pool bloat.
41848   // Don't recurse if we already have more source ops than we can combine in
41849   // the remaining recursion depth.
41850   if (Ops.size() < (MaxDepth - Depth)) {
41851     for (int i = 0, e = Ops.size(); i < e; ++i) {
41852       // For empty roots, we need to resolve zeroable elements before combining
41853       // them with other shuffles.
41854       SmallVector<int, 64> ResolvedMask = Mask;
41855       if (EmptyRoot)
41856         resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
41857       bool AllowCrossLaneVar = false;
41858       bool AllowPerLaneVar = false;
41859       if (Ops[i].getNode()->hasOneUse() ||
41860           SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode())) {
41861         AllowCrossLaneVar = AllowVariableCrossLaneMask;
41862         AllowPerLaneVar = AllowVariablePerLaneMask;
41863       }
41864       if (SDValue Res = combineX86ShufflesRecursively(
41865               Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1, MaxDepth,
41866               HasVariableMask, AllowCrossLaneVar, AllowPerLaneVar, DAG,
41867               Subtarget))
41868         return Res;
41869     }
41870   }
41871 
41872   // Attempt to constant fold all of the constant source ops.
41873   if (SDValue Cst = combineX86ShufflesConstants(
41874           Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
41875     return Cst;
41876 
41877   // If constant fold failed and we only have constants - then we have
41878   // multiple uses by a single non-variable shuffle - just bail.
41879   if (Depth == 0 && llvm::all_of(Ops, [&](SDValue Op) {
41880         APInt UndefElts;
41881         SmallVector<APInt> RawBits;
41882         unsigned EltSizeInBits = RootSizeInBits / Mask.size();
41883         return getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
41884                                              RawBits);
41885       })) {
41886     return SDValue();
41887   }
41888 
41889   // Canonicalize the combined shuffle mask chain with horizontal ops.
41890   // NOTE: This will update the Ops and Mask.
41891   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
41892           Ops, Mask, RootSizeInBits, SDLoc(Root), DAG, Subtarget))
41893     return DAG.getBitcast(RootVT, HOp);
41894 
41895   // Try to refine our inputs given our knowledge of target shuffle mask.
41896   for (auto I : enumerate(Ops)) {
41897     int OpIdx = I.index();
41898     SDValue &Op = I.value();
41899 
41900     // What range of shuffle mask element values results in picking from Op?
41901     int Lo = OpIdx * Mask.size();
41902     int Hi = Lo + Mask.size();
41903 
41904     // Which elements of Op do we demand, given the mask's granularity?
41905     APInt OpDemandedElts(Mask.size(), 0);
41906     for (int MaskElt : Mask) {
41907       if (isInRange(MaskElt, Lo, Hi)) { // Picks from Op?
41908         int OpEltIdx = MaskElt - Lo;
41909         OpDemandedElts.setBit(OpEltIdx);
41910       }
41911     }
41912 
41913     // Is the shuffle result smaller than the root?
41914     if (Op.getValueSizeInBits() < RootSizeInBits) {
41915       // We padded the mask with undefs. But we now need to undo that.
41916       unsigned NumExpectedVectorElts = Mask.size();
41917       unsigned EltSizeInBits = RootSizeInBits / NumExpectedVectorElts;
41918       unsigned NumOpVectorElts = Op.getValueSizeInBits() / EltSizeInBits;
41919       assert(!OpDemandedElts.extractBits(
41920                  NumExpectedVectorElts - NumOpVectorElts, NumOpVectorElts) &&
41921              "Demanding the virtual undef widening padding?");
41922       OpDemandedElts = OpDemandedElts.trunc(NumOpVectorElts); // NUW
41923     }
41924 
41925     // The Op itself may be of different VT, so we need to scale the mask.
41926     unsigned NumOpElts = Op.getValueType().getVectorNumElements();
41927     APInt OpScaledDemandedElts = APIntOps::ScaleBitMask(OpDemandedElts, NumOpElts);
41928 
41929     // Can this operand be simplified any further, given it's demanded elements?
41930     if (SDValue NewOp =
41931             DAG.getTargetLoweringInfo().SimplifyMultipleUseDemandedVectorElts(
41932                 Op, OpScaledDemandedElts, DAG))
41933       Op = NewOp;
41934   }
41935   // FIXME: should we rerun resolveTargetShuffleInputsAndMask() now?
41936 
41937   // Widen any subvector shuffle inputs we've collected.
41938   // TODO: Remove this to avoid generating temporary nodes, we should only
41939   // widen once combineX86ShuffleChain has found a match.
41940   if (any_of(Ops, [RootSizeInBits](SDValue Op) {
41941         return Op.getValueSizeInBits() < RootSizeInBits;
41942       })) {
41943     for (SDValue &Op : Ops)
41944       if (Op.getValueSizeInBits() < RootSizeInBits)
41945         Op = widenSubVector(Op, false, Subtarget, DAG, SDLoc(Op),
41946                             RootSizeInBits);
41947     // Reresolve - we might have repeated subvector sources.
41948     resolveTargetShuffleInputsAndMask(Ops, Mask);
41949   }
41950 
41951   // We can only combine unary and binary shuffle mask cases.
41952   if (Ops.size() <= 2) {
41953     // Minor canonicalization of the accumulated shuffle mask to make it easier
41954     // to match below. All this does is detect masks with sequential pairs of
41955     // elements, and shrink them to the half-width mask. It does this in a loop
41956     // so it will reduce the size of the mask to the minimal width mask which
41957     // performs an equivalent shuffle.
41958     while (Mask.size() > 1) {
41959       SmallVector<int, 64> WidenedMask;
41960       if (!canWidenShuffleElements(Mask, WidenedMask))
41961         break;
41962       Mask = std::move(WidenedMask);
41963     }
41964 
41965     // Canonicalization of binary shuffle masks to improve pattern matching by
41966     // commuting the inputs.
41967     if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
41968       ShuffleVectorSDNode::commuteMask(Mask);
41969       std::swap(Ops[0], Ops[1]);
41970     }
41971 
41972     // Try to combine into a single shuffle instruction.
41973     if (SDValue Shuffle = combineX86ShuffleChain(
41974             Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
41975             AllowVariablePerLaneMask, DAG, Subtarget))
41976       return Shuffle;
41977 
41978     // If all the operands come from the same larger vector, fallthrough and try
41979     // to use combineX86ShuffleChainWithExtract.
41980     SDValue LHS = peekThroughBitcasts(Ops.front());
41981     SDValue RHS = peekThroughBitcasts(Ops.back());
41982     if (Ops.size() != 2 || !Subtarget.hasAVX2() || RootSizeInBits != 128 ||
41983         (RootSizeInBits / Mask.size()) != 64 ||
41984         LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
41985         RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
41986         LHS.getOperand(0) != RHS.getOperand(0))
41987       return SDValue();
41988   }
41989 
41990   // If that failed and any input is extracted then try to combine as a
41991   // shuffle with the larger type.
41992   return combineX86ShuffleChainWithExtract(
41993       Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
41994       AllowVariablePerLaneMask, DAG, Subtarget);
41995 }
41996 
41997 /// Helper entry wrapper to combineX86ShufflesRecursively.
41998 static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
41999                                              const X86Subtarget &Subtarget) {
42000   return combineX86ShufflesRecursively(
42001       {Op}, 0, Op, {0}, {}, /*Depth*/ 0, X86::MaxShuffleCombineDepth,
42002       /*HasVarMask*/ false,
42003       /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, DAG,
42004       Subtarget);
42005 }
42006 
42007 /// Get the PSHUF-style mask from PSHUF node.
42008 ///
42009 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
42010 /// PSHUF-style masks that can be reused with such instructions.
42011 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
42012   MVT VT = N.getSimpleValueType();
42013   SmallVector<int, 4> Mask;
42014   SmallVector<SDValue, 2> Ops;
42015   bool HaveMask =
42016       getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask);
42017   (void)HaveMask;
42018   assert(HaveMask);
42019 
42020   // If we have more than 128-bits, only the low 128-bits of shuffle mask
42021   // matter. Check that the upper masks are repeats and remove them.
42022   if (VT.getSizeInBits() > 128) {
42023     int LaneElts = 128 / VT.getScalarSizeInBits();
42024 #ifndef NDEBUG
42025     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
42026       for (int j = 0; j < LaneElts; ++j)
42027         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
42028                "Mask doesn't repeat in high 128-bit lanes!");
42029 #endif
42030     Mask.resize(LaneElts);
42031   }
42032 
42033   switch (N.getOpcode()) {
42034   case X86ISD::PSHUFD:
42035     return Mask;
42036   case X86ISD::PSHUFLW:
42037     Mask.resize(4);
42038     return Mask;
42039   case X86ISD::PSHUFHW:
42040     Mask.erase(Mask.begin(), Mask.begin() + 4);
42041     for (int &M : Mask)
42042       M -= 4;
42043     return Mask;
42044   default:
42045     llvm_unreachable("No valid shuffle instruction found!");
42046   }
42047 }
42048 
42049 /// Search for a combinable shuffle across a chain ending in pshufd.
42050 ///
42051 /// We walk up the chain and look for a combinable shuffle, skipping over
42052 /// shuffles that we could hoist this shuffle's transformation past without
42053 /// altering anything.
42054 static SDValue
42055 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
42056                              SelectionDAG &DAG) {
42057   assert(N.getOpcode() == X86ISD::PSHUFD &&
42058          "Called with something other than an x86 128-bit half shuffle!");
42059   SDLoc DL(N);
42060 
42061   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
42062   // of the shuffles in the chain so that we can form a fresh chain to replace
42063   // this one.
42064   SmallVector<SDValue, 8> Chain;
42065   SDValue V = N.getOperand(0);
42066   for (; V.hasOneUse(); V = V.getOperand(0)) {
42067     switch (V.getOpcode()) {
42068     default:
42069       return SDValue(); // Nothing combined!
42070 
42071     case ISD::BITCAST:
42072       // Skip bitcasts as we always know the type for the target specific
42073       // instructions.
42074       continue;
42075 
42076     case X86ISD::PSHUFD:
42077       // Found another dword shuffle.
42078       break;
42079 
42080     case X86ISD::PSHUFLW:
42081       // Check that the low words (being shuffled) are the identity in the
42082       // dword shuffle, and the high words are self-contained.
42083       if (Mask[0] != 0 || Mask[1] != 1 ||
42084           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
42085         return SDValue();
42086 
42087       Chain.push_back(V);
42088       continue;
42089 
42090     case X86ISD::PSHUFHW:
42091       // Check that the high words (being shuffled) are the identity in the
42092       // dword shuffle, and the low words are self-contained.
42093       if (Mask[2] != 2 || Mask[3] != 3 ||
42094           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
42095         return SDValue();
42096 
42097       Chain.push_back(V);
42098       continue;
42099 
42100     case X86ISD::UNPCKL:
42101     case X86ISD::UNPCKH:
42102       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
42103       // shuffle into a preceding word shuffle.
42104       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
42105           V.getSimpleValueType().getVectorElementType() != MVT::i16)
42106         return SDValue();
42107 
42108       // Search for a half-shuffle which we can combine with.
42109       unsigned CombineOp =
42110           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
42111       if (V.getOperand(0) != V.getOperand(1) ||
42112           !V->isOnlyUserOf(V.getOperand(0).getNode()))
42113         return SDValue();
42114       Chain.push_back(V);
42115       V = V.getOperand(0);
42116       do {
42117         switch (V.getOpcode()) {
42118         default:
42119           return SDValue(); // Nothing to combine.
42120 
42121         case X86ISD::PSHUFLW:
42122         case X86ISD::PSHUFHW:
42123           if (V.getOpcode() == CombineOp)
42124             break;
42125 
42126           Chain.push_back(V);
42127 
42128           [[fallthrough]];
42129         case ISD::BITCAST:
42130           V = V.getOperand(0);
42131           continue;
42132         }
42133         break;
42134       } while (V.hasOneUse());
42135       break;
42136     }
42137     // Break out of the loop if we break out of the switch.
42138     break;
42139   }
42140 
42141   if (!V.hasOneUse())
42142     // We fell out of the loop without finding a viable combining instruction.
42143     return SDValue();
42144 
42145   // Merge this node's mask and our incoming mask.
42146   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
42147   for (int &M : Mask)
42148     M = VMask[M];
42149   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
42150                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
42151 
42152   // Rebuild the chain around this new shuffle.
42153   while (!Chain.empty()) {
42154     SDValue W = Chain.pop_back_val();
42155 
42156     if (V.getValueType() != W.getOperand(0).getValueType())
42157       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
42158 
42159     switch (W.getOpcode()) {
42160     default:
42161       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
42162 
42163     case X86ISD::UNPCKL:
42164     case X86ISD::UNPCKH:
42165       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
42166       break;
42167 
42168     case X86ISD::PSHUFD:
42169     case X86ISD::PSHUFLW:
42170     case X86ISD::PSHUFHW:
42171       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
42172       break;
42173     }
42174   }
42175   if (V.getValueType() != N.getValueType())
42176     V = DAG.getBitcast(N.getValueType(), V);
42177 
42178   // Return the new chain to replace N.
42179   return V;
42180 }
42181 
42182 // Attempt to commute shufps LHS loads:
42183 // permilps(shufps(load(),x)) --> permilps(shufps(x,load()))
42184 static SDValue combineCommutableSHUFP(SDValue N, MVT VT, const SDLoc &DL,
42185                                       SelectionDAG &DAG) {
42186   // TODO: Add vXf64 support.
42187   if (VT != MVT::v4f32 && VT != MVT::v8f32 && VT != MVT::v16f32)
42188     return SDValue();
42189 
42190   // SHUFP(LHS, RHS) -> SHUFP(RHS, LHS) iff LHS is foldable + RHS is not.
42191   auto commuteSHUFP = [&VT, &DL, &DAG](SDValue Parent, SDValue V) {
42192     if (V.getOpcode() != X86ISD::SHUFP || !Parent->isOnlyUserOf(V.getNode()))
42193       return SDValue();
42194     SDValue N0 = V.getOperand(0);
42195     SDValue N1 = V.getOperand(1);
42196     unsigned Imm = V.getConstantOperandVal(2);
42197     const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
42198     if (!X86::mayFoldLoad(peekThroughOneUseBitcasts(N0), Subtarget) ||
42199         X86::mayFoldLoad(peekThroughOneUseBitcasts(N1), Subtarget))
42200       return SDValue();
42201     Imm = ((Imm & 0x0F) << 4) | ((Imm & 0xF0) >> 4);
42202     return DAG.getNode(X86ISD::SHUFP, DL, VT, N1, N0,
42203                        DAG.getTargetConstant(Imm, DL, MVT::i8));
42204   };
42205 
42206   switch (N.getOpcode()) {
42207   case X86ISD::VPERMILPI:
42208     if (SDValue NewSHUFP = commuteSHUFP(N, N.getOperand(0))) {
42209       unsigned Imm = N.getConstantOperandVal(1);
42210       return DAG.getNode(X86ISD::VPERMILPI, DL, VT, NewSHUFP,
42211                          DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
42212     }
42213     break;
42214   case X86ISD::SHUFP: {
42215     SDValue N0 = N.getOperand(0);
42216     SDValue N1 = N.getOperand(1);
42217     unsigned Imm = N.getConstantOperandVal(2);
42218     if (N0 == N1) {
42219       if (SDValue NewSHUFP = commuteSHUFP(N, N0))
42220         return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, NewSHUFP,
42221                            DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
42222     } else if (SDValue NewSHUFP = commuteSHUFP(N, N0)) {
42223       return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, N1,
42224                          DAG.getTargetConstant(Imm ^ 0x0A, DL, MVT::i8));
42225     } else if (SDValue NewSHUFP = commuteSHUFP(N, N1)) {
42226       return DAG.getNode(X86ISD::SHUFP, DL, VT, N0, NewSHUFP,
42227                          DAG.getTargetConstant(Imm ^ 0xA0, DL, MVT::i8));
42228     }
42229     break;
42230   }
42231   }
42232 
42233   return SDValue();
42234 }
42235 
42236 // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
42237 static SDValue canonicalizeShuffleWithBinOps(SDValue N, SelectionDAG &DAG,
42238                                              const SDLoc &DL) {
42239   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42240   EVT ShuffleVT = N.getValueType();
42241 
42242   auto IsMergeableWithShuffle = [&DAG](SDValue Op, bool FoldLoad = false) {
42243     // AllZeros/AllOnes constants are freely shuffled and will peek through
42244     // bitcasts. Other constant build vectors do not peek through bitcasts. Only
42245     // merge with target shuffles if it has one use so shuffle combining is
42246     // likely to kick in. Shuffles of splats are expected to be removed.
42247     return ISD::isBuildVectorAllOnes(Op.getNode()) ||
42248            ISD::isBuildVectorAllZeros(Op.getNode()) ||
42249            ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
42250            ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()) ||
42251            (Op.getOpcode() == ISD::INSERT_SUBVECTOR && Op->hasOneUse()) ||
42252            (isTargetShuffle(Op.getOpcode()) && Op->hasOneUse()) ||
42253            (FoldLoad && isShuffleFoldableLoad(Op)) ||
42254            DAG.isSplatValue(Op, /*AllowUndefs*/ false);
42255   };
42256   auto IsSafeToMoveShuffle = [ShuffleVT](SDValue Op, unsigned BinOp) {
42257     // Ensure we only shuffle whole vector src elements, unless its a logical
42258     // binops where we can more aggressively move shuffles from dst to src.
42259     return BinOp == ISD::AND || BinOp == ISD::OR || BinOp == ISD::XOR ||
42260            BinOp == X86ISD::ANDNP ||
42261            (Op.getScalarValueSizeInBits() <= ShuffleVT.getScalarSizeInBits());
42262   };
42263 
42264   unsigned Opc = N.getOpcode();
42265   switch (Opc) {
42266   // Unary and Unary+Permute Shuffles.
42267   case X86ISD::PSHUFB: {
42268     // Don't merge PSHUFB if it contains zero'd elements.
42269     SmallVector<int> Mask;
42270     SmallVector<SDValue> Ops;
42271     if (!getTargetShuffleMask(N.getNode(), ShuffleVT.getSimpleVT(), false, Ops,
42272                               Mask))
42273       break;
42274     [[fallthrough]];
42275   }
42276   case X86ISD::VBROADCAST:
42277   case X86ISD::MOVDDUP:
42278   case X86ISD::PSHUFD:
42279   case X86ISD::PSHUFHW:
42280   case X86ISD::PSHUFLW:
42281   case X86ISD::VPERMI:
42282   case X86ISD::VPERMILPI: {
42283     if (N.getOperand(0).getValueType() == ShuffleVT &&
42284         N->isOnlyUserOf(N.getOperand(0).getNode())) {
42285       SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
42286       unsigned SrcOpcode = N0.getOpcode();
42287       if (TLI.isBinOp(SrcOpcode) && IsSafeToMoveShuffle(N0, SrcOpcode)) {
42288         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
42289         SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
42290         if (IsMergeableWithShuffle(Op00, Opc != X86ISD::PSHUFB) ||
42291             IsMergeableWithShuffle(Op01, Opc != X86ISD::PSHUFB)) {
42292           SDValue LHS, RHS;
42293           Op00 = DAG.getBitcast(ShuffleVT, Op00);
42294           Op01 = DAG.getBitcast(ShuffleVT, Op01);
42295           if (N.getNumOperands() == 2) {
42296             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, N.getOperand(1));
42297             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, N.getOperand(1));
42298           } else {
42299             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00);
42300             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01);
42301           }
42302           EVT OpVT = N0.getValueType();
42303           return DAG.getBitcast(ShuffleVT,
42304                                 DAG.getNode(SrcOpcode, DL, OpVT,
42305                                             DAG.getBitcast(OpVT, LHS),
42306                                             DAG.getBitcast(OpVT, RHS)));
42307         }
42308       }
42309     }
42310     break;
42311   }
42312   // Binary and Binary+Permute Shuffles.
42313   case X86ISD::INSERTPS: {
42314     // Don't merge INSERTPS if it contains zero'd elements.
42315     unsigned InsertPSMask = N.getConstantOperandVal(2);
42316     unsigned ZeroMask = InsertPSMask & 0xF;
42317     if (ZeroMask != 0)
42318       break;
42319     [[fallthrough]];
42320   }
42321   case X86ISD::MOVSD:
42322   case X86ISD::MOVSS:
42323   case X86ISD::BLENDI:
42324   case X86ISD::SHUFP:
42325   case X86ISD::UNPCKH:
42326   case X86ISD::UNPCKL: {
42327     if (N->isOnlyUserOf(N.getOperand(0).getNode()) &&
42328         N->isOnlyUserOf(N.getOperand(1).getNode())) {
42329       SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
42330       SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
42331       unsigned SrcOpcode = N0.getOpcode();
42332       if (TLI.isBinOp(SrcOpcode) && N1.getOpcode() == SrcOpcode &&
42333           N0.getValueType() == N1.getValueType() &&
42334           IsSafeToMoveShuffle(N0, SrcOpcode) &&
42335           IsSafeToMoveShuffle(N1, SrcOpcode)) {
42336         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
42337         SDValue Op10 = peekThroughOneUseBitcasts(N1.getOperand(0));
42338         SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
42339         SDValue Op11 = peekThroughOneUseBitcasts(N1.getOperand(1));
42340         // Ensure the total number of shuffles doesn't increase by folding this
42341         // shuffle through to the source ops.
42342         if (((IsMergeableWithShuffle(Op00) && IsMergeableWithShuffle(Op10)) ||
42343              (IsMergeableWithShuffle(Op01) && IsMergeableWithShuffle(Op11))) ||
42344             ((IsMergeableWithShuffle(Op00) || IsMergeableWithShuffle(Op10)) &&
42345              (IsMergeableWithShuffle(Op01) || IsMergeableWithShuffle(Op11)))) {
42346           SDValue LHS, RHS;
42347           Op00 = DAG.getBitcast(ShuffleVT, Op00);
42348           Op10 = DAG.getBitcast(ShuffleVT, Op10);
42349           Op01 = DAG.getBitcast(ShuffleVT, Op01);
42350           Op11 = DAG.getBitcast(ShuffleVT, Op11);
42351           if (N.getNumOperands() == 3) {
42352             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10, N.getOperand(2));
42353             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11, N.getOperand(2));
42354           } else {
42355             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10);
42356             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11);
42357           }
42358           EVT OpVT = N0.getValueType();
42359           return DAG.getBitcast(ShuffleVT,
42360                                 DAG.getNode(SrcOpcode, DL, OpVT,
42361                                             DAG.getBitcast(OpVT, LHS),
42362                                             DAG.getBitcast(OpVT, RHS)));
42363         }
42364       }
42365     }
42366     break;
42367   }
42368   }
42369   return SDValue();
42370 }
42371 
42372 /// Attempt to fold vpermf128(op(),op()) -> op(vpermf128(),vpermf128()).
42373 static SDValue canonicalizeLaneShuffleWithRepeatedOps(SDValue V,
42374                                                       SelectionDAG &DAG,
42375                                                       const SDLoc &DL) {
42376   assert(V.getOpcode() == X86ISD::VPERM2X128 && "Unknown lane shuffle");
42377 
42378   MVT VT = V.getSimpleValueType();
42379   SDValue Src0 = peekThroughBitcasts(V.getOperand(0));
42380   SDValue Src1 = peekThroughBitcasts(V.getOperand(1));
42381   unsigned SrcOpc0 = Src0.getOpcode();
42382   unsigned SrcOpc1 = Src1.getOpcode();
42383   EVT SrcVT0 = Src0.getValueType();
42384   EVT SrcVT1 = Src1.getValueType();
42385 
42386   if (!Src1.isUndef() && (SrcVT0 != SrcVT1 || SrcOpc0 != SrcOpc1))
42387     return SDValue();
42388 
42389   switch (SrcOpc0) {
42390   case X86ISD::MOVDDUP: {
42391     SDValue LHS = Src0.getOperand(0);
42392     SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
42393     SDValue Res =
42394         DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS, V.getOperand(2));
42395     Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res);
42396     return DAG.getBitcast(VT, Res);
42397   }
42398   case X86ISD::VPERMILPI:
42399     // TODO: Handle v4f64 permutes with different low/high lane masks.
42400     if (SrcVT0 == MVT::v4f64) {
42401       uint64_t Mask = Src0.getConstantOperandVal(1);
42402       if ((Mask & 0x3) != ((Mask >> 2) & 0x3))
42403         break;
42404     }
42405     [[fallthrough]];
42406   case X86ISD::VSHLI:
42407   case X86ISD::VSRLI:
42408   case X86ISD::VSRAI:
42409   case X86ISD::PSHUFD:
42410     if (Src1.isUndef() || Src0.getOperand(1) == Src1.getOperand(1)) {
42411       SDValue LHS = Src0.getOperand(0);
42412       SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
42413       SDValue Res = DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS,
42414                                 V.getOperand(2));
42415       Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res, Src0.getOperand(1));
42416       return DAG.getBitcast(VT, Res);
42417     }
42418     break;
42419   }
42420 
42421   return SDValue();
42422 }
42423 
42424 /// Try to combine x86 target specific shuffles.
42425 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
42426                                     TargetLowering::DAGCombinerInfo &DCI,
42427                                     const X86Subtarget &Subtarget) {
42428   SDLoc DL(N);
42429   MVT VT = N.getSimpleValueType();
42430   SmallVector<int, 4> Mask;
42431   unsigned Opcode = N.getOpcode();
42432 
42433   if (SDValue R = combineCommutableSHUFP(N, VT, DL, DAG))
42434     return R;
42435 
42436   // Handle specific target shuffles.
42437   switch (Opcode) {
42438   case X86ISD::MOVDDUP: {
42439     SDValue Src = N.getOperand(0);
42440     // Turn a 128-bit MOVDDUP of a full vector load into movddup+vzload.
42441     if (VT == MVT::v2f64 && Src.hasOneUse() &&
42442         ISD::isNormalLoad(Src.getNode())) {
42443       LoadSDNode *LN = cast<LoadSDNode>(Src);
42444       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::f64, MVT::v2f64, DAG)) {
42445         SDValue Movddup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, VZLoad);
42446         DCI.CombineTo(N.getNode(), Movddup);
42447         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
42448         DCI.recursivelyDeleteUnusedNodes(LN);
42449         return N; // Return N so it doesn't get rechecked!
42450       }
42451     }
42452 
42453     return SDValue();
42454   }
42455   case X86ISD::VBROADCAST: {
42456     SDValue Src = N.getOperand(0);
42457     SDValue BC = peekThroughBitcasts(Src);
42458     EVT SrcVT = Src.getValueType();
42459     EVT BCVT = BC.getValueType();
42460 
42461     // If broadcasting from another shuffle, attempt to simplify it.
42462     // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
42463     if (isTargetShuffle(BC.getOpcode()) &&
42464         VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
42465       unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
42466       SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
42467                                         SM_SentinelUndef);
42468       for (unsigned i = 0; i != Scale; ++i)
42469         DemandedMask[i] = i;
42470       if (SDValue Res = combineX86ShufflesRecursively(
42471               {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
42472               X86::MaxShuffleCombineDepth,
42473               /*HasVarMask*/ false, /*AllowCrossLaneVarMask*/ true,
42474               /*AllowPerLaneVarMask*/ true, DAG, Subtarget))
42475         return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
42476                            DAG.getBitcast(SrcVT, Res));
42477     }
42478 
42479     // broadcast(bitcast(src)) -> bitcast(broadcast(src))
42480     // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
42481     if (Src.getOpcode() == ISD::BITCAST &&
42482         SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits() &&
42483         DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
42484         FixedVectorType::isValidElementType(
42485             BCVT.getScalarType().getTypeForEVT(*DAG.getContext()))) {
42486       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
42487                                    VT.getVectorNumElements());
42488       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
42489     }
42490 
42491     // vbroadcast(bitcast(vbroadcast(src))) -> bitcast(vbroadcast(src))
42492     // If we're re-broadcasting a smaller type then broadcast with that type and
42493     // bitcast.
42494     // TODO: Do this for any splat?
42495     if (Src.getOpcode() == ISD::BITCAST &&
42496         (BC.getOpcode() == X86ISD::VBROADCAST ||
42497          BC.getOpcode() == X86ISD::VBROADCAST_LOAD) &&
42498         (VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits()) == 0 &&
42499         (VT.getSizeInBits() % BCVT.getSizeInBits()) == 0) {
42500       MVT NewVT =
42501           MVT::getVectorVT(BCVT.getSimpleVT().getScalarType(),
42502                            VT.getSizeInBits() / BCVT.getScalarSizeInBits());
42503       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
42504     }
42505 
42506     // Reduce broadcast source vector to lowest 128-bits.
42507     if (SrcVT.getSizeInBits() > 128)
42508       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
42509                          extract128BitVector(Src, 0, DAG, DL));
42510 
42511     // broadcast(scalar_to_vector(x)) -> broadcast(x).
42512     if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR)
42513       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
42514 
42515     // broadcast(extract_vector_elt(x, 0)) -> broadcast(x).
42516     if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
42517         isNullConstant(Src.getOperand(1)) &&
42518         DAG.getTargetLoweringInfo().isTypeLegal(
42519             Src.getOperand(0).getValueType()))
42520       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
42521 
42522     // Share broadcast with the longest vector and extract low subvector (free).
42523     // Ensure the same SDValue from the SDNode use is being used.
42524     for (SDNode *User : Src->uses())
42525       if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
42526           Src == User->getOperand(0) &&
42527           User->getValueSizeInBits(0).getFixedValue() >
42528               VT.getFixedSizeInBits()) {
42529         return extractSubVector(SDValue(User, 0), 0, DAG, DL,
42530                                 VT.getSizeInBits());
42531       }
42532 
42533     // vbroadcast(scalarload X) -> vbroadcast_load X
42534     // For float loads, extract other uses of the scalar from the broadcast.
42535     if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
42536         ISD::isNormalLoad(Src.getNode())) {
42537       LoadSDNode *LN = cast<LoadSDNode>(Src);
42538       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
42539       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
42540       SDValue BcastLd =
42541           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
42542                                   LN->getMemoryVT(), LN->getMemOperand());
42543       // If the load value is used only by N, replace it via CombineTo N.
42544       bool NoReplaceExtract = Src.hasOneUse();
42545       DCI.CombineTo(N.getNode(), BcastLd);
42546       if (NoReplaceExtract) {
42547         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
42548         DCI.recursivelyDeleteUnusedNodes(LN);
42549       } else {
42550         SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
42551                                   DAG.getIntPtrConstant(0, DL));
42552         DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
42553       }
42554       return N; // Return N so it doesn't get rechecked!
42555     }
42556 
42557     // Due to isTypeDesirableForOp, we won't always shrink a load truncated to
42558     // i16. So shrink it ourselves if we can make a broadcast_load.
42559     if (SrcVT == MVT::i16 && Src.getOpcode() == ISD::TRUNCATE &&
42560         Src.hasOneUse() && Src.getOperand(0).hasOneUse()) {
42561       assert(Subtarget.hasAVX2() && "Expected AVX2");
42562       SDValue TruncIn = Src.getOperand(0);
42563 
42564       // If this is a truncate of a non extending load we can just narrow it to
42565       // use a broadcast_load.
42566       if (ISD::isNormalLoad(TruncIn.getNode())) {
42567         LoadSDNode *LN = cast<LoadSDNode>(TruncIn);
42568         // Unless its volatile or atomic.
42569         if (LN->isSimple()) {
42570           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
42571           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
42572           SDValue BcastLd = DAG.getMemIntrinsicNode(
42573               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
42574               LN->getPointerInfo(), LN->getOriginalAlign(),
42575               LN->getMemOperand()->getFlags());
42576           DCI.CombineTo(N.getNode(), BcastLd);
42577           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
42578           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
42579           return N; // Return N so it doesn't get rechecked!
42580         }
42581       }
42582 
42583       // If this is a truncate of an i16 extload, we can directly replace it.
42584       if (ISD::isUNINDEXEDLoad(Src.getOperand(0).getNode()) &&
42585           ISD::isEXTLoad(Src.getOperand(0).getNode())) {
42586         LoadSDNode *LN = cast<LoadSDNode>(Src.getOperand(0));
42587         if (LN->getMemoryVT().getSizeInBits() == 16) {
42588           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
42589           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
42590           SDValue BcastLd =
42591               DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
42592                                       LN->getMemoryVT(), LN->getMemOperand());
42593           DCI.CombineTo(N.getNode(), BcastLd);
42594           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
42595           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
42596           return N; // Return N so it doesn't get rechecked!
42597         }
42598       }
42599 
42600       // If this is a truncate of load that has been shifted right, we can
42601       // offset the pointer and use a narrower load.
42602       if (TruncIn.getOpcode() == ISD::SRL &&
42603           TruncIn.getOperand(0).hasOneUse() &&
42604           isa<ConstantSDNode>(TruncIn.getOperand(1)) &&
42605           ISD::isNormalLoad(TruncIn.getOperand(0).getNode())) {
42606         LoadSDNode *LN = cast<LoadSDNode>(TruncIn.getOperand(0));
42607         unsigned ShiftAmt = TruncIn.getConstantOperandVal(1);
42608         // Make sure the shift amount and the load size are divisible by 16.
42609         // Don't do this if the load is volatile or atomic.
42610         if (ShiftAmt % 16 == 0 && TruncIn.getValueSizeInBits() % 16 == 0 &&
42611             LN->isSimple()) {
42612           unsigned Offset = ShiftAmt / 8;
42613           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
42614           SDValue Ptr = DAG.getMemBasePlusOffset(LN->getBasePtr(),
42615                                                  TypeSize::Fixed(Offset), DL);
42616           SDValue Ops[] = { LN->getChain(), Ptr };
42617           SDValue BcastLd = DAG.getMemIntrinsicNode(
42618               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
42619               LN->getPointerInfo().getWithOffset(Offset),
42620               LN->getOriginalAlign(),
42621               LN->getMemOperand()->getFlags());
42622           DCI.CombineTo(N.getNode(), BcastLd);
42623           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
42624           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
42625           return N; // Return N so it doesn't get rechecked!
42626         }
42627       }
42628     }
42629 
42630     // vbroadcast(vzload X) -> vbroadcast_load X
42631     if (Src.getOpcode() == X86ISD::VZEXT_LOAD && Src.hasOneUse()) {
42632       MemSDNode *LN = cast<MemIntrinsicSDNode>(Src);
42633       if (LN->getMemoryVT().getSizeInBits() == VT.getScalarSizeInBits()) {
42634         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
42635         SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
42636         SDValue BcastLd =
42637             DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
42638                                     LN->getMemoryVT(), LN->getMemOperand());
42639         DCI.CombineTo(N.getNode(), BcastLd);
42640         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
42641         DCI.recursivelyDeleteUnusedNodes(LN);
42642         return N; // Return N so it doesn't get rechecked!
42643       }
42644     }
42645 
42646     // vbroadcast(vector load X) -> vbroadcast_load
42647     if ((SrcVT == MVT::v2f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v2i64 ||
42648          SrcVT == MVT::v4i32) &&
42649         Src.hasOneUse() && ISD::isNormalLoad(Src.getNode())) {
42650       LoadSDNode *LN = cast<LoadSDNode>(Src);
42651       // Unless the load is volatile or atomic.
42652       if (LN->isSimple()) {
42653         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
42654         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
42655         SDValue BcastLd = DAG.getMemIntrinsicNode(
42656             X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SrcVT.getScalarType(),
42657             LN->getPointerInfo(), LN->getOriginalAlign(),
42658             LN->getMemOperand()->getFlags());
42659         DCI.CombineTo(N.getNode(), BcastLd);
42660         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
42661         DCI.recursivelyDeleteUnusedNodes(LN);
42662         return N; // Return N so it doesn't get rechecked!
42663       }
42664     }
42665 
42666     return SDValue();
42667   }
42668   case X86ISD::VZEXT_MOVL: {
42669     SDValue N0 = N.getOperand(0);
42670 
42671     // If this a vzmovl of a full vector load, replace it with a vzload, unless
42672     // the load is volatile.
42673     if (N0.hasOneUse() && ISD::isNormalLoad(N0.getNode())) {
42674       auto *LN = cast<LoadSDNode>(N0);
42675       if (SDValue VZLoad =
42676               narrowLoadToVZLoad(LN, VT.getVectorElementType(), VT, DAG)) {
42677         DCI.CombineTo(N.getNode(), VZLoad);
42678         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
42679         DCI.recursivelyDeleteUnusedNodes(LN);
42680         return N;
42681       }
42682     }
42683 
42684     // If this a VZEXT_MOVL of a VBROADCAST_LOAD, we don't need the broadcast
42685     // and can just use a VZEXT_LOAD.
42686     // FIXME: Is there some way to do this with SimplifyDemandedVectorElts?
42687     if (N0.hasOneUse() && N0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
42688       auto *LN = cast<MemSDNode>(N0);
42689       if (VT.getScalarSizeInBits() == LN->getMemoryVT().getSizeInBits()) {
42690         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
42691         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
42692         SDValue VZLoad =
42693             DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
42694                                     LN->getMemoryVT(), LN->getMemOperand());
42695         DCI.CombineTo(N.getNode(), VZLoad);
42696         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
42697         DCI.recursivelyDeleteUnusedNodes(LN);
42698         return N;
42699       }
42700     }
42701 
42702     // Turn (v2i64 (vzext_movl (scalar_to_vector (i64 X)))) into
42703     // (v2i64 (bitcast (v4i32 (vzext_movl (scalar_to_vector (i32 (trunc X)))))))
42704     // if the upper bits of the i64 are zero.
42705     if (N0.hasOneUse() && N0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
42706         N0.getOperand(0).hasOneUse() &&
42707         N0.getOperand(0).getValueType() == MVT::i64) {
42708       SDValue In = N0.getOperand(0);
42709       APInt Mask = APInt::getHighBitsSet(64, 32);
42710       if (DAG.MaskedValueIsZero(In, Mask)) {
42711         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, In);
42712         MVT VecVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
42713         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Trunc);
42714         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, SclVec);
42715         return DAG.getBitcast(VT, Movl);
42716       }
42717     }
42718 
42719     // Load a scalar integer constant directly to XMM instead of transferring an
42720     // immediate value from GPR.
42721     // vzext_movl (scalar_to_vector C) --> load [C,0...]
42722     if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR) {
42723       if (auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
42724         // Create a vector constant - scalar constant followed by zeros.
42725         EVT ScalarVT = N0.getOperand(0).getValueType();
42726         Type *ScalarTy = ScalarVT.getTypeForEVT(*DAG.getContext());
42727         unsigned NumElts = VT.getVectorNumElements();
42728         Constant *Zero = ConstantInt::getNullValue(ScalarTy);
42729         SmallVector<Constant *, 32> ConstantVec(NumElts, Zero);
42730         ConstantVec[0] = const_cast<ConstantInt *>(C->getConstantIntValue());
42731 
42732         // Load the vector constant from constant pool.
42733         MVT PVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
42734         SDValue CP = DAG.getConstantPool(ConstantVector::get(ConstantVec), PVT);
42735         MachinePointerInfo MPI =
42736             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
42737         Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
42738         return DAG.getLoad(VT, DL, DAG.getEntryNode(), CP, MPI, Alignment,
42739                            MachineMemOperand::MOLoad);
42740       }
42741     }
42742 
42743     // Pull subvector inserts into undef through VZEXT_MOVL by making it an
42744     // insert into a zero vector. This helps get VZEXT_MOVL closer to
42745     // scalar_to_vectors where 256/512 are canonicalized to an insert and a
42746     // 128-bit scalar_to_vector. This reduces the number of isel patterns.
42747     if (!DCI.isBeforeLegalizeOps() && N0.hasOneUse()) {
42748       SDValue V = peekThroughOneUseBitcasts(N0);
42749 
42750       if (V.getOpcode() == ISD::INSERT_SUBVECTOR && V.getOperand(0).isUndef() &&
42751           isNullConstant(V.getOperand(2))) {
42752         SDValue In = V.getOperand(1);
42753         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
42754                                      In.getValueSizeInBits() /
42755                                          VT.getScalarSizeInBits());
42756         In = DAG.getBitcast(SubVT, In);
42757         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, SubVT, In);
42758         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
42759                            getZeroVector(VT, Subtarget, DAG, DL), Movl,
42760                            V.getOperand(2));
42761       }
42762     }
42763 
42764     return SDValue();
42765   }
42766   case X86ISD::BLENDI: {
42767     SDValue N0 = N.getOperand(0);
42768     SDValue N1 = N.getOperand(1);
42769 
42770     // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
42771     // TODO: Handle MVT::v16i16 repeated blend mask.
42772     if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
42773         N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
42774       MVT SrcVT = N0.getOperand(0).getSimpleValueType();
42775       if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
42776           SrcVT.getScalarSizeInBits() >= 32) {
42777         unsigned BlendMask = N.getConstantOperandVal(2);
42778         unsigned Size = VT.getVectorNumElements();
42779         unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
42780         BlendMask = scaleVectorShuffleBlendMask(BlendMask, Size, Scale);
42781         return DAG.getBitcast(
42782             VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
42783                             N1.getOperand(0),
42784                             DAG.getTargetConstant(BlendMask, DL, MVT::i8)));
42785       }
42786     }
42787     return SDValue();
42788   }
42789   case X86ISD::SHUFP: {
42790     // Fold shufps(shuffle(x),shuffle(y)) -> shufps(x,y).
42791     // This is a more relaxed shuffle combiner that can ignore oneuse limits.
42792     // TODO: Support types other than v4f32.
42793     if (VT == MVT::v4f32) {
42794       bool Updated = false;
42795       SmallVector<int> Mask;
42796       SmallVector<SDValue> Ops;
42797       if (getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask) &&
42798           Ops.size() == 2) {
42799         for (int i = 0; i != 2; ++i) {
42800           SmallVector<SDValue> SubOps;
42801           SmallVector<int> SubMask, SubScaledMask;
42802           SDValue Sub = peekThroughBitcasts(Ops[i]);
42803           // TODO: Scaling might be easier if we specify the demanded elts.
42804           if (getTargetShuffleInputs(Sub, SubOps, SubMask, DAG, 0, false) &&
42805               scaleShuffleElements(SubMask, 4, SubScaledMask) &&
42806               SubOps.size() == 1 && isUndefOrInRange(SubScaledMask, 0, 4)) {
42807             int Ofs = i * 2;
42808             Mask[Ofs + 0] = SubScaledMask[Mask[Ofs + 0] % 4] + (i * 4);
42809             Mask[Ofs + 1] = SubScaledMask[Mask[Ofs + 1] % 4] + (i * 4);
42810             Ops[i] = DAG.getBitcast(VT, SubOps[0]);
42811             Updated = true;
42812           }
42813         }
42814       }
42815       if (Updated) {
42816         for (int &M : Mask)
42817           M %= 4;
42818         Ops.push_back(getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
42819         return DAG.getNode(X86ISD::SHUFP, DL, VT, Ops);
42820       }
42821     }
42822     return SDValue();
42823   }
42824   case X86ISD::VPERMI: {
42825     // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
42826     // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
42827     SDValue N0 = N.getOperand(0);
42828     SDValue N1 = N.getOperand(1);
42829     unsigned EltSizeInBits = VT.getScalarSizeInBits();
42830     if (N0.getOpcode() == ISD::BITCAST &&
42831         N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
42832       SDValue Src = N0.getOperand(0);
42833       EVT SrcVT = Src.getValueType();
42834       SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
42835       return DAG.getBitcast(VT, Res);
42836     }
42837     return SDValue();
42838   }
42839   case X86ISD::VPERM2X128: {
42840     // Fold vperm2x128(bitcast(x),bitcast(y),c) -> bitcast(vperm2x128(x,y,c)).
42841     SDValue LHS = N->getOperand(0);
42842     SDValue RHS = N->getOperand(1);
42843     if (LHS.getOpcode() == ISD::BITCAST &&
42844         (RHS.getOpcode() == ISD::BITCAST || RHS.isUndef())) {
42845       EVT SrcVT = LHS.getOperand(0).getValueType();
42846       if (RHS.isUndef() || SrcVT == RHS.getOperand(0).getValueType()) {
42847         return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT,
42848                                               DAG.getBitcast(SrcVT, LHS),
42849                                               DAG.getBitcast(SrcVT, RHS),
42850                                               N->getOperand(2)));
42851       }
42852     }
42853 
42854     // Fold vperm2x128(op(),op()) -> op(vperm2x128(),vperm2x128()).
42855     if (SDValue Res = canonicalizeLaneShuffleWithRepeatedOps(N, DAG, DL))
42856       return Res;
42857 
42858     // Fold vperm2x128 subvector shuffle with an inner concat pattern.
42859     // vperm2x128(concat(X,Y),concat(Z,W)) --> concat X,Y etc.
42860     auto FindSubVector128 = [&](unsigned Idx) {
42861       if (Idx > 3)
42862         return SDValue();
42863       SDValue Src = peekThroughBitcasts(N.getOperand(Idx < 2 ? 0 : 1));
42864       SmallVector<SDValue> SubOps;
42865       if (collectConcatOps(Src.getNode(), SubOps, DAG) && SubOps.size() == 2)
42866         return SubOps[Idx & 1];
42867       unsigned NumElts = Src.getValueType().getVectorNumElements();
42868       if ((Idx & 1) == 1 && Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
42869           Src.getOperand(1).getValueSizeInBits() == 128 &&
42870           Src.getConstantOperandAPInt(2) == (NumElts / 2)) {
42871         return Src.getOperand(1);
42872       }
42873       return SDValue();
42874     };
42875     unsigned Imm = N.getConstantOperandVal(2);
42876     if (SDValue SubLo = FindSubVector128(Imm & 0x0F)) {
42877       if (SDValue SubHi = FindSubVector128((Imm & 0xF0) >> 4)) {
42878         MVT SubVT = VT.getHalfNumVectorElementsVT();
42879         SubLo = DAG.getBitcast(SubVT, SubLo);
42880         SubHi = DAG.getBitcast(SubVT, SubHi);
42881         return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SubLo, SubHi);
42882       }
42883     }
42884     return SDValue();
42885   }
42886   case X86ISD::PSHUFD:
42887   case X86ISD::PSHUFLW:
42888   case X86ISD::PSHUFHW: {
42889     SDValue N0 = N.getOperand(0);
42890     SDValue N1 = N.getOperand(1);
42891     if (N0->hasOneUse()) {
42892       SDValue V = peekThroughOneUseBitcasts(N0);
42893       switch (V.getOpcode()) {
42894       case X86ISD::VSHL:
42895       case X86ISD::VSRL:
42896       case X86ISD::VSRA:
42897       case X86ISD::VSHLI:
42898       case X86ISD::VSRLI:
42899       case X86ISD::VSRAI:
42900       case X86ISD::VROTLI:
42901       case X86ISD::VROTRI: {
42902         MVT InnerVT = V.getSimpleValueType();
42903         if (InnerVT.getScalarSizeInBits() <= VT.getScalarSizeInBits()) {
42904           SDValue Res = DAG.getNode(Opcode, DL, VT,
42905                                     DAG.getBitcast(VT, V.getOperand(0)), N1);
42906           Res = DAG.getBitcast(InnerVT, Res);
42907           Res = DAG.getNode(V.getOpcode(), DL, InnerVT, Res, V.getOperand(1));
42908           return DAG.getBitcast(VT, Res);
42909         }
42910         break;
42911       }
42912       }
42913     }
42914 
42915     Mask = getPSHUFShuffleMask(N);
42916     assert(Mask.size() == 4);
42917     break;
42918   }
42919   case X86ISD::MOVSD:
42920   case X86ISD::MOVSH:
42921   case X86ISD::MOVSS: {
42922     SDValue N0 = N.getOperand(0);
42923     SDValue N1 = N.getOperand(1);
42924 
42925     // Canonicalize scalar FPOps:
42926     // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
42927     // If commutable, allow OP(N1[0], N0[0]).
42928     unsigned Opcode1 = N1.getOpcode();
42929     if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
42930         Opcode1 == ISD::FDIV) {
42931       SDValue N10 = N1.getOperand(0);
42932       SDValue N11 = N1.getOperand(1);
42933       if (N10 == N0 ||
42934           (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
42935         if (N10 != N0)
42936           std::swap(N10, N11);
42937         MVT SVT = VT.getVectorElementType();
42938         SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
42939         N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
42940         N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
42941         SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
42942         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
42943         return DAG.getNode(Opcode, DL, VT, N0, SclVec);
42944       }
42945     }
42946 
42947     return SDValue();
42948   }
42949   case X86ISD::INSERTPS: {
42950     assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
42951     SDValue Op0 = N.getOperand(0);
42952     SDValue Op1 = N.getOperand(1);
42953     unsigned InsertPSMask = N.getConstantOperandVal(2);
42954     unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
42955     unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
42956     unsigned ZeroMask = InsertPSMask & 0xF;
42957 
42958     // If we zero out all elements from Op0 then we don't need to reference it.
42959     if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
42960       return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
42961                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42962 
42963     // If we zero out the element from Op1 then we don't need to reference it.
42964     if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
42965       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
42966                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42967 
42968     // Attempt to merge insertps Op1 with an inner target shuffle node.
42969     SmallVector<int, 8> TargetMask1;
42970     SmallVector<SDValue, 2> Ops1;
42971     APInt KnownUndef1, KnownZero1;
42972     if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
42973                                      KnownZero1)) {
42974       if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
42975         // Zero/UNDEF insertion - zero out element and remove dependency.
42976         InsertPSMask |= (1u << DstIdx);
42977         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
42978                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42979       }
42980       // Update insertps mask srcidx and reference the source input directly.
42981       int M = TargetMask1[SrcIdx];
42982       assert(0 <= M && M < 8 && "Shuffle index out of range");
42983       InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
42984       Op1 = Ops1[M < 4 ? 0 : 1];
42985       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
42986                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42987     }
42988 
42989     // Attempt to merge insertps Op0 with an inner target shuffle node.
42990     SmallVector<int, 8> TargetMask0;
42991     SmallVector<SDValue, 2> Ops0;
42992     APInt KnownUndef0, KnownZero0;
42993     if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
42994                                      KnownZero0)) {
42995       bool Updated = false;
42996       bool UseInput00 = false;
42997       bool UseInput01 = false;
42998       for (int i = 0; i != 4; ++i) {
42999         if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
43000           // No change if element is already zero or the inserted element.
43001           continue;
43002         }
43003 
43004         if (KnownUndef0[i] || KnownZero0[i]) {
43005           // If the target mask is undef/zero then we must zero the element.
43006           InsertPSMask |= (1u << i);
43007           Updated = true;
43008           continue;
43009         }
43010 
43011         // The input vector element must be inline.
43012         int M = TargetMask0[i];
43013         if (M != i && M != (i + 4))
43014           return SDValue();
43015 
43016         // Determine which inputs of the target shuffle we're using.
43017         UseInput00 |= (0 <= M && M < 4);
43018         UseInput01 |= (4 <= M);
43019       }
43020 
43021       // If we're not using both inputs of the target shuffle then use the
43022       // referenced input directly.
43023       if (UseInput00 && !UseInput01) {
43024         Updated = true;
43025         Op0 = Ops0[0];
43026       } else if (!UseInput00 && UseInput01) {
43027         Updated = true;
43028         Op0 = Ops0[1];
43029       }
43030 
43031       if (Updated)
43032         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
43033                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
43034     }
43035 
43036     // If we're inserting an element from a vbroadcast load, fold the
43037     // load into the X86insertps instruction. We need to convert the scalar
43038     // load to a vector and clear the source lane of the INSERTPS control.
43039     if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
43040       auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
43041       if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
43042         SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
43043                                    MemIntr->getBasePtr(),
43044                                    MemIntr->getMemOperand());
43045         SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
43046                            DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
43047                                        Load),
43048                            DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
43049         DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
43050         return Insert;
43051       }
43052     }
43053 
43054     return SDValue();
43055   }
43056   default:
43057     return SDValue();
43058   }
43059 
43060   // Nuke no-op shuffles that show up after combining.
43061   if (isNoopShuffleMask(Mask))
43062     return N.getOperand(0);
43063 
43064   // Look for simplifications involving one or two shuffle instructions.
43065   SDValue V = N.getOperand(0);
43066   switch (N.getOpcode()) {
43067   default:
43068     break;
43069   case X86ISD::PSHUFLW:
43070   case X86ISD::PSHUFHW:
43071     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
43072 
43073     // See if this reduces to a PSHUFD which is no more expensive and can
43074     // combine with more operations. Note that it has to at least flip the
43075     // dwords as otherwise it would have been removed as a no-op.
43076     if (ArrayRef(Mask).equals({2, 3, 0, 1})) {
43077       int DMask[] = {0, 1, 2, 3};
43078       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
43079       DMask[DOffset + 0] = DOffset + 1;
43080       DMask[DOffset + 1] = DOffset + 0;
43081       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
43082       V = DAG.getBitcast(DVT, V);
43083       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
43084                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
43085       return DAG.getBitcast(VT, V);
43086     }
43087 
43088     // Look for shuffle patterns which can be implemented as a single unpack.
43089     // FIXME: This doesn't handle the location of the PSHUFD generically, and
43090     // only works when we have a PSHUFD followed by two half-shuffles.
43091     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
43092         (V.getOpcode() == X86ISD::PSHUFLW ||
43093          V.getOpcode() == X86ISD::PSHUFHW) &&
43094         V.getOpcode() != N.getOpcode() &&
43095         V.hasOneUse() && V.getOperand(0).hasOneUse()) {
43096       SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
43097       if (D.getOpcode() == X86ISD::PSHUFD) {
43098         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
43099         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
43100         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
43101         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
43102         int WordMask[8];
43103         for (int i = 0; i < 4; ++i) {
43104           WordMask[i + NOffset] = Mask[i] + NOffset;
43105           WordMask[i + VOffset] = VMask[i] + VOffset;
43106         }
43107         // Map the word mask through the DWord mask.
43108         int MappedMask[8];
43109         for (int i = 0; i < 8; ++i)
43110           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
43111         if (ArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
43112             ArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
43113           // We can replace all three shuffles with an unpack.
43114           V = DAG.getBitcast(VT, D.getOperand(0));
43115           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
43116                                                 : X86ISD::UNPCKH,
43117                              DL, VT, V, V);
43118         }
43119       }
43120     }
43121 
43122     break;
43123 
43124   case X86ISD::PSHUFD:
43125     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
43126       return NewN;
43127 
43128     break;
43129   }
43130 
43131   return SDValue();
43132 }
43133 
43134 /// Checks if the shuffle mask takes subsequent elements
43135 /// alternately from two vectors.
43136 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
43137 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
43138 
43139   int ParitySrc[2] = {-1, -1};
43140   unsigned Size = Mask.size();
43141   for (unsigned i = 0; i != Size; ++i) {
43142     int M = Mask[i];
43143     if (M < 0)
43144       continue;
43145 
43146     // Make sure we are using the matching element from the input.
43147     if ((M % Size) != i)
43148       return false;
43149 
43150     // Make sure we use the same input for all elements of the same parity.
43151     int Src = M / Size;
43152     if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
43153       return false;
43154     ParitySrc[i % 2] = Src;
43155   }
43156 
43157   // Make sure each input is used.
43158   if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
43159     return false;
43160 
43161   Op0Even = ParitySrc[0] == 0;
43162   return true;
43163 }
43164 
43165 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
43166 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
43167 /// are written to the parameters \p Opnd0 and \p Opnd1.
43168 ///
43169 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
43170 /// so it is easier to generically match. We also insert dummy vector shuffle
43171 /// nodes for the operands which explicitly discard the lanes which are unused
43172 /// by this operation to try to flow through the rest of the combiner
43173 /// the fact that they're unused.
43174 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
43175                              SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
43176                              bool &IsSubAdd) {
43177 
43178   EVT VT = N->getValueType(0);
43179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43180   if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
43181       !VT.getSimpleVT().isFloatingPoint())
43182     return false;
43183 
43184   // We only handle target-independent shuffles.
43185   // FIXME: It would be easy and harmless to use the target shuffle mask
43186   // extraction tool to support more.
43187   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
43188     return false;
43189 
43190   SDValue V1 = N->getOperand(0);
43191   SDValue V2 = N->getOperand(1);
43192 
43193   // Make sure we have an FADD and an FSUB.
43194   if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
43195       (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
43196       V1.getOpcode() == V2.getOpcode())
43197     return false;
43198 
43199   // If there are other uses of these operations we can't fold them.
43200   if (!V1->hasOneUse() || !V2->hasOneUse())
43201     return false;
43202 
43203   // Ensure that both operations have the same operands. Note that we can
43204   // commute the FADD operands.
43205   SDValue LHS, RHS;
43206   if (V1.getOpcode() == ISD::FSUB) {
43207     LHS = V1->getOperand(0); RHS = V1->getOperand(1);
43208     if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
43209         (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
43210       return false;
43211   } else {
43212     assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
43213     LHS = V2->getOperand(0); RHS = V2->getOperand(1);
43214     if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
43215         (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
43216       return false;
43217   }
43218 
43219   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
43220   bool Op0Even;
43221   if (!isAddSubOrSubAddMask(Mask, Op0Even))
43222     return false;
43223 
43224   // It's a subadd if the vector in the even parity is an FADD.
43225   IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
43226                      : V2->getOpcode() == ISD::FADD;
43227 
43228   Opnd0 = LHS;
43229   Opnd1 = RHS;
43230   return true;
43231 }
43232 
43233 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
43234 static SDValue combineShuffleToFMAddSub(SDNode *N,
43235                                         const X86Subtarget &Subtarget,
43236                                         SelectionDAG &DAG) {
43237   // We only handle target-independent shuffles.
43238   // FIXME: It would be easy and harmless to use the target shuffle mask
43239   // extraction tool to support more.
43240   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
43241     return SDValue();
43242 
43243   MVT VT = N->getSimpleValueType(0);
43244   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43245   if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
43246     return SDValue();
43247 
43248   // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
43249   SDValue Op0 = N->getOperand(0);
43250   SDValue Op1 = N->getOperand(1);
43251   SDValue FMAdd = Op0, FMSub = Op1;
43252   if (FMSub.getOpcode() != X86ISD::FMSUB)
43253     std::swap(FMAdd, FMSub);
43254 
43255   if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
43256       FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
43257       FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
43258       FMAdd.getOperand(2) != FMSub.getOperand(2))
43259     return SDValue();
43260 
43261   // Check for correct shuffle mask.
43262   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
43263   bool Op0Even;
43264   if (!isAddSubOrSubAddMask(Mask, Op0Even))
43265     return SDValue();
43266 
43267   // FMAddSub takes zeroth operand from FMSub node.
43268   SDLoc DL(N);
43269   bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
43270   unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
43271   return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
43272                      FMAdd.getOperand(2));
43273 }
43274 
43275 /// Try to combine a shuffle into a target-specific add-sub or
43276 /// mul-add-sub node.
43277 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
43278                                                 const X86Subtarget &Subtarget,
43279                                                 SelectionDAG &DAG) {
43280   if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
43281     return V;
43282 
43283   SDValue Opnd0, Opnd1;
43284   bool IsSubAdd;
43285   if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
43286     return SDValue();
43287 
43288   MVT VT = N->getSimpleValueType(0);
43289   SDLoc DL(N);
43290 
43291   // Try to generate X86ISD::FMADDSUB node here.
43292   SDValue Opnd2;
43293   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
43294     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
43295     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
43296   }
43297 
43298   if (IsSubAdd)
43299     return SDValue();
43300 
43301   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
43302   // the ADDSUB idiom has been successfully recognized. There are no known
43303   // X86 targets with 512-bit ADDSUB instructions!
43304   if (VT.is512BitVector())
43305     return SDValue();
43306 
43307   // Do not generate X86ISD::ADDSUB node for FP16's vector types even though
43308   // the ADDSUB idiom has been successfully recognized. There are no known
43309   // X86 targets with FP16 ADDSUB instructions!
43310   if (VT.getVectorElementType() == MVT::f16)
43311     return SDValue();
43312 
43313   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
43314 }
43315 
43316 // We are looking for a shuffle where both sources are concatenated with undef
43317 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
43318 // if we can express this as a single-source shuffle, that's preferable.
43319 static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
43320                                            const X86Subtarget &Subtarget) {
43321   if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
43322     return SDValue();
43323 
43324   EVT VT = N->getValueType(0);
43325 
43326   // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
43327   if (!VT.is128BitVector() && !VT.is256BitVector())
43328     return SDValue();
43329 
43330   if (VT.getVectorElementType() != MVT::i32 &&
43331       VT.getVectorElementType() != MVT::i64 &&
43332       VT.getVectorElementType() != MVT::f32 &&
43333       VT.getVectorElementType() != MVT::f64)
43334     return SDValue();
43335 
43336   SDValue N0 = N->getOperand(0);
43337   SDValue N1 = N->getOperand(1);
43338 
43339   // Check that both sources are concats with undef.
43340   if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
43341       N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
43342       N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
43343       !N1.getOperand(1).isUndef())
43344     return SDValue();
43345 
43346   // Construct the new shuffle mask. Elements from the first source retain their
43347   // index, but elements from the second source no longer need to skip an undef.
43348   SmallVector<int, 8> Mask;
43349   int NumElts = VT.getVectorNumElements();
43350 
43351   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
43352   for (int Elt : SVOp->getMask())
43353     Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
43354 
43355   SDLoc DL(N);
43356   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
43357                                N1.getOperand(0));
43358   return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
43359 }
43360 
43361 /// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
43362 /// low half of each source vector and does not set any high half elements in
43363 /// the destination vector, narrow the shuffle to half its original size.
43364 static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
43365   EVT VT = Shuf->getValueType(0);
43366   if (!DAG.getTargetLoweringInfo().isTypeLegal(Shuf->getValueType(0)))
43367     return SDValue();
43368   if (!VT.is256BitVector() && !VT.is512BitVector())
43369     return SDValue();
43370 
43371   // See if we can ignore all of the high elements of the shuffle.
43372   ArrayRef<int> Mask = Shuf->getMask();
43373   if (!isUndefUpperHalf(Mask))
43374     return SDValue();
43375 
43376   // Check if the shuffle mask accesses only the low half of each input vector
43377   // (half-index output is 0 or 2).
43378   int HalfIdx1, HalfIdx2;
43379   SmallVector<int, 8> HalfMask(Mask.size() / 2);
43380   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
43381       (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
43382     return SDValue();
43383 
43384   // Create a half-width shuffle to replace the unnecessarily wide shuffle.
43385   // The trick is knowing that all of the insert/extract are actually free
43386   // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
43387   // of narrow inputs into a narrow output, and that is always cheaper than
43388   // the wide shuffle that we started with.
43389   return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
43390                                Shuf->getOperand(1), HalfMask, HalfIdx1,
43391                                HalfIdx2, false, DAG, /*UseConcat*/ true);
43392 }
43393 
43394 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
43395                               TargetLowering::DAGCombinerInfo &DCI,
43396                               const X86Subtarget &Subtarget) {
43397   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
43398     if (SDValue V = narrowShuffle(Shuf, DAG))
43399       return V;
43400 
43401   // If we have legalized the vector types, look for blends of FADD and FSUB
43402   // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
43403   SDLoc dl(N);
43404   EVT VT = N->getValueType(0);
43405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43406   if (TLI.isTypeLegal(VT))
43407     if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
43408       return AddSub;
43409 
43410   // Attempt to combine into a vector load/broadcast.
43411   if (SDValue LD = combineToConsecutiveLoads(
43412           VT, SDValue(N, 0), dl, DAG, Subtarget, /*IsAfterLegalize*/ true))
43413     return LD;
43414 
43415   // For AVX2, we sometimes want to combine
43416   // (vector_shuffle <mask> (concat_vectors t1, undef)
43417   //                        (concat_vectors t2, undef))
43418   // Into:
43419   // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
43420   // Since the latter can be efficiently lowered with VPERMD/VPERMQ
43421   if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
43422     return ShufConcat;
43423 
43424   if (isTargetShuffle(N->getOpcode())) {
43425     SDValue Op(N, 0);
43426     if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
43427       return Shuffle;
43428 
43429     // Try recursively combining arbitrary sequences of x86 shuffle
43430     // instructions into higher-order shuffles. We do this after combining
43431     // specific PSHUF instruction sequences into their minimal form so that we
43432     // can evaluate how many specialized shuffle instructions are involved in
43433     // a particular chain.
43434     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
43435       return Res;
43436 
43437     // Simplify source operands based on shuffle mask.
43438     // TODO - merge this into combineX86ShufflesRecursively.
43439     APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
43440     if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, DCI))
43441       return SDValue(N, 0);
43442 
43443     // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
43444     // Perform this after other shuffle combines to allow inner shuffles to be
43445     // combined away first.
43446     if (SDValue BinOp = canonicalizeShuffleWithBinOps(Op, DAG, dl))
43447       return BinOp;
43448   }
43449 
43450   return SDValue();
43451 }
43452 
43453 // Simplify variable target shuffle masks based on the demanded elements.
43454 // TODO: Handle DemandedBits in mask indices as well?
43455 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetShuffle(
43456     SDValue Op, const APInt &DemandedElts, unsigned MaskIndex,
43457     TargetLowering::TargetLoweringOpt &TLO, unsigned Depth) const {
43458   // If we're demanding all elements don't bother trying to simplify the mask.
43459   unsigned NumElts = DemandedElts.getBitWidth();
43460   if (DemandedElts.isAllOnes())
43461     return false;
43462 
43463   SDValue Mask = Op.getOperand(MaskIndex);
43464   if (!Mask.hasOneUse())
43465     return false;
43466 
43467   // Attempt to generically simplify the variable shuffle mask.
43468   APInt MaskUndef, MaskZero;
43469   if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
43470                                  Depth + 1))
43471     return true;
43472 
43473   // Attempt to extract+simplify a (constant pool load) shuffle mask.
43474   // TODO: Support other types from getTargetShuffleMaskIndices?
43475   SDValue BC = peekThroughOneUseBitcasts(Mask);
43476   EVT BCVT = BC.getValueType();
43477   auto *Load = dyn_cast<LoadSDNode>(BC);
43478   if (!Load)
43479     return false;
43480 
43481   const Constant *C = getTargetConstantFromNode(Load);
43482   if (!C)
43483     return false;
43484 
43485   Type *CTy = C->getType();
43486   if (!CTy->isVectorTy() ||
43487       CTy->getPrimitiveSizeInBits() != Mask.getValueSizeInBits())
43488     return false;
43489 
43490   // Handle scaling for i64 elements on 32-bit targets.
43491   unsigned NumCstElts = cast<FixedVectorType>(CTy)->getNumElements();
43492   if (NumCstElts != NumElts && NumCstElts != (NumElts * 2))
43493     return false;
43494   unsigned Scale = NumCstElts / NumElts;
43495 
43496   // Simplify mask if we have an undemanded element that is not undef.
43497   bool Simplified = false;
43498   SmallVector<Constant *, 32> ConstVecOps;
43499   for (unsigned i = 0; i != NumCstElts; ++i) {
43500     Constant *Elt = C->getAggregateElement(i);
43501     if (!DemandedElts[i / Scale] && !isa<UndefValue>(Elt)) {
43502       ConstVecOps.push_back(UndefValue::get(Elt->getType()));
43503       Simplified = true;
43504       continue;
43505     }
43506     ConstVecOps.push_back(Elt);
43507   }
43508   if (!Simplified)
43509     return false;
43510 
43511   // Generate new constant pool entry + legalize immediately for the load.
43512   SDLoc DL(Op);
43513   SDValue CV = TLO.DAG.getConstantPool(ConstantVector::get(ConstVecOps), BCVT);
43514   SDValue LegalCV = LowerConstantPool(CV, TLO.DAG);
43515   SDValue NewMask = TLO.DAG.getLoad(
43516       BCVT, DL, TLO.DAG.getEntryNode(), LegalCV,
43517       MachinePointerInfo::getConstantPool(TLO.DAG.getMachineFunction()),
43518       Load->getAlign());
43519   return TLO.CombineTo(Mask, TLO.DAG.getBitcast(Mask.getValueType(), NewMask));
43520 }
43521 
43522 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
43523     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
43524     TargetLoweringOpt &TLO, unsigned Depth) const {
43525   int NumElts = DemandedElts.getBitWidth();
43526   unsigned Opc = Op.getOpcode();
43527   EVT VT = Op.getValueType();
43528 
43529   // Handle special case opcodes.
43530   switch (Opc) {
43531   case X86ISD::PMULDQ:
43532   case X86ISD::PMULUDQ: {
43533     APInt LHSUndef, LHSZero;
43534     APInt RHSUndef, RHSZero;
43535     SDValue LHS = Op.getOperand(0);
43536     SDValue RHS = Op.getOperand(1);
43537     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
43538                                    Depth + 1))
43539       return true;
43540     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
43541                                    Depth + 1))
43542       return true;
43543     // Multiply by zero.
43544     KnownZero = LHSZero | RHSZero;
43545     break;
43546   }
43547   case X86ISD::VPMADDWD: {
43548     APInt LHSUndef, LHSZero;
43549     APInt RHSUndef, RHSZero;
43550     SDValue LHS = Op.getOperand(0);
43551     SDValue RHS = Op.getOperand(1);
43552     APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, 2 * NumElts);
43553 
43554     if (SimplifyDemandedVectorElts(LHS, DemandedSrcElts, LHSUndef, LHSZero, TLO,
43555                                    Depth + 1))
43556       return true;
43557     if (SimplifyDemandedVectorElts(RHS, DemandedSrcElts, RHSUndef, RHSZero, TLO,
43558                                    Depth + 1))
43559       return true;
43560 
43561     // TODO: Multiply by zero.
43562 
43563     // If RHS/LHS elements are known zero then we don't need the LHS/RHS equivalent.
43564     APInt DemandedLHSElts = DemandedSrcElts & ~RHSZero;
43565     if (SimplifyDemandedVectorElts(LHS, DemandedLHSElts, LHSUndef, LHSZero, TLO,
43566                                    Depth + 1))
43567       return true;
43568     APInt DemandedRHSElts = DemandedSrcElts & ~LHSZero;
43569     if (SimplifyDemandedVectorElts(RHS, DemandedRHSElts, RHSUndef, RHSZero, TLO,
43570                                    Depth + 1))
43571       return true;
43572     break;
43573   }
43574   case X86ISD::PSADBW: {
43575     SDValue LHS = Op.getOperand(0);
43576     SDValue RHS = Op.getOperand(1);
43577     assert(VT.getScalarType() == MVT::i64 &&
43578            LHS.getValueType() == RHS.getValueType() &&
43579            LHS.getValueType().getScalarType() == MVT::i8 &&
43580            "Unexpected PSADBW types");
43581 
43582     // Aggressively peek through ops to get at the demanded elts.
43583     if (!DemandedElts.isAllOnes()) {
43584       unsigned NumSrcElts = LHS.getValueType().getVectorNumElements();
43585       APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
43586       SDValue NewLHS = SimplifyMultipleUseDemandedVectorElts(
43587           LHS, DemandedSrcElts, TLO.DAG, Depth + 1);
43588       SDValue NewRHS = SimplifyMultipleUseDemandedVectorElts(
43589           RHS, DemandedSrcElts, TLO.DAG, Depth + 1);
43590       if (NewLHS || NewRHS) {
43591         NewLHS = NewLHS ? NewLHS : LHS;
43592         NewRHS = NewRHS ? NewRHS : RHS;
43593         return TLO.CombineTo(
43594             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
43595       }
43596     }
43597     break;
43598   }
43599   case X86ISD::VSHL:
43600   case X86ISD::VSRL:
43601   case X86ISD::VSRA: {
43602     // We only need the bottom 64-bits of the (128-bit) shift amount.
43603     SDValue Amt = Op.getOperand(1);
43604     MVT AmtVT = Amt.getSimpleValueType();
43605     assert(AmtVT.is128BitVector() && "Unexpected value type");
43606 
43607     // If we reuse the shift amount just for sse shift amounts then we know that
43608     // only the bottom 64-bits are only ever used.
43609     bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
43610       unsigned UseOpc = Use->getOpcode();
43611       return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
43612               UseOpc == X86ISD::VSRA) &&
43613              Use->getOperand(0) != Amt;
43614     });
43615 
43616     APInt AmtUndef, AmtZero;
43617     unsigned NumAmtElts = AmtVT.getVectorNumElements();
43618     APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
43619     if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
43620                                    Depth + 1, AssumeSingleUse))
43621       return true;
43622     [[fallthrough]];
43623   }
43624   case X86ISD::VSHLI:
43625   case X86ISD::VSRLI:
43626   case X86ISD::VSRAI: {
43627     SDValue Src = Op.getOperand(0);
43628     APInt SrcUndef;
43629     if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
43630                                    Depth + 1))
43631       return true;
43632 
43633     // Fold shift(0,x) -> 0
43634     if (DemandedElts.isSubsetOf(KnownZero))
43635       return TLO.CombineTo(
43636           Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
43637 
43638     // Aggressively peek through ops to get at the demanded elts.
43639     if (!DemandedElts.isAllOnes())
43640       if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
43641               Src, DemandedElts, TLO.DAG, Depth + 1))
43642         return TLO.CombineTo(
43643             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc, Op.getOperand(1)));
43644     break;
43645   }
43646   case X86ISD::VPSHA:
43647   case X86ISD::VPSHL:
43648   case X86ISD::VSHLV:
43649   case X86ISD::VSRLV:
43650   case X86ISD::VSRAV: {
43651     APInt LHSUndef, LHSZero;
43652     APInt RHSUndef, RHSZero;
43653     SDValue LHS = Op.getOperand(0);
43654     SDValue RHS = Op.getOperand(1);
43655     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
43656                                    Depth + 1))
43657       return true;
43658 
43659     // Fold shift(0,x) -> 0
43660     if (DemandedElts.isSubsetOf(LHSZero))
43661       return TLO.CombineTo(
43662           Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
43663 
43664     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
43665                                    Depth + 1))
43666       return true;
43667 
43668     KnownZero = LHSZero;
43669     break;
43670   }
43671   case X86ISD::KSHIFTL: {
43672     SDValue Src = Op.getOperand(0);
43673     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
43674     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
43675     unsigned ShiftAmt = Amt->getZExtValue();
43676 
43677     if (ShiftAmt == 0)
43678       return TLO.CombineTo(Op, Src);
43679 
43680     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
43681     // single shift.  We can do this if the bottom bits (which are shifted
43682     // out) are never demanded.
43683     if (Src.getOpcode() == X86ISD::KSHIFTR) {
43684       if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
43685         unsigned C1 = Src.getConstantOperandVal(1);
43686         unsigned NewOpc = X86ISD::KSHIFTL;
43687         int Diff = ShiftAmt - C1;
43688         if (Diff < 0) {
43689           Diff = -Diff;
43690           NewOpc = X86ISD::KSHIFTR;
43691         }
43692 
43693         SDLoc dl(Op);
43694         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
43695         return TLO.CombineTo(
43696             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
43697       }
43698     }
43699 
43700     APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
43701     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
43702                                    Depth + 1))
43703       return true;
43704 
43705     KnownUndef <<= ShiftAmt;
43706     KnownZero <<= ShiftAmt;
43707     KnownZero.setLowBits(ShiftAmt);
43708     break;
43709   }
43710   case X86ISD::KSHIFTR: {
43711     SDValue Src = Op.getOperand(0);
43712     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
43713     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
43714     unsigned ShiftAmt = Amt->getZExtValue();
43715 
43716     if (ShiftAmt == 0)
43717       return TLO.CombineTo(Op, Src);
43718 
43719     // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
43720     // single shift.  We can do this if the top bits (which are shifted
43721     // out) are never demanded.
43722     if (Src.getOpcode() == X86ISD::KSHIFTL) {
43723       if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
43724         unsigned C1 = Src.getConstantOperandVal(1);
43725         unsigned NewOpc = X86ISD::KSHIFTR;
43726         int Diff = ShiftAmt - C1;
43727         if (Diff < 0) {
43728           Diff = -Diff;
43729           NewOpc = X86ISD::KSHIFTL;
43730         }
43731 
43732         SDLoc dl(Op);
43733         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
43734         return TLO.CombineTo(
43735             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
43736       }
43737     }
43738 
43739     APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
43740     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
43741                                    Depth + 1))
43742       return true;
43743 
43744     KnownUndef.lshrInPlace(ShiftAmt);
43745     KnownZero.lshrInPlace(ShiftAmt);
43746     KnownZero.setHighBits(ShiftAmt);
43747     break;
43748   }
43749   case X86ISD::ANDNP: {
43750     // ANDNP = (~LHS & RHS);
43751     SDValue LHS = Op.getOperand(0);
43752     SDValue RHS = Op.getOperand(1);
43753 
43754     auto GetDemandedMasks = [&](SDValue Op, bool Invert = false) {
43755       APInt UndefElts;
43756       SmallVector<APInt> EltBits;
43757       int NumElts = VT.getVectorNumElements();
43758       int EltSizeInBits = VT.getScalarSizeInBits();
43759       APInt OpBits = APInt::getAllOnes(EltSizeInBits);
43760       APInt OpElts = DemandedElts;
43761       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
43762                                         EltBits)) {
43763         OpBits.clearAllBits();
43764         OpElts.clearAllBits();
43765         for (int I = 0; I != NumElts; ++I) {
43766           if (!DemandedElts[I])
43767             continue;
43768           if (UndefElts[I]) {
43769             // We can't assume an undef src element gives an undef dst - the
43770             // other src might be zero.
43771             OpBits.setAllBits();
43772             OpElts.setBit(I);
43773           } else if ((Invert && !EltBits[I].isAllOnes()) ||
43774                      (!Invert && !EltBits[I].isZero())) {
43775             OpBits |= Invert ? ~EltBits[I] : EltBits[I];
43776             OpElts.setBit(I);
43777           }
43778         }
43779       }
43780       return std::make_pair(OpBits, OpElts);
43781     };
43782     APInt BitsLHS, EltsLHS;
43783     APInt BitsRHS, EltsRHS;
43784     std::tie(BitsLHS, EltsLHS) = GetDemandedMasks(RHS);
43785     std::tie(BitsRHS, EltsRHS) = GetDemandedMasks(LHS, true);
43786 
43787     APInt LHSUndef, LHSZero;
43788     APInt RHSUndef, RHSZero;
43789     if (SimplifyDemandedVectorElts(LHS, EltsLHS, LHSUndef, LHSZero, TLO,
43790                                    Depth + 1))
43791       return true;
43792     if (SimplifyDemandedVectorElts(RHS, EltsRHS, RHSUndef, RHSZero, TLO,
43793                                    Depth + 1))
43794       return true;
43795 
43796     if (!DemandedElts.isAllOnes()) {
43797       SDValue NewLHS = SimplifyMultipleUseDemandedBits(LHS, BitsLHS, EltsLHS,
43798                                                        TLO.DAG, Depth + 1);
43799       SDValue NewRHS = SimplifyMultipleUseDemandedBits(RHS, BitsRHS, EltsRHS,
43800                                                        TLO.DAG, Depth + 1);
43801       if (NewLHS || NewRHS) {
43802         NewLHS = NewLHS ? NewLHS : LHS;
43803         NewRHS = NewRHS ? NewRHS : RHS;
43804         return TLO.CombineTo(
43805             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
43806       }
43807     }
43808     break;
43809   }
43810   case X86ISD::CVTSI2P:
43811   case X86ISD::CVTUI2P: {
43812     SDValue Src = Op.getOperand(0);
43813     MVT SrcVT = Src.getSimpleValueType();
43814     APInt SrcUndef, SrcZero;
43815     APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
43816     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
43817                                    Depth + 1))
43818       return true;
43819     break;
43820   }
43821   case X86ISD::PACKSS:
43822   case X86ISD::PACKUS: {
43823     SDValue N0 = Op.getOperand(0);
43824     SDValue N1 = Op.getOperand(1);
43825 
43826     APInt DemandedLHS, DemandedRHS;
43827     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
43828 
43829     APInt LHSUndef, LHSZero;
43830     if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
43831                                    Depth + 1))
43832       return true;
43833     APInt RHSUndef, RHSZero;
43834     if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
43835                                    Depth + 1))
43836       return true;
43837 
43838     // TODO - pass on known zero/undef.
43839 
43840     // Aggressively peek through ops to get at the demanded elts.
43841     // TODO - we should do this for all target/faux shuffles ops.
43842     if (!DemandedElts.isAllOnes()) {
43843       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
43844                                                             TLO.DAG, Depth + 1);
43845       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
43846                                                             TLO.DAG, Depth + 1);
43847       if (NewN0 || NewN1) {
43848         NewN0 = NewN0 ? NewN0 : N0;
43849         NewN1 = NewN1 ? NewN1 : N1;
43850         return TLO.CombineTo(Op,
43851                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
43852       }
43853     }
43854     break;
43855   }
43856   case X86ISD::HADD:
43857   case X86ISD::HSUB:
43858   case X86ISD::FHADD:
43859   case X86ISD::FHSUB: {
43860     SDValue N0 = Op.getOperand(0);
43861     SDValue N1 = Op.getOperand(1);
43862 
43863     APInt DemandedLHS, DemandedRHS;
43864     getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
43865 
43866     APInt LHSUndef, LHSZero;
43867     if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
43868                                    Depth + 1))
43869       return true;
43870     APInt RHSUndef, RHSZero;
43871     if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
43872                                    Depth + 1))
43873       return true;
43874 
43875     // TODO - pass on known zero/undef.
43876 
43877     // Aggressively peek through ops to get at the demanded elts.
43878     // TODO: Handle repeated operands.
43879     if (N0 != N1 && !DemandedElts.isAllOnes()) {
43880       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
43881                                                             TLO.DAG, Depth + 1);
43882       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
43883                                                             TLO.DAG, Depth + 1);
43884       if (NewN0 || NewN1) {
43885         NewN0 = NewN0 ? NewN0 : N0;
43886         NewN1 = NewN1 ? NewN1 : N1;
43887         return TLO.CombineTo(Op,
43888                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
43889       }
43890     }
43891     break;
43892   }
43893   case X86ISD::VTRUNC:
43894   case X86ISD::VTRUNCS:
43895   case X86ISD::VTRUNCUS: {
43896     SDValue Src = Op.getOperand(0);
43897     MVT SrcVT = Src.getSimpleValueType();
43898     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
43899     APInt SrcUndef, SrcZero;
43900     if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
43901                                    Depth + 1))
43902       return true;
43903     KnownZero = SrcZero.zextOrTrunc(NumElts);
43904     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
43905     break;
43906   }
43907   case X86ISD::BLENDV: {
43908     APInt SelUndef, SelZero;
43909     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
43910                                    SelZero, TLO, Depth + 1))
43911       return true;
43912 
43913     // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
43914     APInt LHSUndef, LHSZero;
43915     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
43916                                    LHSZero, TLO, Depth + 1))
43917       return true;
43918 
43919     APInt RHSUndef, RHSZero;
43920     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
43921                                    RHSZero, TLO, Depth + 1))
43922       return true;
43923 
43924     KnownZero = LHSZero & RHSZero;
43925     KnownUndef = LHSUndef & RHSUndef;
43926     break;
43927   }
43928   case X86ISD::VZEXT_MOVL: {
43929     // If upper demanded elements are already zero then we have nothing to do.
43930     SDValue Src = Op.getOperand(0);
43931     APInt DemandedUpperElts = DemandedElts;
43932     DemandedUpperElts.clearLowBits(1);
43933     if (TLO.DAG.MaskedVectorIsZero(Src, DemandedUpperElts, Depth + 1))
43934       return TLO.CombineTo(Op, Src);
43935     break;
43936   }
43937   case X86ISD::VBROADCAST: {
43938     SDValue Src = Op.getOperand(0);
43939     MVT SrcVT = Src.getSimpleValueType();
43940     if (!SrcVT.isVector())
43941       break;
43942     // Don't bother broadcasting if we just need the 0'th element.
43943     if (DemandedElts == 1) {
43944       if (Src.getValueType() != VT)
43945         Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
43946                              SDLoc(Op));
43947       return TLO.CombineTo(Op, Src);
43948     }
43949     APInt SrcUndef, SrcZero;
43950     APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
43951     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
43952                                    Depth + 1))
43953       return true;
43954     // Aggressively peek through src to get at the demanded elt.
43955     // TODO - we should do this for all target/faux shuffles ops.
43956     if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
43957             Src, SrcElts, TLO.DAG, Depth + 1))
43958       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
43959     break;
43960   }
43961   case X86ISD::VPERMV:
43962     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 0, TLO,
43963                                                    Depth))
43964       return true;
43965     break;
43966   case X86ISD::PSHUFB:
43967   case X86ISD::VPERMV3:
43968   case X86ISD::VPERMILPV:
43969     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 1, TLO,
43970                                                    Depth))
43971       return true;
43972     break;
43973   case X86ISD::VPPERM:
43974   case X86ISD::VPERMIL2:
43975     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 2, TLO,
43976                                                    Depth))
43977       return true;
43978     break;
43979   }
43980 
43981   // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
43982   // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
43983   // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
43984   if ((VT.is256BitVector() || VT.is512BitVector()) &&
43985       DemandedElts.lshr(NumElts / 2) == 0) {
43986     unsigned SizeInBits = VT.getSizeInBits();
43987     unsigned ExtSizeInBits = SizeInBits / 2;
43988 
43989     // See if 512-bit ops only use the bottom 128-bits.
43990     if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
43991       ExtSizeInBits = SizeInBits / 4;
43992 
43993     switch (Opc) {
43994       // Scalar broadcast.
43995     case X86ISD::VBROADCAST: {
43996       SDLoc DL(Op);
43997       SDValue Src = Op.getOperand(0);
43998       if (Src.getValueSizeInBits() > ExtSizeInBits)
43999         Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
44000       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
44001                                     ExtSizeInBits / VT.getScalarSizeInBits());
44002       SDValue Bcst = TLO.DAG.getNode(X86ISD::VBROADCAST, DL, BcstVT, Src);
44003       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
44004                                                TLO.DAG, DL, ExtSizeInBits));
44005     }
44006     case X86ISD::VBROADCAST_LOAD: {
44007       SDLoc DL(Op);
44008       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
44009       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
44010                                     ExtSizeInBits / VT.getScalarSizeInBits());
44011       SDVTList Tys = TLO.DAG.getVTList(BcstVT, MVT::Other);
44012       SDValue Ops[] = {MemIntr->getOperand(0), MemIntr->getOperand(1)};
44013       SDValue Bcst = TLO.DAG.getMemIntrinsicNode(
44014           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MemIntr->getMemoryVT(),
44015           MemIntr->getMemOperand());
44016       TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
44017                                            Bcst.getValue(1));
44018       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
44019                                                TLO.DAG, DL, ExtSizeInBits));
44020     }
44021       // Subvector broadcast.
44022     case X86ISD::SUBV_BROADCAST_LOAD: {
44023       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
44024       EVT MemVT = MemIntr->getMemoryVT();
44025       if (ExtSizeInBits == MemVT.getStoreSizeInBits()) {
44026         SDLoc DL(Op);
44027         SDValue Ld =
44028             TLO.DAG.getLoad(MemVT, DL, MemIntr->getChain(),
44029                             MemIntr->getBasePtr(), MemIntr->getMemOperand());
44030         TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
44031                                              Ld.getValue(1));
44032         return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Ld, 0,
44033                                                  TLO.DAG, DL, ExtSizeInBits));
44034       } else if ((ExtSizeInBits % MemVT.getStoreSizeInBits()) == 0) {
44035         SDLoc DL(Op);
44036         EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
44037                                       ExtSizeInBits / VT.getScalarSizeInBits());
44038         if (SDValue BcstLd =
44039                 getBROADCAST_LOAD(Opc, DL, BcstVT, MemVT, MemIntr, 0, TLO.DAG))
44040           return TLO.CombineTo(Op,
44041                                insertSubVector(TLO.DAG.getUNDEF(VT), BcstLd, 0,
44042                                                TLO.DAG, DL, ExtSizeInBits));
44043       }
44044       break;
44045     }
44046       // Byte shifts by immediate.
44047     case X86ISD::VSHLDQ:
44048     case X86ISD::VSRLDQ:
44049       // Shift by uniform.
44050     case X86ISD::VSHL:
44051     case X86ISD::VSRL:
44052     case X86ISD::VSRA:
44053       // Shift by immediate.
44054     case X86ISD::VSHLI:
44055     case X86ISD::VSRLI:
44056     case X86ISD::VSRAI: {
44057       SDLoc DL(Op);
44058       SDValue Ext0 =
44059           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
44060       SDValue ExtOp =
44061           TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
44062       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
44063       SDValue Insert =
44064           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
44065       return TLO.CombineTo(Op, Insert);
44066     }
44067     case X86ISD::VPERMI: {
44068       // Simplify PERMPD/PERMQ to extract_subvector.
44069       // TODO: This should be done in shuffle combining.
44070       if (VT == MVT::v4f64 || VT == MVT::v4i64) {
44071         SmallVector<int, 4> Mask;
44072         DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
44073         if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
44074           SDLoc DL(Op);
44075           SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
44076           SDValue UndefVec = TLO.DAG.getUNDEF(VT);
44077           SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
44078           return TLO.CombineTo(Op, Insert);
44079         }
44080       }
44081       break;
44082     }
44083     case X86ISD::VPERM2X128: {
44084       // Simplify VPERM2F128/VPERM2I128 to extract_subvector.
44085       SDLoc DL(Op);
44086       unsigned LoMask = Op.getConstantOperandVal(2) & 0xF;
44087       if (LoMask & 0x8)
44088         return TLO.CombineTo(
44089             Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, DL));
44090       unsigned EltIdx = (LoMask & 0x1) * (NumElts / 2);
44091       unsigned SrcIdx = (LoMask & 0x2) >> 1;
44092       SDValue ExtOp =
44093           extractSubVector(Op.getOperand(SrcIdx), EltIdx, TLO.DAG, DL, 128);
44094       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
44095       SDValue Insert =
44096           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
44097       return TLO.CombineTo(Op, Insert);
44098     }
44099       // Zero upper elements.
44100     case X86ISD::VZEXT_MOVL:
44101       // Target unary shuffles by immediate:
44102     case X86ISD::PSHUFD:
44103     case X86ISD::PSHUFLW:
44104     case X86ISD::PSHUFHW:
44105     case X86ISD::VPERMILPI:
44106       // (Non-Lane Crossing) Target Shuffles.
44107     case X86ISD::VPERMILPV:
44108     case X86ISD::VPERMIL2:
44109     case X86ISD::PSHUFB:
44110     case X86ISD::UNPCKL:
44111     case X86ISD::UNPCKH:
44112     case X86ISD::BLENDI:
44113       // Integer ops.
44114     case X86ISD::PACKSS:
44115     case X86ISD::PACKUS:
44116       // Horizontal Ops.
44117     case X86ISD::HADD:
44118     case X86ISD::HSUB:
44119     case X86ISD::FHADD:
44120     case X86ISD::FHSUB: {
44121       SDLoc DL(Op);
44122       SmallVector<SDValue, 4> Ops;
44123       for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
44124         SDValue SrcOp = Op.getOperand(i);
44125         EVT SrcVT = SrcOp.getValueType();
44126         assert((!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) &&
44127                "Unsupported vector size");
44128         Ops.push_back(SrcVT.isVector() ? extractSubVector(SrcOp, 0, TLO.DAG, DL,
44129                                                           ExtSizeInBits)
44130                                        : SrcOp);
44131       }
44132       MVT ExtVT = VT.getSimpleVT();
44133       ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
44134                                ExtSizeInBits / ExtVT.getScalarSizeInBits());
44135       SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ops);
44136       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
44137       SDValue Insert =
44138           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
44139       return TLO.CombineTo(Op, Insert);
44140     }
44141     }
44142   }
44143 
44144   // For splats, unless we *only* demand the 0'th element,
44145   // stop attempts at simplification here, we aren't going to improve things,
44146   // this is better than any potential shuffle.
44147   if (!DemandedElts.isOne() && TLO.DAG.isSplatValue(Op, /*AllowUndefs*/false))
44148     return false;
44149 
44150   // Get target/faux shuffle mask.
44151   APInt OpUndef, OpZero;
44152   SmallVector<int, 64> OpMask;
44153   SmallVector<SDValue, 2> OpInputs;
44154   if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
44155                               OpZero, TLO.DAG, Depth, false))
44156     return false;
44157 
44158   // Shuffle inputs must be the same size as the result.
44159   if (OpMask.size() != (unsigned)NumElts ||
44160       llvm::any_of(OpInputs, [VT](SDValue V) {
44161         return VT.getSizeInBits() != V.getValueSizeInBits() ||
44162                !V.getValueType().isVector();
44163       }))
44164     return false;
44165 
44166   KnownZero = OpZero;
44167   KnownUndef = OpUndef;
44168 
44169   // Check if shuffle mask can be simplified to undef/zero/identity.
44170   int NumSrcs = OpInputs.size();
44171   for (int i = 0; i != NumElts; ++i)
44172     if (!DemandedElts[i])
44173       OpMask[i] = SM_SentinelUndef;
44174 
44175   if (isUndefInRange(OpMask, 0, NumElts)) {
44176     KnownUndef.setAllBits();
44177     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
44178   }
44179   if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
44180     KnownZero.setAllBits();
44181     return TLO.CombineTo(
44182         Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
44183   }
44184   for (int Src = 0; Src != NumSrcs; ++Src)
44185     if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
44186       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
44187 
44188   // Attempt to simplify inputs.
44189   for (int Src = 0; Src != NumSrcs; ++Src) {
44190     // TODO: Support inputs of different types.
44191     if (OpInputs[Src].getValueType() != VT)
44192       continue;
44193 
44194     int Lo = Src * NumElts;
44195     APInt SrcElts = APInt::getZero(NumElts);
44196     for (int i = 0; i != NumElts; ++i)
44197       if (DemandedElts[i]) {
44198         int M = OpMask[i] - Lo;
44199         if (0 <= M && M < NumElts)
44200           SrcElts.setBit(M);
44201       }
44202 
44203     // TODO - Propagate input undef/zero elts.
44204     APInt SrcUndef, SrcZero;
44205     if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
44206                                    TLO, Depth + 1))
44207       return true;
44208   }
44209 
44210   // If we don't demand all elements, then attempt to combine to a simpler
44211   // shuffle.
44212   // We need to convert the depth to something combineX86ShufflesRecursively
44213   // can handle - so pretend its Depth == 0 again, and reduce the max depth
44214   // to match. This prevents combineX86ShuffleChain from returning a
44215   // combined shuffle that's the same as the original root, causing an
44216   // infinite loop.
44217   if (!DemandedElts.isAllOnes()) {
44218     assert(Depth < X86::MaxShuffleCombineDepth && "Depth out of range");
44219 
44220     SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
44221     for (int i = 0; i != NumElts; ++i)
44222       if (DemandedElts[i])
44223         DemandedMask[i] = i;
44224 
44225     SDValue NewShuffle = combineX86ShufflesRecursively(
44226         {Op}, 0, Op, DemandedMask, {}, 0, X86::MaxShuffleCombineDepth - Depth,
44227         /*HasVarMask*/ false,
44228         /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, TLO.DAG,
44229         Subtarget);
44230     if (NewShuffle)
44231       return TLO.CombineTo(Op, NewShuffle);
44232   }
44233 
44234   return false;
44235 }
44236 
44237 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
44238     SDValue Op, const APInt &OriginalDemandedBits,
44239     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
44240     unsigned Depth) const {
44241   EVT VT = Op.getValueType();
44242   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
44243   unsigned Opc = Op.getOpcode();
44244   switch(Opc) {
44245   case X86ISD::VTRUNC: {
44246     KnownBits KnownOp;
44247     SDValue Src = Op.getOperand(0);
44248     MVT SrcVT = Src.getSimpleValueType();
44249 
44250     // Simplify the input, using demanded bit information.
44251     APInt TruncMask = OriginalDemandedBits.zext(SrcVT.getScalarSizeInBits());
44252     APInt DemandedElts = OriginalDemandedElts.trunc(SrcVT.getVectorNumElements());
44253     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, KnownOp, TLO, Depth + 1))
44254       return true;
44255     break;
44256   }
44257   case X86ISD::PMULDQ:
44258   case X86ISD::PMULUDQ: {
44259     // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
44260     KnownBits KnownLHS, KnownRHS;
44261     SDValue LHS = Op.getOperand(0);
44262     SDValue RHS = Op.getOperand(1);
44263 
44264     // Don't mask bits on 32-bit AVX512 targets which might lose a broadcast.
44265     // FIXME: Can we bound this better?
44266     APInt DemandedMask = APInt::getLowBitsSet(64, 32);
44267     APInt DemandedMaskLHS = APInt::getAllOnes(64);
44268     APInt DemandedMaskRHS = APInt::getAllOnes(64);
44269 
44270     bool Is32BitAVX512 = !Subtarget.is64Bit() && Subtarget.hasAVX512();
44271     if (!Is32BitAVX512 || !TLO.DAG.isSplatValue(LHS))
44272       DemandedMaskLHS = DemandedMask;
44273     if (!Is32BitAVX512 || !TLO.DAG.isSplatValue(RHS))
44274       DemandedMaskRHS = DemandedMask;
44275 
44276     if (SimplifyDemandedBits(LHS, DemandedMaskLHS, OriginalDemandedElts,
44277                              KnownLHS, TLO, Depth + 1))
44278       return true;
44279     if (SimplifyDemandedBits(RHS, DemandedMaskRHS, OriginalDemandedElts,
44280                              KnownRHS, TLO, Depth + 1))
44281       return true;
44282 
44283     // PMULUDQ(X,1) -> AND(X,(1<<32)-1) 'getZeroExtendInReg'.
44284     KnownRHS = KnownRHS.trunc(32);
44285     if (Opc == X86ISD::PMULUDQ && KnownRHS.isConstant() &&
44286         KnownRHS.getConstant().isOne()) {
44287       SDLoc DL(Op);
44288       SDValue Mask = TLO.DAG.getConstant(DemandedMask, DL, VT);
44289       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, DL, VT, LHS, Mask));
44290     }
44291 
44292     // Aggressively peek through ops to get at the demanded low bits.
44293     SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
44294         LHS, DemandedMaskLHS, OriginalDemandedElts, TLO.DAG, Depth + 1);
44295     SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
44296         RHS, DemandedMaskRHS, OriginalDemandedElts, TLO.DAG, Depth + 1);
44297     if (DemandedLHS || DemandedRHS) {
44298       DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
44299       DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
44300       return TLO.CombineTo(
44301           Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
44302     }
44303     break;
44304   }
44305   case X86ISD::ANDNP: {
44306     KnownBits Known2;
44307     SDValue Op0 = Op.getOperand(0);
44308     SDValue Op1 = Op.getOperand(1);
44309 
44310     if (SimplifyDemandedBits(Op1, OriginalDemandedBits, OriginalDemandedElts,
44311                              Known, TLO, Depth + 1))
44312       return true;
44313     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
44314 
44315     if (SimplifyDemandedBits(Op0, ~Known.Zero & OriginalDemandedBits,
44316                              OriginalDemandedElts, Known2, TLO, Depth + 1))
44317       return true;
44318     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
44319 
44320     // If the RHS is a constant, see if we can simplify it.
44321     if (ShrinkDemandedConstant(Op, ~Known2.One & OriginalDemandedBits,
44322                                OriginalDemandedElts, TLO))
44323       return true;
44324 
44325     // ANDNP = (~Op0 & Op1);
44326     Known.One &= Known2.Zero;
44327     Known.Zero |= Known2.One;
44328     break;
44329   }
44330   case X86ISD::VSHLI: {
44331     SDValue Op0 = Op.getOperand(0);
44332 
44333     unsigned ShAmt = Op.getConstantOperandVal(1);
44334     if (ShAmt >= BitWidth)
44335       break;
44336 
44337     APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
44338 
44339     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
44340     // single shift.  We can do this if the bottom bits (which are shifted
44341     // out) are never demanded.
44342     if (Op0.getOpcode() == X86ISD::VSRLI &&
44343         OriginalDemandedBits.countr_zero() >= ShAmt) {
44344       unsigned Shift2Amt = Op0.getConstantOperandVal(1);
44345       if (Shift2Amt < BitWidth) {
44346         int Diff = ShAmt - Shift2Amt;
44347         if (Diff == 0)
44348           return TLO.CombineTo(Op, Op0.getOperand(0));
44349 
44350         unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
44351         SDValue NewShift = TLO.DAG.getNode(
44352             NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
44353             TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
44354         return TLO.CombineTo(Op, NewShift);
44355       }
44356     }
44357 
44358     // If we are only demanding sign bits then we can use the shift source directly.
44359     unsigned NumSignBits =
44360         TLO.DAG.ComputeNumSignBits(Op0, OriginalDemandedElts, Depth + 1);
44361     unsigned UpperDemandedBits = BitWidth - OriginalDemandedBits.countr_zero();
44362     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
44363       return TLO.CombineTo(Op, Op0);
44364 
44365     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
44366                              TLO, Depth + 1))
44367       return true;
44368 
44369     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
44370     Known.Zero <<= ShAmt;
44371     Known.One <<= ShAmt;
44372 
44373     // Low bits known zero.
44374     Known.Zero.setLowBits(ShAmt);
44375     return false;
44376   }
44377   case X86ISD::VSRLI: {
44378     unsigned ShAmt = Op.getConstantOperandVal(1);
44379     if (ShAmt >= BitWidth)
44380       break;
44381 
44382     APInt DemandedMask = OriginalDemandedBits << ShAmt;
44383 
44384     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
44385                              OriginalDemandedElts, Known, TLO, Depth + 1))
44386       return true;
44387 
44388     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
44389     Known.Zero.lshrInPlace(ShAmt);
44390     Known.One.lshrInPlace(ShAmt);
44391 
44392     // High bits known zero.
44393     Known.Zero.setHighBits(ShAmt);
44394     return false;
44395   }
44396   case X86ISD::VSRAI: {
44397     SDValue Op0 = Op.getOperand(0);
44398     SDValue Op1 = Op.getOperand(1);
44399 
44400     unsigned ShAmt = cast<ConstantSDNode>(Op1)->getZExtValue();
44401     if (ShAmt >= BitWidth)
44402       break;
44403 
44404     APInt DemandedMask = OriginalDemandedBits << ShAmt;
44405 
44406     // If we just want the sign bit then we don't need to shift it.
44407     if (OriginalDemandedBits.isSignMask())
44408       return TLO.CombineTo(Op, Op0);
44409 
44410     // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
44411     if (Op0.getOpcode() == X86ISD::VSHLI &&
44412         Op.getOperand(1) == Op0.getOperand(1)) {
44413       SDValue Op00 = Op0.getOperand(0);
44414       unsigned NumSignBits =
44415           TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
44416       if (ShAmt < NumSignBits)
44417         return TLO.CombineTo(Op, Op00);
44418     }
44419 
44420     // If any of the demanded bits are produced by the sign extension, we also
44421     // demand the input sign bit.
44422     if (OriginalDemandedBits.countl_zero() < ShAmt)
44423       DemandedMask.setSignBit();
44424 
44425     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
44426                              TLO, Depth + 1))
44427       return true;
44428 
44429     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
44430     Known.Zero.lshrInPlace(ShAmt);
44431     Known.One.lshrInPlace(ShAmt);
44432 
44433     // If the input sign bit is known to be zero, or if none of the top bits
44434     // are demanded, turn this into an unsigned shift right.
44435     if (Known.Zero[BitWidth - ShAmt - 1] ||
44436         OriginalDemandedBits.countl_zero() >= ShAmt)
44437       return TLO.CombineTo(
44438           Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
44439 
44440     // High bits are known one.
44441     if (Known.One[BitWidth - ShAmt - 1])
44442       Known.One.setHighBits(ShAmt);
44443     return false;
44444   }
44445   case X86ISD::BLENDV: {
44446     SDValue Sel = Op.getOperand(0);
44447     SDValue LHS = Op.getOperand(1);
44448     SDValue RHS = Op.getOperand(2);
44449 
44450     APInt SignMask = APInt::getSignMask(BitWidth);
44451     SDValue NewSel = SimplifyMultipleUseDemandedBits(
44452         Sel, SignMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
44453     SDValue NewLHS = SimplifyMultipleUseDemandedBits(
44454         LHS, OriginalDemandedBits, OriginalDemandedElts, TLO.DAG, Depth + 1);
44455     SDValue NewRHS = SimplifyMultipleUseDemandedBits(
44456         RHS, OriginalDemandedBits, OriginalDemandedElts, TLO.DAG, Depth + 1);
44457 
44458     if (NewSel || NewLHS || NewRHS) {
44459       NewSel = NewSel ? NewSel : Sel;
44460       NewLHS = NewLHS ? NewLHS : LHS;
44461       NewRHS = NewRHS ? NewRHS : RHS;
44462       return TLO.CombineTo(Op, TLO.DAG.getNode(X86ISD::BLENDV, SDLoc(Op), VT,
44463                                                NewSel, NewLHS, NewRHS));
44464     }
44465     break;
44466   }
44467   case X86ISD::PEXTRB:
44468   case X86ISD::PEXTRW: {
44469     SDValue Vec = Op.getOperand(0);
44470     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
44471     MVT VecVT = Vec.getSimpleValueType();
44472     unsigned NumVecElts = VecVT.getVectorNumElements();
44473 
44474     if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
44475       unsigned Idx = CIdx->getZExtValue();
44476       unsigned VecBitWidth = VecVT.getScalarSizeInBits();
44477 
44478       // If we demand no bits from the vector then we must have demanded
44479       // bits from the implict zext - simplify to zero.
44480       APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
44481       if (DemandedVecBits == 0)
44482         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
44483 
44484       APInt KnownUndef, KnownZero;
44485       APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
44486       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
44487                                      KnownZero, TLO, Depth + 1))
44488         return true;
44489 
44490       KnownBits KnownVec;
44491       if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
44492                                KnownVec, TLO, Depth + 1))
44493         return true;
44494 
44495       if (SDValue V = SimplifyMultipleUseDemandedBits(
44496               Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
44497         return TLO.CombineTo(
44498             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
44499 
44500       Known = KnownVec.zext(BitWidth);
44501       return false;
44502     }
44503     break;
44504   }
44505   case X86ISD::PINSRB:
44506   case X86ISD::PINSRW: {
44507     SDValue Vec = Op.getOperand(0);
44508     SDValue Scl = Op.getOperand(1);
44509     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
44510     MVT VecVT = Vec.getSimpleValueType();
44511 
44512     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
44513       unsigned Idx = CIdx->getZExtValue();
44514       if (!OriginalDemandedElts[Idx])
44515         return TLO.CombineTo(Op, Vec);
44516 
44517       KnownBits KnownVec;
44518       APInt DemandedVecElts(OriginalDemandedElts);
44519       DemandedVecElts.clearBit(Idx);
44520       if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
44521                                KnownVec, TLO, Depth + 1))
44522         return true;
44523 
44524       KnownBits KnownScl;
44525       unsigned NumSclBits = Scl.getScalarValueSizeInBits();
44526       APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
44527       if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
44528         return true;
44529 
44530       KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
44531       Known = KnownVec.intersectWith(KnownScl);
44532       return false;
44533     }
44534     break;
44535   }
44536   case X86ISD::PACKSS:
44537     // PACKSS saturates to MIN/MAX integer values. So if we just want the
44538     // sign bit then we can just ask for the source operands sign bit.
44539     // TODO - add known bits handling.
44540     if (OriginalDemandedBits.isSignMask()) {
44541       APInt DemandedLHS, DemandedRHS;
44542       getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
44543 
44544       KnownBits KnownLHS, KnownRHS;
44545       APInt SignMask = APInt::getSignMask(BitWidth * 2);
44546       if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
44547                                KnownLHS, TLO, Depth + 1))
44548         return true;
44549       if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
44550                                KnownRHS, TLO, Depth + 1))
44551         return true;
44552 
44553       // Attempt to avoid multi-use ops if we don't need anything from them.
44554       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
44555           Op.getOperand(0), SignMask, DemandedLHS, TLO.DAG, Depth + 1);
44556       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
44557           Op.getOperand(1), SignMask, DemandedRHS, TLO.DAG, Depth + 1);
44558       if (DemandedOp0 || DemandedOp1) {
44559         SDValue Op0 = DemandedOp0 ? DemandedOp0 : Op.getOperand(0);
44560         SDValue Op1 = DemandedOp1 ? DemandedOp1 : Op.getOperand(1);
44561         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, Op0, Op1));
44562       }
44563     }
44564     // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
44565     break;
44566   case X86ISD::VBROADCAST: {
44567     SDValue Src = Op.getOperand(0);
44568     MVT SrcVT = Src.getSimpleValueType();
44569     APInt DemandedElts = APInt::getOneBitSet(
44570         SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1, 0);
44571     if (SimplifyDemandedBits(Src, OriginalDemandedBits, DemandedElts, Known,
44572                              TLO, Depth + 1))
44573       return true;
44574     // If we don't need the upper bits, attempt to narrow the broadcast source.
44575     // Don't attempt this on AVX512 as it might affect broadcast folding.
44576     // TODO: Should we attempt this for i32/i16 splats? They tend to be slower.
44577     if ((BitWidth == 64) && SrcVT.isScalarInteger() && !Subtarget.hasAVX512() &&
44578         OriginalDemandedBits.countl_zero() >= (BitWidth / 2) &&
44579         Src->hasOneUse()) {
44580       MVT NewSrcVT = MVT::getIntegerVT(BitWidth / 2);
44581       SDValue NewSrc =
44582           TLO.DAG.getNode(ISD::TRUNCATE, SDLoc(Src), NewSrcVT, Src);
44583       MVT NewVT = MVT::getVectorVT(NewSrcVT, VT.getVectorNumElements() * 2);
44584       SDValue NewBcst =
44585           TLO.DAG.getNode(X86ISD::VBROADCAST, SDLoc(Op), NewVT, NewSrc);
44586       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, NewBcst));
44587     }
44588     break;
44589   }
44590   case X86ISD::PCMPGT:
44591     // icmp sgt(0, R) == ashr(R, BitWidth-1).
44592     // iff we only need the sign bit then we can use R directly.
44593     if (OriginalDemandedBits.isSignMask() &&
44594         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
44595       return TLO.CombineTo(Op, Op.getOperand(1));
44596     break;
44597   case X86ISD::MOVMSK: {
44598     SDValue Src = Op.getOperand(0);
44599     MVT SrcVT = Src.getSimpleValueType();
44600     unsigned SrcBits = SrcVT.getScalarSizeInBits();
44601     unsigned NumElts = SrcVT.getVectorNumElements();
44602 
44603     // If we don't need the sign bits at all just return zero.
44604     if (OriginalDemandedBits.countr_zero() >= NumElts)
44605       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
44606 
44607     // See if we only demand bits from the lower 128-bit vector.
44608     if (SrcVT.is256BitVector() &&
44609         OriginalDemandedBits.getActiveBits() <= (NumElts / 2)) {
44610       SDValue NewSrc = extract128BitVector(Src, 0, TLO.DAG, SDLoc(Src));
44611       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
44612     }
44613 
44614     // Only demand the vector elements of the sign bits we need.
44615     APInt KnownUndef, KnownZero;
44616     APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
44617     if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
44618                                    TLO, Depth + 1))
44619       return true;
44620 
44621     Known.Zero = KnownZero.zext(BitWidth);
44622     Known.Zero.setHighBits(BitWidth - NumElts);
44623 
44624     // MOVMSK only uses the MSB from each vector element.
44625     KnownBits KnownSrc;
44626     APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
44627     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
44628                              Depth + 1))
44629       return true;
44630 
44631     if (KnownSrc.One[SrcBits - 1])
44632       Known.One.setLowBits(NumElts);
44633     else if (KnownSrc.Zero[SrcBits - 1])
44634       Known.Zero.setLowBits(NumElts);
44635 
44636     // Attempt to avoid multi-use os if we don't need anything from it.
44637     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
44638             Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
44639       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
44640     return false;
44641   }
44642   case X86ISD::TESTP: {
44643     SDValue Op0 = Op.getOperand(0);
44644     SDValue Op1 = Op.getOperand(1);
44645     MVT OpVT = Op0.getSimpleValueType();
44646     assert((OpVT.getVectorElementType() == MVT::f32 ||
44647             OpVT.getVectorElementType() == MVT::f64) &&
44648            "Illegal vector type for X86ISD::TESTP");
44649 
44650     // TESTPS/TESTPD only demands the sign bits of ALL the elements.
44651     KnownBits KnownSrc;
44652     APInt SignMask = APInt::getSignMask(OpVT.getScalarSizeInBits());
44653     bool AssumeSingleUse = (Op0 == Op1) && Op->isOnlyUserOf(Op0.getNode());
44654     return SimplifyDemandedBits(Op0, SignMask, KnownSrc, TLO, Depth + 1,
44655                                 AssumeSingleUse) ||
44656            SimplifyDemandedBits(Op1, SignMask, KnownSrc, TLO, Depth + 1,
44657                                 AssumeSingleUse);
44658   }
44659   case X86ISD::BEXTR:
44660   case X86ISD::BEXTRI: {
44661     SDValue Op0 = Op.getOperand(0);
44662     SDValue Op1 = Op.getOperand(1);
44663 
44664     // Only bottom 16-bits of the control bits are required.
44665     if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
44666       // NOTE: SimplifyDemandedBits won't do this for constants.
44667       uint64_t Val1 = Cst1->getZExtValue();
44668       uint64_t MaskedVal1 = Val1 & 0xFFFF;
44669       if (Opc == X86ISD::BEXTR && MaskedVal1 != Val1) {
44670         SDLoc DL(Op);
44671         return TLO.CombineTo(
44672             Op, TLO.DAG.getNode(X86ISD::BEXTR, DL, VT, Op0,
44673                                 TLO.DAG.getConstant(MaskedVal1, DL, VT)));
44674       }
44675 
44676       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
44677       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
44678 
44679       // If the length is 0, the result is 0.
44680       if (Length == 0) {
44681         Known.setAllZero();
44682         return false;
44683       }
44684 
44685       if ((Shift + Length) <= BitWidth) {
44686         APInt DemandedMask = APInt::getBitsSet(BitWidth, Shift, Shift + Length);
44687         if (SimplifyDemandedBits(Op0, DemandedMask, Known, TLO, Depth + 1))
44688           return true;
44689 
44690         Known = Known.extractBits(Length, Shift);
44691         Known = Known.zextOrTrunc(BitWidth);
44692         return false;
44693       }
44694     } else {
44695       assert(Opc == X86ISD::BEXTR && "Unexpected opcode!");
44696       KnownBits Known1;
44697       APInt DemandedMask(APInt::getLowBitsSet(BitWidth, 16));
44698       if (SimplifyDemandedBits(Op1, DemandedMask, Known1, TLO, Depth + 1))
44699         return true;
44700 
44701       // If the length is 0, replace with 0.
44702       KnownBits LengthBits = Known1.extractBits(8, 8);
44703       if (LengthBits.isZero())
44704         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
44705     }
44706 
44707     break;
44708   }
44709   case X86ISD::PDEP: {
44710     SDValue Op0 = Op.getOperand(0);
44711     SDValue Op1 = Op.getOperand(1);
44712 
44713     unsigned DemandedBitsLZ = OriginalDemandedBits.countl_zero();
44714     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
44715 
44716     // If the demanded bits has leading zeroes, we don't demand those from the
44717     // mask.
44718     if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
44719       return true;
44720 
44721     // The number of possible 1s in the mask determines the number of LSBs of
44722     // operand 0 used. Undemanded bits from the mask don't matter so filter
44723     // them before counting.
44724     KnownBits Known2;
44725     uint64_t Count = (~Known.Zero & LoMask).popcount();
44726     APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
44727     if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
44728       return true;
44729 
44730     // Zeroes are retained from the mask, but not ones.
44731     Known.One.clearAllBits();
44732     // The result will have at least as many trailing zeros as the non-mask
44733     // operand since bits can only map to the same or higher bit position.
44734     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
44735     return false;
44736   }
44737   }
44738 
44739   return TargetLowering::SimplifyDemandedBitsForTargetNode(
44740       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
44741 }
44742 
44743 SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
44744     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
44745     SelectionDAG &DAG, unsigned Depth) const {
44746   int NumElts = DemandedElts.getBitWidth();
44747   unsigned Opc = Op.getOpcode();
44748   EVT VT = Op.getValueType();
44749 
44750   switch (Opc) {
44751   case X86ISD::PINSRB:
44752   case X86ISD::PINSRW: {
44753     // If we don't demand the inserted element, return the base vector.
44754     SDValue Vec = Op.getOperand(0);
44755     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
44756     MVT VecVT = Vec.getSimpleValueType();
44757     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
44758         !DemandedElts[CIdx->getZExtValue()])
44759       return Vec;
44760     break;
44761   }
44762   case X86ISD::VSHLI: {
44763     // If we are only demanding sign bits then we can use the shift source
44764     // directly.
44765     SDValue Op0 = Op.getOperand(0);
44766     unsigned ShAmt = Op.getConstantOperandVal(1);
44767     unsigned BitWidth = DemandedBits.getBitWidth();
44768     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
44769     unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
44770     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
44771       return Op0;
44772     break;
44773   }
44774   case X86ISD::VSRAI:
44775     // iff we only need the sign bit then we can use the source directly.
44776     // TODO: generalize where we only demand extended signbits.
44777     if (DemandedBits.isSignMask())
44778       return Op.getOperand(0);
44779     break;
44780   case X86ISD::PCMPGT:
44781     // icmp sgt(0, R) == ashr(R, BitWidth-1).
44782     // iff we only need the sign bit then we can use R directly.
44783     if (DemandedBits.isSignMask() &&
44784         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
44785       return Op.getOperand(1);
44786     break;
44787   case X86ISD::ANDNP: {
44788     // ANDNP = (~LHS & RHS);
44789     SDValue LHS = Op.getOperand(0);
44790     SDValue RHS = Op.getOperand(1);
44791 
44792     KnownBits LHSKnown = DAG.computeKnownBits(LHS, DemandedElts, Depth + 1);
44793     KnownBits RHSKnown = DAG.computeKnownBits(RHS, DemandedElts, Depth + 1);
44794 
44795     // If all of the demanded bits are known 0 on LHS and known 0 on RHS, then
44796     // the (inverted) LHS bits cannot contribute to the result of the 'andn' in
44797     // this context, so return RHS.
44798     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero))
44799       return RHS;
44800     break;
44801   }
44802   }
44803 
44804   APInt ShuffleUndef, ShuffleZero;
44805   SmallVector<int, 16> ShuffleMask;
44806   SmallVector<SDValue, 2> ShuffleOps;
44807   if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
44808                              ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
44809     // If all the demanded elts are from one operand and are inline,
44810     // then we can use the operand directly.
44811     int NumOps = ShuffleOps.size();
44812     if (ShuffleMask.size() == (unsigned)NumElts &&
44813         llvm::all_of(ShuffleOps, [VT](SDValue V) {
44814           return VT.getSizeInBits() == V.getValueSizeInBits();
44815         })) {
44816 
44817       if (DemandedElts.isSubsetOf(ShuffleUndef))
44818         return DAG.getUNDEF(VT);
44819       if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
44820         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
44821 
44822       // Bitmask that indicates which ops have only been accessed 'inline'.
44823       APInt IdentityOp = APInt::getAllOnes(NumOps);
44824       for (int i = 0; i != NumElts; ++i) {
44825         int M = ShuffleMask[i];
44826         if (!DemandedElts[i] || ShuffleUndef[i])
44827           continue;
44828         int OpIdx = M / NumElts;
44829         int EltIdx = M % NumElts;
44830         if (M < 0 || EltIdx != i) {
44831           IdentityOp.clearAllBits();
44832           break;
44833         }
44834         IdentityOp &= APInt::getOneBitSet(NumOps, OpIdx);
44835         if (IdentityOp == 0)
44836           break;
44837       }
44838       assert((IdentityOp == 0 || IdentityOp.popcount() == 1) &&
44839              "Multiple identity shuffles detected");
44840 
44841       if (IdentityOp != 0)
44842         return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countr_zero()]);
44843     }
44844   }
44845 
44846   return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
44847       Op, DemandedBits, DemandedElts, DAG, Depth);
44848 }
44849 
44850 bool X86TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
44851     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
44852     bool PoisonOnly, unsigned Depth) const {
44853   unsigned EltsBits = Op.getScalarValueSizeInBits();
44854   unsigned NumElts = DemandedElts.getBitWidth();
44855 
44856   // TODO: Add more target shuffles.
44857   switch (Op.getOpcode()) {
44858   case X86ISD::PSHUFD:
44859   case X86ISD::VPERMILPI: {
44860     SmallVector<int, 8> Mask;
44861     DecodePSHUFMask(NumElts, EltsBits, Op.getConstantOperandVal(1), Mask);
44862 
44863     APInt DemandedSrcElts = APInt::getZero(NumElts);
44864     for (unsigned I = 0; I != NumElts; ++I)
44865       if (DemandedElts[I])
44866         DemandedSrcElts.setBit(Mask[I]);
44867 
44868     return DAG.isGuaranteedNotToBeUndefOrPoison(
44869         Op.getOperand(0), DemandedSrcElts, PoisonOnly, Depth + 1);
44870   }
44871   }
44872   return TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
44873       Op, DemandedElts, DAG, PoisonOnly, Depth);
44874 }
44875 
44876 bool X86TargetLowering::canCreateUndefOrPoisonForTargetNode(
44877     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
44878     bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const {
44879 
44880   // TODO: Add more target shuffles.
44881   switch (Op.getOpcode()) {
44882   case X86ISD::PSHUFD:
44883   case X86ISD::VPERMILPI:
44884     return false;
44885   }
44886   return TargetLowering::canCreateUndefOrPoisonForTargetNode(
44887       Op, DemandedElts, DAG, PoisonOnly, ConsiderFlags, Depth);
44888 }
44889 
44890 bool X86TargetLowering::isSplatValueForTargetNode(SDValue Op,
44891                                                   const APInt &DemandedElts,
44892                                                   APInt &UndefElts,
44893                                                   const SelectionDAG &DAG,
44894                                                   unsigned Depth) const {
44895   unsigned NumElts = DemandedElts.getBitWidth();
44896   unsigned Opc = Op.getOpcode();
44897 
44898   switch (Opc) {
44899   case X86ISD::VBROADCAST:
44900   case X86ISD::VBROADCAST_LOAD:
44901     UndefElts = APInt::getZero(NumElts);
44902     return true;
44903   }
44904 
44905   return TargetLowering::isSplatValueForTargetNode(Op, DemandedElts, UndefElts,
44906                                                    DAG, Depth);
44907 }
44908 
44909 // Helper to peek through bitops/trunc/setcc to determine size of source vector.
44910 // Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
44911 static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size,
44912                                       bool AllowTruncate) {
44913   switch (Src.getOpcode()) {
44914   case ISD::TRUNCATE:
44915     if (!AllowTruncate)
44916       return false;
44917     [[fallthrough]];
44918   case ISD::SETCC:
44919     return Src.getOperand(0).getValueSizeInBits() == Size;
44920   case ISD::AND:
44921   case ISD::XOR:
44922   case ISD::OR:
44923     return checkBitcastSrcVectorSize(Src.getOperand(0), Size, AllowTruncate) &&
44924            checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate);
44925   case ISD::SELECT:
44926   case ISD::VSELECT:
44927     return Src.getOperand(0).getScalarValueSizeInBits() == 1 &&
44928            checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate) &&
44929            checkBitcastSrcVectorSize(Src.getOperand(2), Size, AllowTruncate);
44930   case ISD::BUILD_VECTOR:
44931     return ISD::isBuildVectorAllZeros(Src.getNode()) ||
44932            ISD::isBuildVectorAllOnes(Src.getNode());
44933   }
44934   return false;
44935 }
44936 
44937 // Helper to flip between AND/OR/XOR opcodes and their X86ISD FP equivalents.
44938 static unsigned getAltBitOpcode(unsigned Opcode) {
44939   switch(Opcode) {
44940   case ISD::AND: return X86ISD::FAND;
44941   case ISD::OR: return X86ISD::FOR;
44942   case ISD::XOR: return X86ISD::FXOR;
44943   case X86ISD::ANDNP: return X86ISD::FANDN;
44944   }
44945   llvm_unreachable("Unknown bitwise opcode");
44946 }
44947 
44948 // Helper to adjust v4i32 MOVMSK expansion to work with SSE1-only targets.
44949 static SDValue adjustBitcastSrcVectorSSE1(SelectionDAG &DAG, SDValue Src,
44950                                           const SDLoc &DL) {
44951   EVT SrcVT = Src.getValueType();
44952   if (SrcVT != MVT::v4i1)
44953     return SDValue();
44954 
44955   switch (Src.getOpcode()) {
44956   case ISD::SETCC:
44957     if (Src.getOperand(0).getValueType() == MVT::v4i32 &&
44958         ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
44959         cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT) {
44960       SDValue Op0 = Src.getOperand(0);
44961       if (ISD::isNormalLoad(Op0.getNode()))
44962         return DAG.getBitcast(MVT::v4f32, Op0);
44963       if (Op0.getOpcode() == ISD::BITCAST &&
44964           Op0.getOperand(0).getValueType() == MVT::v4f32)
44965         return Op0.getOperand(0);
44966     }
44967     break;
44968   case ISD::AND:
44969   case ISD::XOR:
44970   case ISD::OR: {
44971     SDValue Op0 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(0), DL);
44972     SDValue Op1 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(1), DL);
44973     if (Op0 && Op1)
44974       return DAG.getNode(getAltBitOpcode(Src.getOpcode()), DL, MVT::v4f32, Op0,
44975                          Op1);
44976     break;
44977   }
44978   }
44979   return SDValue();
44980 }
44981 
44982 // Helper to push sign extension of vXi1 SETCC result through bitops.
44983 static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
44984                                           SDValue Src, const SDLoc &DL) {
44985   switch (Src.getOpcode()) {
44986   case ISD::SETCC:
44987   case ISD::TRUNCATE:
44988   case ISD::BUILD_VECTOR:
44989     return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
44990   case ISD::AND:
44991   case ISD::XOR:
44992   case ISD::OR:
44993     return DAG.getNode(
44994         Src.getOpcode(), DL, SExtVT,
44995         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
44996         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
44997   case ISD::SELECT:
44998   case ISD::VSELECT:
44999     return DAG.getSelect(
45000         DL, SExtVT, Src.getOperand(0),
45001         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL),
45002         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(2), DL));
45003   }
45004   llvm_unreachable("Unexpected node type for vXi1 sign extension");
45005 }
45006 
45007 // Try to match patterns such as
45008 // (i16 bitcast (v16i1 x))
45009 // ->
45010 // (i16 movmsk (16i8 sext (v16i1 x)))
45011 // before the illegal vector is scalarized on subtargets that don't have legal
45012 // vxi1 types.
45013 static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
45014                                   const SDLoc &DL,
45015                                   const X86Subtarget &Subtarget) {
45016   EVT SrcVT = Src.getValueType();
45017   if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
45018     return SDValue();
45019 
45020   // Recognize the IR pattern for the movmsk intrinsic under SSE1 before type
45021   // legalization destroys the v4i32 type.
45022   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2()) {
45023     if (SDValue V = adjustBitcastSrcVectorSSE1(DAG, Src, DL)) {
45024       V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32,
45025                       DAG.getBitcast(MVT::v4f32, V));
45026       return DAG.getZExtOrTrunc(V, DL, VT);
45027     }
45028   }
45029 
45030   // If the input is a truncate from v16i8 or v32i8 go ahead and use a
45031   // movmskb even with avx512. This will be better than truncating to vXi1 and
45032   // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
45033   // vpcmpeqb/vpcmpgtb.
45034   bool PreferMovMsk = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
45035                       (Src.getOperand(0).getValueType() == MVT::v16i8 ||
45036                        Src.getOperand(0).getValueType() == MVT::v32i8 ||
45037                        Src.getOperand(0).getValueType() == MVT::v64i8);
45038 
45039   // Prefer movmsk for AVX512 for (bitcast (setlt X, 0)) which can be handled
45040   // directly with vpmovmskb/vmovmskps/vmovmskpd.
45041   if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
45042       cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT &&
45043       ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
45044     EVT CmpVT = Src.getOperand(0).getValueType();
45045     EVT EltVT = CmpVT.getVectorElementType();
45046     if (CmpVT.getSizeInBits() <= 256 &&
45047         (EltVT == MVT::i8 || EltVT == MVT::i32 || EltVT == MVT::i64))
45048       PreferMovMsk = true;
45049   }
45050 
45051   // With AVX512 vxi1 types are legal and we prefer using k-regs.
45052   // MOVMSK is supported in SSE2 or later.
45053   if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !PreferMovMsk))
45054     return SDValue();
45055 
45056   // If the upper ops of a concatenation are undef, then try to bitcast the
45057   // lower op and extend.
45058   SmallVector<SDValue, 4> SubSrcOps;
45059   if (collectConcatOps(Src.getNode(), SubSrcOps, DAG) &&
45060       SubSrcOps.size() >= 2) {
45061     SDValue LowerOp = SubSrcOps[0];
45062     ArrayRef<SDValue> UpperOps(std::next(SubSrcOps.begin()), SubSrcOps.end());
45063     if (LowerOp.getOpcode() == ISD::SETCC &&
45064         all_of(UpperOps, [](SDValue Op) { return Op.isUndef(); })) {
45065       EVT SubVT = VT.getIntegerVT(
45066           *DAG.getContext(), LowerOp.getValueType().getVectorMinNumElements());
45067       if (SDValue V = combineBitcastvxi1(DAG, SubVT, LowerOp, DL, Subtarget)) {
45068         EVT IntVT = VT.getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
45069         return DAG.getBitcast(VT, DAG.getNode(ISD::ANY_EXTEND, DL, IntVT, V));
45070       }
45071     }
45072   }
45073 
45074   // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
45075   // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
45076   // v8i16 and v16i16.
45077   // For these two cases, we can shuffle the upper element bytes to a
45078   // consecutive sequence at the start of the vector and treat the results as
45079   // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
45080   // for v16i16 this is not the case, because the shuffle is expensive, so we
45081   // avoid sign-extending to this type entirely.
45082   // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
45083   // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
45084   MVT SExtVT;
45085   bool PropagateSExt = false;
45086   switch (SrcVT.getSimpleVT().SimpleTy) {
45087   default:
45088     return SDValue();
45089   case MVT::v2i1:
45090     SExtVT = MVT::v2i64;
45091     break;
45092   case MVT::v4i1:
45093     SExtVT = MVT::v4i32;
45094     // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
45095     // sign-extend to a 256-bit operation to avoid truncation.
45096     if (Subtarget.hasAVX() &&
45097         checkBitcastSrcVectorSize(Src, 256, Subtarget.hasAVX2())) {
45098       SExtVT = MVT::v4i64;
45099       PropagateSExt = true;
45100     }
45101     break;
45102   case MVT::v8i1:
45103     SExtVT = MVT::v8i16;
45104     // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
45105     // sign-extend to a 256-bit operation to match the compare.
45106     // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
45107     // 256-bit because the shuffle is cheaper than sign extending the result of
45108     // the compare.
45109     if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256, true) ||
45110                                checkBitcastSrcVectorSize(Src, 512, true))) {
45111       SExtVT = MVT::v8i32;
45112       PropagateSExt = true;
45113     }
45114     break;
45115   case MVT::v16i1:
45116     SExtVT = MVT::v16i8;
45117     // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
45118     // it is not profitable to sign-extend to 256-bit because this will
45119     // require an extra cross-lane shuffle which is more expensive than
45120     // truncating the result of the compare to 128-bits.
45121     break;
45122   case MVT::v32i1:
45123     SExtVT = MVT::v32i8;
45124     break;
45125   case MVT::v64i1:
45126     // If we have AVX512F, but not AVX512BW and the input is truncated from
45127     // v64i8 checked earlier. Then split the input and make two pmovmskbs.
45128     if (Subtarget.hasAVX512()) {
45129       if (Subtarget.hasBWI())
45130         return SDValue();
45131       SExtVT = MVT::v64i8;
45132       break;
45133     }
45134     // Split if this is a <64 x i8> comparison result.
45135     if (checkBitcastSrcVectorSize(Src, 512, false)) {
45136       SExtVT = MVT::v64i8;
45137       break;
45138     }
45139     return SDValue();
45140   };
45141 
45142   SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
45143                             : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
45144 
45145   if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
45146     V = getPMOVMSKB(DL, V, DAG, Subtarget);
45147   } else {
45148     if (SExtVT == MVT::v8i16) {
45149       V = widenSubVector(V, false, Subtarget, DAG, DL, 256);
45150       V = DAG.getNode(ISD::TRUNCATE, DL, MVT::v16i8, V);
45151     }
45152     V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
45153   }
45154 
45155   EVT IntVT =
45156       EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
45157   V = DAG.getZExtOrTrunc(V, DL, IntVT);
45158   return DAG.getBitcast(VT, V);
45159 }
45160 
45161 // Convert a vXi1 constant build vector to the same width scalar integer.
45162 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
45163   EVT SrcVT = Op.getValueType();
45164   assert(SrcVT.getVectorElementType() == MVT::i1 &&
45165          "Expected a vXi1 vector");
45166   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
45167          "Expected a constant build vector");
45168 
45169   APInt Imm(SrcVT.getVectorNumElements(), 0);
45170   for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
45171     SDValue In = Op.getOperand(Idx);
45172     if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
45173       Imm.setBit(Idx);
45174   }
45175   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
45176   return DAG.getConstant(Imm, SDLoc(Op), IntVT);
45177 }
45178 
45179 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
45180                                            TargetLowering::DAGCombinerInfo &DCI,
45181                                            const X86Subtarget &Subtarget) {
45182   assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
45183 
45184   if (!DCI.isBeforeLegalizeOps())
45185     return SDValue();
45186 
45187   // Only do this if we have k-registers.
45188   if (!Subtarget.hasAVX512())
45189     return SDValue();
45190 
45191   EVT DstVT = N->getValueType(0);
45192   SDValue Op = N->getOperand(0);
45193   EVT SrcVT = Op.getValueType();
45194 
45195   if (!Op.hasOneUse())
45196     return SDValue();
45197 
45198   // Look for logic ops.
45199   if (Op.getOpcode() != ISD::AND &&
45200       Op.getOpcode() != ISD::OR &&
45201       Op.getOpcode() != ISD::XOR)
45202     return SDValue();
45203 
45204   // Make sure we have a bitcast between mask registers and a scalar type.
45205   if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
45206         DstVT.isScalarInteger()) &&
45207       !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
45208         SrcVT.isScalarInteger()))
45209     return SDValue();
45210 
45211   SDValue LHS = Op.getOperand(0);
45212   SDValue RHS = Op.getOperand(1);
45213 
45214   if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
45215       LHS.getOperand(0).getValueType() == DstVT)
45216     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
45217                        DAG.getBitcast(DstVT, RHS));
45218 
45219   if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
45220       RHS.getOperand(0).getValueType() == DstVT)
45221     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
45222                        DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
45223 
45224   // If the RHS is a vXi1 build vector, this is a good reason to flip too.
45225   // Most of these have to move a constant from the scalar domain anyway.
45226   if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
45227     RHS = combinevXi1ConstantToInteger(RHS, DAG);
45228     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
45229                        DAG.getBitcast(DstVT, LHS), RHS);
45230   }
45231 
45232   return SDValue();
45233 }
45234 
45235 static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
45236                                     const X86Subtarget &Subtarget) {
45237   SDLoc DL(BV);
45238   unsigned NumElts = BV->getNumOperands();
45239   SDValue Splat = BV->getSplatValue();
45240 
45241   // Build MMX element from integer GPR or SSE float values.
45242   auto CreateMMXElement = [&](SDValue V) {
45243     if (V.isUndef())
45244       return DAG.getUNDEF(MVT::x86mmx);
45245     if (V.getValueType().isFloatingPoint()) {
45246       if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
45247         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
45248         V = DAG.getBitcast(MVT::v2i64, V);
45249         return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
45250       }
45251       V = DAG.getBitcast(MVT::i32, V);
45252     } else {
45253       V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
45254     }
45255     return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
45256   };
45257 
45258   // Convert build vector ops to MMX data in the bottom elements.
45259   SmallVector<SDValue, 8> Ops;
45260 
45261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45262 
45263   // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
45264   if (Splat) {
45265     if (Splat.isUndef())
45266       return DAG.getUNDEF(MVT::x86mmx);
45267 
45268     Splat = CreateMMXElement(Splat);
45269 
45270     if (Subtarget.hasSSE1()) {
45271       // Unpack v8i8 to splat i8 elements to lowest 16-bits.
45272       if (NumElts == 8)
45273         Splat = DAG.getNode(
45274             ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
45275             DAG.getTargetConstant(Intrinsic::x86_mmx_punpcklbw, DL,
45276                                   TLI.getPointerTy(DAG.getDataLayout())),
45277             Splat, Splat);
45278 
45279       // Use PSHUFW to repeat 16-bit elements.
45280       unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
45281       return DAG.getNode(
45282           ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
45283           DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL,
45284                                 TLI.getPointerTy(DAG.getDataLayout())),
45285           Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
45286     }
45287     Ops.append(NumElts, Splat);
45288   } else {
45289     for (unsigned i = 0; i != NumElts; ++i)
45290       Ops.push_back(CreateMMXElement(BV->getOperand(i)));
45291   }
45292 
45293   // Use tree of PUNPCKLs to build up general MMX vector.
45294   while (Ops.size() > 1) {
45295     unsigned NumOps = Ops.size();
45296     unsigned IntrinOp =
45297         (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
45298                      : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
45299                                     : Intrinsic::x86_mmx_punpcklbw));
45300     SDValue Intrin = DAG.getTargetConstant(
45301         IntrinOp, DL, TLI.getPointerTy(DAG.getDataLayout()));
45302     for (unsigned i = 0; i != NumOps; i += 2)
45303       Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
45304                                Ops[i], Ops[i + 1]);
45305     Ops.resize(NumOps / 2);
45306   }
45307 
45308   return Ops[0];
45309 }
45310 
45311 // Recursive function that attempts to find if a bool vector node was originally
45312 // a vector/float/double that got truncated/extended/bitcast to/from a scalar
45313 // integer. If so, replace the scalar ops with bool vector equivalents back down
45314 // the chain.
45315 static SDValue combineBitcastToBoolVector(EVT VT, SDValue V, const SDLoc &DL,
45316                                           SelectionDAG &DAG,
45317                                           const X86Subtarget &Subtarget) {
45318   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45319   unsigned Opc = V.getOpcode();
45320   switch (Opc) {
45321   case ISD::BITCAST: {
45322     // Bitcast from a vector/float/double, we can cheaply bitcast to VT.
45323     SDValue Src = V.getOperand(0);
45324     EVT SrcVT = Src.getValueType();
45325     if (SrcVT.isVector() || SrcVT.isFloatingPoint())
45326       return DAG.getBitcast(VT, Src);
45327     break;
45328   }
45329   case ISD::TRUNCATE: {
45330     // If we find a suitable source, a truncated scalar becomes a subvector.
45331     SDValue Src = V.getOperand(0);
45332     EVT NewSrcVT =
45333         EVT::getVectorVT(*DAG.getContext(), MVT::i1, Src.getValueSizeInBits());
45334     if (TLI.isTypeLegal(NewSrcVT))
45335       if (SDValue N0 =
45336               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
45337         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N0,
45338                            DAG.getIntPtrConstant(0, DL));
45339     break;
45340   }
45341   case ISD::ANY_EXTEND:
45342   case ISD::ZERO_EXTEND: {
45343     // If we find a suitable source, an extended scalar becomes a subvector.
45344     SDValue Src = V.getOperand(0);
45345     EVT NewSrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
45346                                     Src.getScalarValueSizeInBits());
45347     if (TLI.isTypeLegal(NewSrcVT))
45348       if (SDValue N0 =
45349               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
45350         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
45351                            Opc == ISD::ANY_EXTEND ? DAG.getUNDEF(VT)
45352                                                   : DAG.getConstant(0, DL, VT),
45353                            N0, DAG.getIntPtrConstant(0, DL));
45354     break;
45355   }
45356   case ISD::OR: {
45357     // If we find suitable sources, we can just move an OR to the vector domain.
45358     SDValue Src0 = V.getOperand(0);
45359     SDValue Src1 = V.getOperand(1);
45360     if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
45361       if (SDValue N1 = combineBitcastToBoolVector(VT, Src1, DL, DAG, Subtarget))
45362         return DAG.getNode(Opc, DL, VT, N0, N1);
45363     break;
45364   }
45365   case ISD::SHL: {
45366     // If we find a suitable source, a SHL becomes a KSHIFTL.
45367     SDValue Src0 = V.getOperand(0);
45368     if ((VT == MVT::v8i1 && !Subtarget.hasDQI()) ||
45369         ((VT == MVT::v32i1 || VT == MVT::v64i1) && !Subtarget.hasBWI()))
45370       break;
45371 
45372     if (auto *Amt = dyn_cast<ConstantSDNode>(V.getOperand(1)))
45373       if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
45374         return DAG.getNode(
45375             X86ISD::KSHIFTL, DL, VT, N0,
45376             DAG.getTargetConstant(Amt->getZExtValue(), DL, MVT::i8));
45377     break;
45378   }
45379   }
45380   return SDValue();
45381 }
45382 
45383 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
45384                               TargetLowering::DAGCombinerInfo &DCI,
45385                               const X86Subtarget &Subtarget) {
45386   SDValue N0 = N->getOperand(0);
45387   EVT VT = N->getValueType(0);
45388   EVT SrcVT = N0.getValueType();
45389   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45390 
45391   // Try to match patterns such as
45392   // (i16 bitcast (v16i1 x))
45393   // ->
45394   // (i16 movmsk (16i8 sext (v16i1 x)))
45395   // before the setcc result is scalarized on subtargets that don't have legal
45396   // vxi1 types.
45397   if (DCI.isBeforeLegalize()) {
45398     SDLoc dl(N);
45399     if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
45400       return V;
45401 
45402     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
45403     // type, widen both sides to avoid a trip through memory.
45404     if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
45405         Subtarget.hasAVX512()) {
45406       N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
45407       N0 = DAG.getBitcast(MVT::v8i1, N0);
45408       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
45409                          DAG.getIntPtrConstant(0, dl));
45410     }
45411 
45412     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
45413     // type, widen both sides to avoid a trip through memory.
45414     if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
45415         Subtarget.hasAVX512()) {
45416       // Use zeros for the widening if we already have some zeroes. This can
45417       // allow SimplifyDemandedBits to remove scalar ANDs that may be down
45418       // stream of this.
45419       // FIXME: It might make sense to detect a concat_vectors with a mix of
45420       // zeroes and undef and turn it into insert_subvector for i1 vectors as
45421       // a separate combine. What we can't do is canonicalize the operands of
45422       // such a concat or we'll get into a loop with SimplifyDemandedBits.
45423       if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
45424         SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
45425         if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
45426           SrcVT = LastOp.getValueType();
45427           unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
45428           SmallVector<SDValue, 4> Ops(N0->op_begin(), N0->op_end());
45429           Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
45430           N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
45431           N0 = DAG.getBitcast(MVT::i8, N0);
45432           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
45433         }
45434       }
45435 
45436       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
45437       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
45438       Ops[0] = N0;
45439       N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
45440       N0 = DAG.getBitcast(MVT::i8, N0);
45441       return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
45442     }
45443   } else {
45444     // If we're bitcasting from iX to vXi1, see if the integer originally
45445     // began as a vXi1 and whether we can remove the bitcast entirely.
45446     if (VT.isVector() && VT.getScalarType() == MVT::i1 &&
45447         SrcVT.isScalarInteger() && TLI.isTypeLegal(VT)) {
45448       if (SDValue V =
45449               combineBitcastToBoolVector(VT, N0, SDLoc(N), DAG, Subtarget))
45450         return V;
45451     }
45452   }
45453 
45454   // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
45455   // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
45456   // due to insert_subvector legalization on KNL. By promoting the copy to i16
45457   // we can help with known bits propagation from the vXi1 domain to the
45458   // scalar domain.
45459   if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
45460       !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
45461       N0.getOperand(0).getValueType() == MVT::v16i1 &&
45462       isNullConstant(N0.getOperand(1)))
45463     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
45464                        DAG.getBitcast(MVT::i16, N0.getOperand(0)));
45465 
45466   // Canonicalize (bitcast (vbroadcast_load)) so that the output of the bitcast
45467   // and the vbroadcast_load are both integer or both fp. In some cases this
45468   // will remove the bitcast entirely.
45469   if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
45470        VT.isFloatingPoint() != SrcVT.isFloatingPoint() && VT.isVector()) {
45471     auto *BCast = cast<MemIntrinsicSDNode>(N0);
45472     unsigned SrcVTSize = SrcVT.getScalarSizeInBits();
45473     unsigned MemSize = BCast->getMemoryVT().getScalarSizeInBits();
45474     // Don't swap i8/i16 since don't have fp types that size.
45475     if (MemSize >= 32) {
45476       MVT MemVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(MemSize)
45477                                        : MVT::getIntegerVT(MemSize);
45478       MVT LoadVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(SrcVTSize)
45479                                         : MVT::getIntegerVT(SrcVTSize);
45480       LoadVT = MVT::getVectorVT(LoadVT, SrcVT.getVectorNumElements());
45481 
45482       SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
45483       SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
45484       SDValue ResNode =
45485           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
45486                                   MemVT, BCast->getMemOperand());
45487       DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
45488       return DAG.getBitcast(VT, ResNode);
45489     }
45490   }
45491 
45492   // Since MMX types are special and don't usually play with other vector types,
45493   // it's better to handle them early to be sure we emit efficient code by
45494   // avoiding store-load conversions.
45495   if (VT == MVT::x86mmx) {
45496     // Detect MMX constant vectors.
45497     APInt UndefElts;
45498     SmallVector<APInt, 1> EltBits;
45499     if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
45500       SDLoc DL(N0);
45501       // Handle zero-extension of i32 with MOVD.
45502       if (EltBits[0].countl_zero() >= 32)
45503         return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
45504                            DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
45505       // Else, bitcast to a double.
45506       // TODO - investigate supporting sext 32-bit immediates on x86_64.
45507       APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
45508       return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
45509     }
45510 
45511     // Detect bitcasts to x86mmx low word.
45512     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
45513         (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
45514         N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
45515       bool LowUndef = true, AllUndefOrZero = true;
45516       for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
45517         SDValue Op = N0.getOperand(i);
45518         LowUndef &= Op.isUndef() || (i >= e/2);
45519         AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
45520       }
45521       if (AllUndefOrZero) {
45522         SDValue N00 = N0.getOperand(0);
45523         SDLoc dl(N00);
45524         N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
45525                        : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
45526         return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
45527       }
45528     }
45529 
45530     // Detect bitcasts of 64-bit build vectors and convert to a
45531     // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
45532     // lowest element.
45533     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
45534         (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
45535          SrcVT == MVT::v8i8))
45536       return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
45537 
45538     // Detect bitcasts between element or subvector extraction to x86mmx.
45539     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
45540          N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
45541         isNullConstant(N0.getOperand(1))) {
45542       SDValue N00 = N0.getOperand(0);
45543       if (N00.getValueType().is128BitVector())
45544         return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
45545                            DAG.getBitcast(MVT::v2i64, N00));
45546     }
45547 
45548     // Detect bitcasts from FP_TO_SINT to x86mmx.
45549     if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
45550       SDLoc DL(N0);
45551       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
45552                                 DAG.getUNDEF(MVT::v2i32));
45553       return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
45554                          DAG.getBitcast(MVT::v2i64, Res));
45555     }
45556   }
45557 
45558   // Try to remove a bitcast of constant vXi1 vector. We have to legalize
45559   // most of these to scalar anyway.
45560   if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
45561       SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
45562       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
45563     return combinevXi1ConstantToInteger(N0, DAG);
45564   }
45565 
45566   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
45567       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
45568       isa<ConstantSDNode>(N0)) {
45569     auto *C = cast<ConstantSDNode>(N0);
45570     if (C->isAllOnes())
45571       return DAG.getConstant(1, SDLoc(N0), VT);
45572     if (C->isZero())
45573       return DAG.getConstant(0, SDLoc(N0), VT);
45574   }
45575 
45576   // Look for MOVMSK that is maybe truncated and then bitcasted to vXi1.
45577   // Turn it into a sign bit compare that produces a k-register. This avoids
45578   // a trip through a GPR.
45579   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
45580       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
45581       isPowerOf2_32(VT.getVectorNumElements())) {
45582     unsigned NumElts = VT.getVectorNumElements();
45583     SDValue Src = N0;
45584 
45585     // Peek through truncate.
45586     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
45587       Src = N0.getOperand(0);
45588 
45589     if (Src.getOpcode() == X86ISD::MOVMSK && Src.hasOneUse()) {
45590       SDValue MovmskIn = Src.getOperand(0);
45591       MVT MovmskVT = MovmskIn.getSimpleValueType();
45592       unsigned MovMskElts = MovmskVT.getVectorNumElements();
45593 
45594       // We allow extra bits of the movmsk to be used since they are known zero.
45595       // We can't convert a VPMOVMSKB without avx512bw.
45596       if (MovMskElts <= NumElts &&
45597           (Subtarget.hasBWI() || MovmskVT.getVectorElementType() != MVT::i8)) {
45598         EVT IntVT = EVT(MovmskVT).changeVectorElementTypeToInteger();
45599         MovmskIn = DAG.getBitcast(IntVT, MovmskIn);
45600         SDLoc dl(N);
45601         MVT CmpVT = MVT::getVectorVT(MVT::i1, MovMskElts);
45602         SDValue Cmp = DAG.getSetCC(dl, CmpVT, MovmskIn,
45603                                    DAG.getConstant(0, dl, IntVT), ISD::SETLT);
45604         if (EVT(CmpVT) == VT)
45605           return Cmp;
45606 
45607         // Pad with zeroes up to original VT to replace the zeroes that were
45608         // being used from the MOVMSK.
45609         unsigned NumConcats = NumElts / MovMskElts;
45610         SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, CmpVT));
45611         Ops[0] = Cmp;
45612         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Ops);
45613       }
45614     }
45615   }
45616 
45617   // Try to remove bitcasts from input and output of mask arithmetic to
45618   // remove GPR<->K-register crossings.
45619   if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
45620     return V;
45621 
45622   // Convert a bitcasted integer logic operation that has one bitcasted
45623   // floating-point operand into a floating-point logic operation. This may
45624   // create a load of a constant, but that is cheaper than materializing the
45625   // constant in an integer register and transferring it to an SSE register or
45626   // transferring the SSE operand to integer register and back.
45627   unsigned FPOpcode;
45628   switch (N0.getOpcode()) {
45629     case ISD::AND: FPOpcode = X86ISD::FAND; break;
45630     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
45631     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
45632     default: return SDValue();
45633   }
45634 
45635   // Check if we have a bitcast from another integer type as well.
45636   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
45637         (Subtarget.hasSSE2() && VT == MVT::f64) ||
45638         (Subtarget.hasFP16() && VT == MVT::f16) ||
45639         (Subtarget.hasSSE2() && VT.isInteger() && VT.isVector() &&
45640          TLI.isTypeLegal(VT))))
45641     return SDValue();
45642 
45643   SDValue LogicOp0 = N0.getOperand(0);
45644   SDValue LogicOp1 = N0.getOperand(1);
45645   SDLoc DL0(N0);
45646 
45647   // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
45648   if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
45649       LogicOp0.hasOneUse() && LogicOp0.getOperand(0).hasOneUse() &&
45650       LogicOp0.getOperand(0).getValueType() == VT &&
45651       !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
45652     SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
45653     unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
45654     return DAG.getNode(Opcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
45655   }
45656   // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
45657   if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
45658       LogicOp1.hasOneUse() && LogicOp1.getOperand(0).hasOneUse() &&
45659       LogicOp1.getOperand(0).getValueType() == VT &&
45660       !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
45661     SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
45662     unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
45663     return DAG.getNode(Opcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
45664   }
45665 
45666   return SDValue();
45667 }
45668 
45669 // (mul (zext a), (sext, b))
45670 static bool detectExtMul(SelectionDAG &DAG, const SDValue &Mul, SDValue &Op0,
45671                          SDValue &Op1) {
45672   Op0 = Mul.getOperand(0);
45673   Op1 = Mul.getOperand(1);
45674 
45675   // The operand1 should be signed extend
45676   if (Op0.getOpcode() == ISD::SIGN_EXTEND)
45677     std::swap(Op0, Op1);
45678 
45679   auto IsFreeTruncation = [](SDValue &Op) -> bool {
45680     if ((Op.getOpcode() == ISD::ZERO_EXTEND ||
45681          Op.getOpcode() == ISD::SIGN_EXTEND) &&
45682         Op.getOperand(0).getScalarValueSizeInBits() <= 8)
45683       return true;
45684 
45685     auto *BV = dyn_cast<BuildVectorSDNode>(Op);
45686     return (BV && BV->isConstant());
45687   };
45688 
45689   // (dpbusd (zext a), (sext, b)). Since the first operand should be unsigned
45690   // value, we need to check Op0 is zero extended value. Op1 should be signed
45691   // value, so we just check the signed bits.
45692   if ((IsFreeTruncation(Op0) &&
45693        DAG.computeKnownBits(Op0).countMaxActiveBits() <= 8) &&
45694       (IsFreeTruncation(Op1) && DAG.ComputeMaxSignificantBits(Op1) <= 8))
45695     return true;
45696 
45697   return false;
45698 }
45699 
45700 // Given a ABS node, detect the following pattern:
45701 // (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
45702 // This is useful as it is the input into a SAD pattern.
45703 static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
45704   SDValue AbsOp1 = Abs->getOperand(0);
45705   if (AbsOp1.getOpcode() != ISD::SUB)
45706     return false;
45707 
45708   Op0 = AbsOp1.getOperand(0);
45709   Op1 = AbsOp1.getOperand(1);
45710 
45711   // Check if the operands of the sub are zero-extended from vectors of i8.
45712   if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
45713       Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
45714       Op1.getOpcode() != ISD::ZERO_EXTEND ||
45715       Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
45716     return false;
45717 
45718   return true;
45719 }
45720 
45721 static SDValue createVPDPBUSD(SelectionDAG &DAG, SDValue LHS, SDValue RHS,
45722                               unsigned &LogBias, const SDLoc &DL,
45723                               const X86Subtarget &Subtarget) {
45724   // Extend or truncate to MVT::i8 first.
45725   MVT Vi8VT =
45726       MVT::getVectorVT(MVT::i8, LHS.getValueType().getVectorElementCount());
45727   LHS = DAG.getZExtOrTrunc(LHS, DL, Vi8VT);
45728   RHS = DAG.getSExtOrTrunc(RHS, DL, Vi8VT);
45729 
45730   // VPDPBUSD(<16 x i32>C, <16 x i8>A, <16 x i8>B). For each dst element
45731   // C[0] = C[0] + A[0]B[0] + A[1]B[1] + A[2]B[2] + A[3]B[3].
45732   // The src A, B element type is i8, but the dst C element type is i32.
45733   // When we calculate the reduce stage, we use src vector type vXi8 for it
45734   // so we need logbias 2 to avoid extra 2 stages.
45735   LogBias = 2;
45736 
45737   unsigned RegSize = std::max(128u, (unsigned)Vi8VT.getSizeInBits());
45738   if (Subtarget.hasVNNI() && !Subtarget.hasVLX())
45739     RegSize = std::max(512u, RegSize);
45740 
45741   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
45742   // fill in the missing vector elements with 0.
45743   unsigned NumConcat = RegSize / Vi8VT.getSizeInBits();
45744   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, Vi8VT));
45745   Ops[0] = LHS;
45746   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
45747   SDValue DpOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
45748   Ops[0] = RHS;
45749   SDValue DpOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
45750 
45751   // Actually build the DotProduct, split as 256/512 bits for
45752   // AVXVNNI/AVX512VNNI.
45753   auto DpBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45754                        ArrayRef<SDValue> Ops) {
45755     MVT VT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
45756     return DAG.getNode(X86ISD::VPDPBUSD, DL, VT, Ops);
45757   };
45758   MVT DpVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
45759   SDValue Zero = DAG.getConstant(0, DL, DpVT);
45760 
45761   return SplitOpsAndApply(DAG, Subtarget, DL, DpVT, {Zero, DpOp0, DpOp1},
45762                           DpBuilder, false);
45763 }
45764 
45765 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
45766 // to these zexts.
45767 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
45768                             const SDValue &Zext1, const SDLoc &DL,
45769                             const X86Subtarget &Subtarget) {
45770   // Find the appropriate width for the PSADBW.
45771   EVT InVT = Zext0.getOperand(0).getValueType();
45772   unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
45773 
45774   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
45775   // fill in the missing vector elements with 0.
45776   unsigned NumConcat = RegSize / InVT.getSizeInBits();
45777   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
45778   Ops[0] = Zext0.getOperand(0);
45779   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
45780   SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
45781   Ops[0] = Zext1.getOperand(0);
45782   SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
45783 
45784   // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
45785   auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45786                           ArrayRef<SDValue> Ops) {
45787     MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
45788     return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
45789   };
45790   MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
45791   return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
45792                           PSADBWBuilder);
45793 }
45794 
45795 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
45796 // PHMINPOSUW.
45797 static SDValue combineMinMaxReduction(SDNode *Extract, SelectionDAG &DAG,
45798                                       const X86Subtarget &Subtarget) {
45799   // Bail without SSE41.
45800   if (!Subtarget.hasSSE41())
45801     return SDValue();
45802 
45803   EVT ExtractVT = Extract->getValueType(0);
45804   if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
45805     return SDValue();
45806 
45807   // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
45808   ISD::NodeType BinOp;
45809   SDValue Src = DAG.matchBinOpReduction(
45810       Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
45811   if (!Src)
45812     return SDValue();
45813 
45814   EVT SrcVT = Src.getValueType();
45815   EVT SrcSVT = SrcVT.getScalarType();
45816   if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
45817     return SDValue();
45818 
45819   SDLoc DL(Extract);
45820   SDValue MinPos = Src;
45821 
45822   // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
45823   while (SrcVT.getSizeInBits() > 128) {
45824     SDValue Lo, Hi;
45825     std::tie(Lo, Hi) = splitVector(MinPos, DAG, DL);
45826     SrcVT = Lo.getValueType();
45827     MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
45828   }
45829   assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
45830           (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
45831          "Unexpected value type");
45832 
45833   // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
45834   // to flip the value accordingly.
45835   SDValue Mask;
45836   unsigned MaskEltsBits = ExtractVT.getSizeInBits();
45837   if (BinOp == ISD::SMAX)
45838     Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
45839   else if (BinOp == ISD::SMIN)
45840     Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
45841   else if (BinOp == ISD::UMAX)
45842     Mask = DAG.getAllOnesConstant(DL, SrcVT);
45843 
45844   if (Mask)
45845     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
45846 
45847   // For v16i8 cases we need to perform UMIN on pairs of byte elements,
45848   // shuffling each upper element down and insert zeros. This means that the
45849   // v16i8 UMIN will leave the upper element as zero, performing zero-extension
45850   // ready for the PHMINPOS.
45851   if (ExtractVT == MVT::i8) {
45852     SDValue Upper = DAG.getVectorShuffle(
45853         SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
45854         {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
45855     MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
45856   }
45857 
45858   // Perform the PHMINPOS on a v8i16 vector,
45859   MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
45860   MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
45861   MinPos = DAG.getBitcast(SrcVT, MinPos);
45862 
45863   if (Mask)
45864     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
45865 
45866   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
45867                      DAG.getIntPtrConstant(0, DL));
45868 }
45869 
45870 // Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
45871 static SDValue combinePredicateReduction(SDNode *Extract, SelectionDAG &DAG,
45872                                          const X86Subtarget &Subtarget) {
45873   // Bail without SSE2.
45874   if (!Subtarget.hasSSE2())
45875     return SDValue();
45876 
45877   EVT ExtractVT = Extract->getValueType(0);
45878   unsigned BitWidth = ExtractVT.getSizeInBits();
45879   if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
45880       ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
45881     return SDValue();
45882 
45883   // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
45884   ISD::NodeType BinOp;
45885   SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
45886   if (!Match && ExtractVT == MVT::i1)
45887     Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
45888   if (!Match)
45889     return SDValue();
45890 
45891   // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
45892   // which we can't support here for now.
45893   if (Match.getScalarValueSizeInBits() != BitWidth)
45894     return SDValue();
45895 
45896   SDValue Movmsk;
45897   SDLoc DL(Extract);
45898   EVT MatchVT = Match.getValueType();
45899   unsigned NumElts = MatchVT.getVectorNumElements();
45900   unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
45901   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45902   LLVMContext &Ctx = *DAG.getContext();
45903 
45904   if (ExtractVT == MVT::i1) {
45905     // Special case for (pre-legalization) vXi1 reductions.
45906     if (NumElts > 64 || !isPowerOf2_32(NumElts))
45907       return SDValue();
45908     if (Match.getOpcode() == ISD::SETCC) {
45909       ISD::CondCode CC = cast<CondCodeSDNode>(Match.getOperand(2))->get();
45910       if ((BinOp == ISD::AND && CC == ISD::CondCode::SETEQ) ||
45911           (BinOp == ISD::OR && CC == ISD::CondCode::SETNE)) {
45912         // For all_of(setcc(x,y,eq)) - use (iX)x == (iX)y.
45913         // For any_of(setcc(x,y,ne)) - use (iX)x != (iX)y.
45914         X86::CondCode X86CC;
45915         SDValue LHS = DAG.getFreeze(Match.getOperand(0));
45916         SDValue RHS = DAG.getFreeze(Match.getOperand(1));
45917         APInt Mask = APInt::getAllOnes(LHS.getScalarValueSizeInBits());
45918         if (SDValue V = LowerVectorAllEqual(DL, LHS, RHS, CC, Mask, Subtarget,
45919                                             DAG, X86CC))
45920           return DAG.getNode(ISD::TRUNCATE, DL, ExtractVT,
45921                              getSETCC(X86CC, V, DL, DAG));
45922       }
45923     }
45924     if (TLI.isTypeLegal(MatchVT)) {
45925       // If this is a legal AVX512 predicate type then we can just bitcast.
45926       EVT MovmskVT = EVT::getIntegerVT(Ctx, NumElts);
45927       Movmsk = DAG.getBitcast(MovmskVT, Match);
45928     } else {
45929       // Use combineBitcastvxi1 to create the MOVMSK.
45930       while (NumElts > MaxElts) {
45931         SDValue Lo, Hi;
45932         std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
45933         Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
45934         NumElts /= 2;
45935       }
45936       EVT MovmskVT = EVT::getIntegerVT(Ctx, NumElts);
45937       Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
45938     }
45939     if (!Movmsk)
45940       return SDValue();
45941     Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
45942   } else {
45943     // FIXME: Better handling of k-registers or 512-bit vectors?
45944     unsigned MatchSizeInBits = Match.getValueSizeInBits();
45945     if (!(MatchSizeInBits == 128 ||
45946           (MatchSizeInBits == 256 && Subtarget.hasAVX())))
45947       return SDValue();
45948 
45949     // Make sure this isn't a vector of 1 element. The perf win from using
45950     // MOVMSK diminishes with less elements in the reduction, but it is
45951     // generally better to get the comparison over to the GPRs as soon as
45952     // possible to reduce the number of vector ops.
45953     if (Match.getValueType().getVectorNumElements() < 2)
45954       return SDValue();
45955 
45956     // Check that we are extracting a reduction of all sign bits.
45957     if (DAG.ComputeNumSignBits(Match) != BitWidth)
45958       return SDValue();
45959 
45960     if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
45961       SDValue Lo, Hi;
45962       std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
45963       Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
45964       MatchSizeInBits = Match.getValueSizeInBits();
45965     }
45966 
45967     // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
45968     MVT MaskSrcVT;
45969     if (64 == BitWidth || 32 == BitWidth)
45970       MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
45971                                    MatchSizeInBits / BitWidth);
45972     else
45973       MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
45974 
45975     SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
45976     Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
45977     NumElts = MaskSrcVT.getVectorNumElements();
45978   }
45979   assert((NumElts <= 32 || NumElts == 64) &&
45980          "Not expecting more than 64 elements");
45981 
45982   MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
45983   if (BinOp == ISD::XOR) {
45984     // parity -> (PARITY(MOVMSK X))
45985     SDValue Result = DAG.getNode(ISD::PARITY, DL, CmpVT, Movmsk);
45986     return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
45987   }
45988 
45989   SDValue CmpC;
45990   ISD::CondCode CondCode;
45991   if (BinOp == ISD::OR) {
45992     // any_of -> MOVMSK != 0
45993     CmpC = DAG.getConstant(0, DL, CmpVT);
45994     CondCode = ISD::CondCode::SETNE;
45995   } else {
45996     // all_of -> MOVMSK == ((1 << NumElts) - 1)
45997     CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
45998                            DL, CmpVT);
45999     CondCode = ISD::CondCode::SETEQ;
46000   }
46001 
46002   // The setcc produces an i8 of 0/1, so extend that to the result width and
46003   // negate to get the final 0/-1 mask value.
46004   EVT SetccVT = TLI.getSetCCResultType(DAG.getDataLayout(), Ctx, CmpVT);
46005   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
46006   SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
46007   SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
46008   return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
46009 }
46010 
46011 static SDValue combineVPDPBUSDPattern(SDNode *Extract, SelectionDAG &DAG,
46012                                       const X86Subtarget &Subtarget) {
46013   if (!Subtarget.hasVNNI() && !Subtarget.hasAVXVNNI())
46014     return SDValue();
46015 
46016   EVT ExtractVT = Extract->getValueType(0);
46017   // Verify the type we're extracting is i32, as the output element type of
46018   // vpdpbusd is i32.
46019   if (ExtractVT != MVT::i32)
46020     return SDValue();
46021 
46022   EVT VT = Extract->getOperand(0).getValueType();
46023   if (!isPowerOf2_32(VT.getVectorNumElements()))
46024     return SDValue();
46025 
46026   // Match shuffle + add pyramid.
46027   ISD::NodeType BinOp;
46028   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
46029 
46030   // We can't combine to vpdpbusd for zext, because each of the 4 multiplies
46031   // done by vpdpbusd compute a signed 16-bit product that will be sign extended
46032   // before adding into the accumulator.
46033   // TODO:
46034   // We also need to verify that the multiply has at least 2x the number of bits
46035   // of the input. We shouldn't match
46036   // (sign_extend (mul (vXi9 (zext (vXi8 X))), (vXi9 (zext (vXi8 Y)))).
46037   // if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND))
46038   //   Root = Root.getOperand(0);
46039 
46040   // If there was a match, we want Root to be a mul.
46041   if (!Root || Root.getOpcode() != ISD::MUL)
46042     return SDValue();
46043 
46044   // Check whether we have an extend and mul pattern
46045   SDValue LHS, RHS;
46046   if (!detectExtMul(DAG, Root, LHS, RHS))
46047     return SDValue();
46048 
46049   // Create the dot product instruction.
46050   SDLoc DL(Extract);
46051   unsigned StageBias;
46052   SDValue DP = createVPDPBUSD(DAG, LHS, RHS, StageBias, DL, Subtarget);
46053 
46054   // If the original vector was wider than 4 elements, sum over the results
46055   // in the DP vector.
46056   unsigned Stages = Log2_32(VT.getVectorNumElements());
46057   EVT DpVT = DP.getValueType();
46058 
46059   if (Stages > StageBias) {
46060     unsigned DpElems = DpVT.getVectorNumElements();
46061 
46062     for (unsigned i = Stages - StageBias; i > 0; --i) {
46063       SmallVector<int, 16> Mask(DpElems, -1);
46064       for (unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
46065         Mask[j] = MaskEnd + j;
46066 
46067       SDValue Shuffle =
46068           DAG.getVectorShuffle(DpVT, DL, DP, DAG.getUNDEF(DpVT), Mask);
46069       DP = DAG.getNode(ISD::ADD, DL, DpVT, DP, Shuffle);
46070     }
46071   }
46072 
46073   // Return the lowest ExtractSizeInBits bits.
46074   EVT ResVT =
46075       EVT::getVectorVT(*DAG.getContext(), ExtractVT,
46076                        DpVT.getSizeInBits() / ExtractVT.getSizeInBits());
46077   DP = DAG.getBitcast(ResVT, DP);
46078   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, DP,
46079                      Extract->getOperand(1));
46080 }
46081 
46082 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
46083                                       const X86Subtarget &Subtarget) {
46084   // PSADBW is only supported on SSE2 and up.
46085   if (!Subtarget.hasSSE2())
46086     return SDValue();
46087 
46088   EVT ExtractVT = Extract->getValueType(0);
46089   // Verify the type we're extracting is either i32 or i64.
46090   // FIXME: Could support other types, but this is what we have coverage for.
46091   if (ExtractVT != MVT::i32 && ExtractVT != MVT::i64)
46092     return SDValue();
46093 
46094   EVT VT = Extract->getOperand(0).getValueType();
46095   if (!isPowerOf2_32(VT.getVectorNumElements()))
46096     return SDValue();
46097 
46098   // Match shuffle + add pyramid.
46099   ISD::NodeType BinOp;
46100   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
46101 
46102   // The operand is expected to be zero extended from i8
46103   // (verified in detectZextAbsDiff).
46104   // In order to convert to i64 and above, additional any/zero/sign
46105   // extend is expected.
46106   // The zero extend from 32 bit has no mathematical effect on the result.
46107   // Also the sign extend is basically zero extend
46108   // (extends the sign bit which is zero).
46109   // So it is correct to skip the sign/zero extend instruction.
46110   if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
46111                Root.getOpcode() == ISD::ZERO_EXTEND ||
46112                Root.getOpcode() == ISD::ANY_EXTEND))
46113     Root = Root.getOperand(0);
46114 
46115   // If there was a match, we want Root to be a select that is the root of an
46116   // abs-diff pattern.
46117   if (!Root || Root.getOpcode() != ISD::ABS)
46118     return SDValue();
46119 
46120   // Check whether we have an abs-diff pattern feeding into the select.
46121   SDValue Zext0, Zext1;
46122   if (!detectZextAbsDiff(Root, Zext0, Zext1))
46123     return SDValue();
46124 
46125   // Create the SAD instruction.
46126   SDLoc DL(Extract);
46127   SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
46128 
46129   // If the original vector was wider than 8 elements, sum over the results
46130   // in the SAD vector.
46131   unsigned Stages = Log2_32(VT.getVectorNumElements());
46132   EVT SadVT = SAD.getValueType();
46133   if (Stages > 3) {
46134     unsigned SadElems = SadVT.getVectorNumElements();
46135 
46136     for(unsigned i = Stages - 3; i > 0; --i) {
46137       SmallVector<int, 16> Mask(SadElems, -1);
46138       for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
46139         Mask[j] = MaskEnd + j;
46140 
46141       SDValue Shuffle =
46142           DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
46143       SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
46144     }
46145   }
46146 
46147   unsigned ExtractSizeInBits = ExtractVT.getSizeInBits();
46148   // Return the lowest ExtractSizeInBits bits.
46149   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), ExtractVT,
46150                                SadVT.getSizeInBits() / ExtractSizeInBits);
46151   SAD = DAG.getBitcast(ResVT, SAD);
46152   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, SAD,
46153                      Extract->getOperand(1));
46154 }
46155 
46156 // Attempt to peek through a target shuffle and extract the scalar from the
46157 // source.
46158 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
46159                                          TargetLowering::DAGCombinerInfo &DCI,
46160                                          const X86Subtarget &Subtarget) {
46161   if (DCI.isBeforeLegalizeOps())
46162     return SDValue();
46163 
46164   SDLoc dl(N);
46165   SDValue Src = N->getOperand(0);
46166   SDValue Idx = N->getOperand(1);
46167 
46168   EVT VT = N->getValueType(0);
46169   EVT SrcVT = Src.getValueType();
46170   EVT SrcSVT = SrcVT.getVectorElementType();
46171   unsigned SrcEltBits = SrcSVT.getSizeInBits();
46172   unsigned NumSrcElts = SrcVT.getVectorNumElements();
46173 
46174   // Don't attempt this for boolean mask vectors or unknown extraction indices.
46175   if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
46176     return SDValue();
46177 
46178   const APInt &IdxC = N->getConstantOperandAPInt(1);
46179   if (IdxC.uge(NumSrcElts))
46180     return SDValue();
46181 
46182   SDValue SrcBC = peekThroughBitcasts(Src);
46183 
46184   // Handle extract(bitcast(broadcast(scalar_value))).
46185   if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
46186     SDValue SrcOp = SrcBC.getOperand(0);
46187     EVT SrcOpVT = SrcOp.getValueType();
46188     if (SrcOpVT.isScalarInteger() && VT.isInteger() &&
46189         (SrcOpVT.getSizeInBits() % SrcEltBits) == 0) {
46190       unsigned Scale = SrcOpVT.getSizeInBits() / SrcEltBits;
46191       unsigned Offset = IdxC.urem(Scale) * SrcEltBits;
46192       // TODO support non-zero offsets.
46193       if (Offset == 0) {
46194         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, SrcVT.getScalarType());
46195         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, VT);
46196         return SrcOp;
46197       }
46198     }
46199   }
46200 
46201   // If we're extracting a single element from a broadcast load and there are
46202   // no other users, just create a single load.
46203   if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
46204     auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
46205     unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
46206     if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
46207         VT.getSizeInBits() == SrcBCWidth && SrcEltBits == SrcBCWidth) {
46208       SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
46209                                  MemIntr->getBasePtr(),
46210                                  MemIntr->getPointerInfo(),
46211                                  MemIntr->getOriginalAlign(),
46212                                  MemIntr->getMemOperand()->getFlags());
46213       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
46214       return Load;
46215     }
46216   }
46217 
46218   // Handle extract(bitcast(scalar_to_vector(scalar_value))) for integers.
46219   // TODO: Move to DAGCombine?
46220   if (SrcBC.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isInteger() &&
46221       SrcBC.getValueType().isInteger() &&
46222       (SrcBC.getScalarValueSizeInBits() % SrcEltBits) == 0 &&
46223       SrcBC.getScalarValueSizeInBits() ==
46224           SrcBC.getOperand(0).getValueSizeInBits()) {
46225     unsigned Scale = SrcBC.getScalarValueSizeInBits() / SrcEltBits;
46226     if (IdxC.ult(Scale)) {
46227       unsigned Offset = IdxC.getZExtValue() * SrcVT.getScalarSizeInBits();
46228       SDValue Scl = SrcBC.getOperand(0);
46229       EVT SclVT = Scl.getValueType();
46230       if (Offset) {
46231         Scl = DAG.getNode(ISD::SRL, dl, SclVT, Scl,
46232                           DAG.getShiftAmountConstant(Offset, SclVT, dl));
46233       }
46234       Scl = DAG.getZExtOrTrunc(Scl, dl, SrcVT.getScalarType());
46235       Scl = DAG.getZExtOrTrunc(Scl, dl, VT);
46236       return Scl;
46237     }
46238   }
46239 
46240   // Handle extract(truncate(x)) for 0'th index.
46241   // TODO: Treat this as a faux shuffle?
46242   // TODO: When can we use this for general indices?
46243   if (ISD::TRUNCATE == Src.getOpcode() && IdxC == 0 &&
46244       (SrcVT.getSizeInBits() % 128) == 0) {
46245     Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
46246     MVT ExtractVT = MVT::getVectorVT(SrcSVT.getSimpleVT(), 128 / SrcEltBits);
46247     return DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(ExtractVT, Src),
46248                        Idx);
46249   }
46250 
46251   // We can only legally extract other elements from 128-bit vectors and in
46252   // certain circumstances, depending on SSE-level.
46253   // TODO: Investigate float/double extraction if it will be just stored.
46254   auto GetLegalExtract = [&Subtarget, &DAG, &dl](SDValue Vec, EVT VecVT,
46255                                                  unsigned Idx) {
46256     EVT VecSVT = VecVT.getScalarType();
46257     if ((VecVT.is256BitVector() || VecVT.is512BitVector()) &&
46258         (VecSVT == MVT::i8 || VecSVT == MVT::i16 || VecSVT == MVT::i32 ||
46259          VecSVT == MVT::i64)) {
46260       unsigned EltSizeInBits = VecSVT.getSizeInBits();
46261       unsigned NumEltsPerLane = 128 / EltSizeInBits;
46262       unsigned LaneOffset = (Idx & ~(NumEltsPerLane - 1)) * EltSizeInBits;
46263       unsigned LaneIdx = LaneOffset / Vec.getScalarValueSizeInBits();
46264       VecVT = EVT::getVectorVT(*DAG.getContext(), VecSVT, NumEltsPerLane);
46265       Vec = extract128BitVector(Vec, LaneIdx, DAG, dl);
46266       Idx &= (NumEltsPerLane - 1);
46267     }
46268     if ((VecVT == MVT::v4i32 || VecVT == MVT::v2i64) &&
46269         ((Idx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
46270       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VecVT.getScalarType(),
46271                          DAG.getBitcast(VecVT, Vec),
46272                          DAG.getIntPtrConstant(Idx, dl));
46273     }
46274     if ((VecVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
46275         (VecVT == MVT::v16i8 && Subtarget.hasSSE41())) {
46276       unsigned OpCode = (VecVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
46277       return DAG.getNode(OpCode, dl, MVT::i32, DAG.getBitcast(VecVT, Vec),
46278                          DAG.getTargetConstant(Idx, dl, MVT::i8));
46279     }
46280     return SDValue();
46281   };
46282 
46283   // Resolve the target shuffle inputs and mask.
46284   SmallVector<int, 16> Mask;
46285   SmallVector<SDValue, 2> Ops;
46286   if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
46287     return SDValue();
46288 
46289   // Shuffle inputs must be the same size as the result.
46290   if (llvm::any_of(Ops, [SrcVT](SDValue Op) {
46291         return SrcVT.getSizeInBits() != Op.getValueSizeInBits();
46292       }))
46293     return SDValue();
46294 
46295   // Attempt to narrow/widen the shuffle mask to the correct size.
46296   if (Mask.size() != NumSrcElts) {
46297     if ((NumSrcElts % Mask.size()) == 0) {
46298       SmallVector<int, 16> ScaledMask;
46299       int Scale = NumSrcElts / Mask.size();
46300       narrowShuffleMaskElts(Scale, Mask, ScaledMask);
46301       Mask = std::move(ScaledMask);
46302     } else if ((Mask.size() % NumSrcElts) == 0) {
46303       // Simplify Mask based on demanded element.
46304       int ExtractIdx = (int)IdxC.getZExtValue();
46305       int Scale = Mask.size() / NumSrcElts;
46306       int Lo = Scale * ExtractIdx;
46307       int Hi = Scale * (ExtractIdx + 1);
46308       for (int i = 0, e = (int)Mask.size(); i != e; ++i)
46309         if (i < Lo || Hi <= i)
46310           Mask[i] = SM_SentinelUndef;
46311 
46312       SmallVector<int, 16> WidenedMask;
46313       while (Mask.size() > NumSrcElts &&
46314              canWidenShuffleElements(Mask, WidenedMask))
46315         Mask = std::move(WidenedMask);
46316     }
46317   }
46318 
46319   // If narrowing/widening failed, see if we can extract+zero-extend.
46320   int ExtractIdx;
46321   EVT ExtractVT;
46322   if (Mask.size() == NumSrcElts) {
46323     ExtractIdx = Mask[IdxC.getZExtValue()];
46324     ExtractVT = SrcVT;
46325   } else {
46326     unsigned Scale = Mask.size() / NumSrcElts;
46327     if ((Mask.size() % NumSrcElts) != 0 || SrcVT.isFloatingPoint())
46328       return SDValue();
46329     unsigned ScaledIdx = Scale * IdxC.getZExtValue();
46330     if (!isUndefOrZeroInRange(Mask, ScaledIdx + 1, Scale - 1))
46331       return SDValue();
46332     ExtractIdx = Mask[ScaledIdx];
46333     EVT ExtractSVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltBits / Scale);
46334     ExtractVT = EVT::getVectorVT(*DAG.getContext(), ExtractSVT, Mask.size());
46335     assert(SrcVT.getSizeInBits() == ExtractVT.getSizeInBits() &&
46336            "Failed to widen vector type");
46337   }
46338 
46339   // If the shuffle source element is undef/zero then we can just accept it.
46340   if (ExtractIdx == SM_SentinelUndef)
46341     return DAG.getUNDEF(VT);
46342 
46343   if (ExtractIdx == SM_SentinelZero)
46344     return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
46345                                 : DAG.getConstant(0, dl, VT);
46346 
46347   SDValue SrcOp = Ops[ExtractIdx / Mask.size()];
46348   ExtractIdx = ExtractIdx % Mask.size();
46349   if (SDValue V = GetLegalExtract(SrcOp, ExtractVT, ExtractIdx))
46350     return DAG.getZExtOrTrunc(V, dl, VT);
46351 
46352   return SDValue();
46353 }
46354 
46355 /// Extracting a scalar FP value from vector element 0 is free, so extract each
46356 /// operand first, then perform the math as a scalar op.
46357 static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG,
46358                                  const X86Subtarget &Subtarget) {
46359   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract");
46360   SDValue Vec = ExtElt->getOperand(0);
46361   SDValue Index = ExtElt->getOperand(1);
46362   EVT VT = ExtElt->getValueType(0);
46363   EVT VecVT = Vec.getValueType();
46364 
46365   // TODO: If this is a unary/expensive/expand op, allow extraction from a
46366   // non-zero element because the shuffle+scalar op will be cheaper?
46367   if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
46368     return SDValue();
46369 
46370   // Vector FP compares don't fit the pattern of FP math ops (propagate, not
46371   // extract, the condition code), so deal with those as a special-case.
46372   if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
46373     EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
46374     if (OpVT != MVT::f32 && OpVT != MVT::f64)
46375       return SDValue();
46376 
46377     // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
46378     SDLoc DL(ExtElt);
46379     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
46380                                Vec.getOperand(0), Index);
46381     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
46382                                Vec.getOperand(1), Index);
46383     return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
46384   }
46385 
46386   if (!(VT == MVT::f16 && Subtarget.hasFP16()) && VT != MVT::f32 &&
46387       VT != MVT::f64)
46388     return SDValue();
46389 
46390   // Vector FP selects don't fit the pattern of FP math ops (because the
46391   // condition has a different type and we have to change the opcode), so deal
46392   // with those here.
46393   // FIXME: This is restricted to pre type legalization by ensuring the setcc
46394   // has i1 elements. If we loosen this we need to convert vector bool to a
46395   // scalar bool.
46396   if (Vec.getOpcode() == ISD::VSELECT &&
46397       Vec.getOperand(0).getOpcode() == ISD::SETCC &&
46398       Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
46399       Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
46400     // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
46401     SDLoc DL(ExtElt);
46402     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
46403                                Vec.getOperand(0).getValueType().getScalarType(),
46404                                Vec.getOperand(0), Index);
46405     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
46406                                Vec.getOperand(1), Index);
46407     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
46408                                Vec.getOperand(2), Index);
46409     return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
46410   }
46411 
46412   // TODO: This switch could include FNEG and the x86-specific FP logic ops
46413   // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
46414   // missed load folding and fma+fneg combining.
46415   switch (Vec.getOpcode()) {
46416   case ISD::FMA: // Begin 3 operands
46417   case ISD::FMAD:
46418   case ISD::FADD: // Begin 2 operands
46419   case ISD::FSUB:
46420   case ISD::FMUL:
46421   case ISD::FDIV:
46422   case ISD::FREM:
46423   case ISD::FCOPYSIGN:
46424   case ISD::FMINNUM:
46425   case ISD::FMAXNUM:
46426   case ISD::FMINNUM_IEEE:
46427   case ISD::FMAXNUM_IEEE:
46428   case ISD::FMAXIMUM:
46429   case ISD::FMINIMUM:
46430   case X86ISD::FMAX:
46431   case X86ISD::FMIN:
46432   case ISD::FABS: // Begin 1 operand
46433   case ISD::FSQRT:
46434   case ISD::FRINT:
46435   case ISD::FCEIL:
46436   case ISD::FTRUNC:
46437   case ISD::FNEARBYINT:
46438   case ISD::FROUND:
46439   case ISD::FFLOOR:
46440   case X86ISD::FRCP:
46441   case X86ISD::FRSQRT: {
46442     // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
46443     SDLoc DL(ExtElt);
46444     SmallVector<SDValue, 4> ExtOps;
46445     for (SDValue Op : Vec->ops())
46446       ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
46447     return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
46448   }
46449   default:
46450     return SDValue();
46451   }
46452   llvm_unreachable("All opcodes should return within switch");
46453 }
46454 
46455 /// Try to convert a vector reduction sequence composed of binops and shuffles
46456 /// into horizontal ops.
46457 static SDValue combineArithReduction(SDNode *ExtElt, SelectionDAG &DAG,
46458                                      const X86Subtarget &Subtarget) {
46459   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller");
46460 
46461   // We need at least SSE2 to anything here.
46462   if (!Subtarget.hasSSE2())
46463     return SDValue();
46464 
46465   ISD::NodeType Opc;
46466   SDValue Rdx = DAG.matchBinOpReduction(ExtElt, Opc,
46467                                         {ISD::ADD, ISD::MUL, ISD::FADD}, true);
46468   if (!Rdx)
46469     return SDValue();
46470 
46471   SDValue Index = ExtElt->getOperand(1);
46472   assert(isNullConstant(Index) &&
46473          "Reduction doesn't end in an extract from index 0");
46474 
46475   EVT VT = ExtElt->getValueType(0);
46476   EVT VecVT = Rdx.getValueType();
46477   if (VecVT.getScalarType() != VT)
46478     return SDValue();
46479 
46480   SDLoc DL(ExtElt);
46481   unsigned NumElts = VecVT.getVectorNumElements();
46482   unsigned EltSizeInBits = VecVT.getScalarSizeInBits();
46483 
46484   // Extend v4i8/v8i8 vector to v16i8, with undef upper 64-bits.
46485   auto WidenToV16I8 = [&](SDValue V, bool ZeroExtend) {
46486     if (V.getValueType() == MVT::v4i8) {
46487       if (ZeroExtend && Subtarget.hasSSE41()) {
46488         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
46489                         DAG.getConstant(0, DL, MVT::v4i32),
46490                         DAG.getBitcast(MVT::i32, V),
46491                         DAG.getIntPtrConstant(0, DL));
46492         return DAG.getBitcast(MVT::v16i8, V);
46493       }
46494       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, V,
46495                       ZeroExtend ? DAG.getConstant(0, DL, MVT::v4i8)
46496                                  : DAG.getUNDEF(MVT::v4i8));
46497     }
46498     return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V,
46499                        DAG.getUNDEF(MVT::v8i8));
46500   };
46501 
46502   // vXi8 mul reduction - promote to vXi16 mul reduction.
46503   if (Opc == ISD::MUL) {
46504     if (VT != MVT::i8 || NumElts < 4 || !isPowerOf2_32(NumElts))
46505       return SDValue();
46506     if (VecVT.getSizeInBits() >= 128) {
46507       EVT WideVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts / 2);
46508       SDValue Lo = getUnpackl(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
46509       SDValue Hi = getUnpackh(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
46510       Lo = DAG.getBitcast(WideVT, Lo);
46511       Hi = DAG.getBitcast(WideVT, Hi);
46512       Rdx = DAG.getNode(Opc, DL, WideVT, Lo, Hi);
46513       while (Rdx.getValueSizeInBits() > 128) {
46514         std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
46515         Rdx = DAG.getNode(Opc, DL, Lo.getValueType(), Lo, Hi);
46516       }
46517     } else {
46518       Rdx = WidenToV16I8(Rdx, false);
46519       Rdx = getUnpackl(DAG, DL, MVT::v16i8, Rdx, DAG.getUNDEF(MVT::v16i8));
46520       Rdx = DAG.getBitcast(MVT::v8i16, Rdx);
46521     }
46522     if (NumElts >= 8)
46523       Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
46524                         DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
46525                                              {4, 5, 6, 7, -1, -1, -1, -1}));
46526     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
46527                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
46528                                            {2, 3, -1, -1, -1, -1, -1, -1}));
46529     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
46530                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
46531                                            {1, -1, -1, -1, -1, -1, -1, -1}));
46532     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
46533     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
46534   }
46535 
46536   // vXi8 add reduction - sub 128-bit vector.
46537   if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
46538     Rdx = WidenToV16I8(Rdx, true);
46539     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
46540                       DAG.getConstant(0, DL, MVT::v16i8));
46541     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
46542     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
46543   }
46544 
46545   // Must be a >=128-bit vector with pow2 elements.
46546   if ((VecVT.getSizeInBits() % 128) != 0 || !isPowerOf2_32(NumElts))
46547     return SDValue();
46548 
46549   // vXi8 add reduction - sum lo/hi halves then use PSADBW.
46550   if (VT == MVT::i8) {
46551     while (Rdx.getValueSizeInBits() > 128) {
46552       SDValue Lo, Hi;
46553       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
46554       VecVT = Lo.getValueType();
46555       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
46556     }
46557     assert(VecVT == MVT::v16i8 && "v16i8 reduction expected");
46558 
46559     SDValue Hi = DAG.getVectorShuffle(
46560         MVT::v16i8, DL, Rdx, Rdx,
46561         {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
46562     Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
46563     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
46564                       getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
46565     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
46566     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
46567   }
46568 
46569   // See if we can use vXi8 PSADBW add reduction for larger zext types.
46570   // If the source vector values are 0-255, then we can use PSADBW to
46571   // sum+zext v8i8 subvectors to vXi64, then perform the reduction.
46572   // TODO: See if its worth avoiding vXi16/i32 truncations?
46573   if (Opc == ISD::ADD && NumElts >= 4 && EltSizeInBits >= 16 &&
46574       DAG.computeKnownBits(Rdx).getMaxValue().ule(255) &&
46575       (EltSizeInBits == 16 || Rdx.getOpcode() == ISD::ZERO_EXTEND ||
46576        Subtarget.hasAVX512())) {
46577     EVT ByteVT = VecVT.changeVectorElementType(MVT::i8);
46578     Rdx = DAG.getNode(ISD::TRUNCATE, DL, ByteVT, Rdx);
46579     if (ByteVT.getSizeInBits() < 128)
46580       Rdx = WidenToV16I8(Rdx, true);
46581 
46582     // Build the PSADBW, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
46583     auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46584                             ArrayRef<SDValue> Ops) {
46585       MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
46586       SDValue Zero = DAG.getConstant(0, DL, Ops[0].getValueType());
46587       return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops[0], Zero);
46588     };
46589     MVT SadVT = MVT::getVectorVT(MVT::i64, Rdx.getValueSizeInBits() / 64);
46590     Rdx = SplitOpsAndApply(DAG, Subtarget, DL, SadVT, {Rdx}, PSADBWBuilder);
46591 
46592     // TODO: We could truncate to vXi16/vXi32 before performing the reduction.
46593     while (Rdx.getValueSizeInBits() > 128) {
46594       SDValue Lo, Hi;
46595       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
46596       VecVT = Lo.getValueType();
46597       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
46598     }
46599     assert(Rdx.getValueType() == MVT::v2i64 && "v2i64 reduction expected");
46600 
46601     if (NumElts > 8) {
46602       SDValue RdxHi = DAG.getVectorShuffle(MVT::v2i64, DL, Rdx, Rdx, {1, -1});
46603       Rdx = DAG.getNode(ISD::ADD, DL, MVT::v2i64, Rdx, RdxHi);
46604     }
46605 
46606     VecVT = MVT::getVectorVT(VT.getSimpleVT(), 128 / VT.getSizeInBits());
46607     Rdx = DAG.getBitcast(VecVT, Rdx);
46608     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
46609   }
46610 
46611   // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
46612   if (!shouldUseHorizontalOp(true, DAG, Subtarget))
46613     return SDValue();
46614 
46615   unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
46616 
46617   // 256-bit horizontal instructions operate on 128-bit chunks rather than
46618   // across the whole vector, so we need an extract + hop preliminary stage.
46619   // This is the only step where the operands of the hop are not the same value.
46620   // TODO: We could extend this to handle 512-bit or even longer vectors.
46621   if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
46622       ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
46623     unsigned NumElts = VecVT.getVectorNumElements();
46624     SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
46625     SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
46626     Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
46627     VecVT = Rdx.getValueType();
46628   }
46629   if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
46630       !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
46631     return SDValue();
46632 
46633   // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
46634   unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
46635   for (unsigned i = 0; i != ReductionSteps; ++i)
46636     Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
46637 
46638   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
46639 }
46640 
46641 /// Detect vector gather/scatter index generation and convert it from being a
46642 /// bunch of shuffles and extracts into a somewhat faster sequence.
46643 /// For i686, the best sequence is apparently storing the value and loading
46644 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
46645 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
46646                                        TargetLowering::DAGCombinerInfo &DCI,
46647                                        const X86Subtarget &Subtarget) {
46648   if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
46649     return NewOp;
46650 
46651   SDValue InputVector = N->getOperand(0);
46652   SDValue EltIdx = N->getOperand(1);
46653   auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
46654 
46655   EVT SrcVT = InputVector.getValueType();
46656   EVT VT = N->getValueType(0);
46657   SDLoc dl(InputVector);
46658   bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
46659   unsigned NumSrcElts = SrcVT.getVectorNumElements();
46660   unsigned NumEltBits = VT.getScalarSizeInBits();
46661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46662 
46663   if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
46664     return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
46665 
46666   // Integer Constant Folding.
46667   if (CIdx && VT.isInteger()) {
46668     APInt UndefVecElts;
46669     SmallVector<APInt, 16> EltBits;
46670     unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
46671     if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
46672                                       EltBits, true, false)) {
46673       uint64_t Idx = CIdx->getZExtValue();
46674       if (UndefVecElts[Idx])
46675         return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
46676       return DAG.getConstant(EltBits[Idx].zext(NumEltBits), dl, VT);
46677     }
46678 
46679     // Convert extract_element(bitcast(<X x i1>) -> bitcast(extract_subvector()).
46680     // Improves lowering of bool masks on rust which splits them into byte array.
46681     if (InputVector.getOpcode() == ISD::BITCAST && (NumEltBits % 8) == 0) {
46682       SDValue Src = peekThroughBitcasts(InputVector);
46683       if (Src.getValueType().getScalarType() == MVT::i1 &&
46684           TLI.isTypeLegal(Src.getValueType())) {
46685         MVT SubVT = MVT::getVectorVT(MVT::i1, NumEltBits);
46686         SDValue Sub = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Src,
46687             DAG.getIntPtrConstant(CIdx->getZExtValue() * NumEltBits, dl));
46688         return DAG.getBitcast(VT, Sub);
46689       }
46690     }
46691   }
46692 
46693   if (IsPextr) {
46694     if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumEltBits),
46695                                  DCI))
46696       return SDValue(N, 0);
46697 
46698     // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
46699     if ((InputVector.getOpcode() == X86ISD::PINSRB ||
46700          InputVector.getOpcode() == X86ISD::PINSRW) &&
46701         InputVector.getOperand(2) == EltIdx) {
46702       assert(SrcVT == InputVector.getOperand(0).getValueType() &&
46703              "Vector type mismatch");
46704       SDValue Scl = InputVector.getOperand(1);
46705       Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
46706       return DAG.getZExtOrTrunc(Scl, dl, VT);
46707     }
46708 
46709     // TODO - Remove this once we can handle the implicit zero-extension of
46710     // X86ISD::PEXTRW/X86ISD::PEXTRB in combinePredicateReduction and
46711     // combineBasicSADPattern.
46712     return SDValue();
46713   }
46714 
46715   // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
46716   if (VT == MVT::i64 && SrcVT == MVT::v1i64 &&
46717       InputVector.getOpcode() == ISD::BITCAST &&
46718       InputVector.getOperand(0).getValueType() == MVT::x86mmx &&
46719       isNullConstant(EltIdx) && InputVector.hasOneUse())
46720     return DAG.getBitcast(VT, InputVector);
46721 
46722   // Detect mmx to i32 conversion through a v2i32 elt extract.
46723   if (VT == MVT::i32 && SrcVT == MVT::v2i32 &&
46724       InputVector.getOpcode() == ISD::BITCAST &&
46725       InputVector.getOperand(0).getValueType() == MVT::x86mmx &&
46726       isNullConstant(EltIdx) && InputVector.hasOneUse())
46727     return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32,
46728                        InputVector.getOperand(0));
46729 
46730   // Check whether this extract is the root of a sum of absolute differences
46731   // pattern. This has to be done here because we really want it to happen
46732   // pre-legalization,
46733   if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
46734     return SAD;
46735 
46736   if (SDValue VPDPBUSD = combineVPDPBUSDPattern(N, DAG, Subtarget))
46737     return VPDPBUSD;
46738 
46739   // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
46740   if (SDValue Cmp = combinePredicateReduction(N, DAG, Subtarget))
46741     return Cmp;
46742 
46743   // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
46744   if (SDValue MinMax = combineMinMaxReduction(N, DAG, Subtarget))
46745     return MinMax;
46746 
46747   // Attempt to optimize ADD/FADD/MUL reductions with HADD, promotion etc..
46748   if (SDValue V = combineArithReduction(N, DAG, Subtarget))
46749     return V;
46750 
46751   if (SDValue V = scalarizeExtEltFP(N, DAG, Subtarget))
46752     return V;
46753 
46754   // Attempt to extract a i1 element by using MOVMSK to extract the signbits
46755   // and then testing the relevant element.
46756   //
46757   // Note that we only combine extracts on the *same* result number, i.e.
46758   //   t0 = merge_values a0, a1, a2, a3
46759   //   i1 = extract_vector_elt t0, Constant:i64<2>
46760   //   i1 = extract_vector_elt t0, Constant:i64<3>
46761   // but not
46762   //   i1 = extract_vector_elt t0:1, Constant:i64<2>
46763   // since the latter would need its own MOVMSK.
46764   if (SrcVT.getScalarType() == MVT::i1) {
46765     bool IsVar = !CIdx;
46766     SmallVector<SDNode *, 16> BoolExtracts;
46767     unsigned ResNo = InputVector.getResNo();
46768     auto IsBoolExtract = [&BoolExtracts, &ResNo, &IsVar](SDNode *Use) {
46769       if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
46770           Use->getOperand(0).getResNo() == ResNo &&
46771           Use->getValueType(0) == MVT::i1) {
46772         BoolExtracts.push_back(Use);
46773         IsVar |= !isa<ConstantSDNode>(Use->getOperand(1));
46774         return true;
46775       }
46776       return false;
46777     };
46778     // TODO: Can we drop the oneuse check for constant extracts?
46779     if (all_of(InputVector->uses(), IsBoolExtract) &&
46780         (IsVar || BoolExtracts.size() > 1)) {
46781       EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
46782       if (SDValue BC =
46783               combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
46784         for (SDNode *Use : BoolExtracts) {
46785           // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
46786           // Mask = 1 << MaskIdx
46787           SDValue MaskIdx = DAG.getZExtOrTrunc(Use->getOperand(1), dl, MVT::i8);
46788           SDValue MaskBit = DAG.getConstant(1, dl, BCVT);
46789           SDValue Mask = DAG.getNode(ISD::SHL, dl, BCVT, MaskBit, MaskIdx);
46790           SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
46791           Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
46792           DCI.CombineTo(Use, Res);
46793         }
46794         return SDValue(N, 0);
46795       }
46796     }
46797   }
46798 
46799   // If this extract is from a loaded vector value and will be used as an
46800   // integer, that requires a potentially expensive XMM -> GPR transfer.
46801   // Additionally, if we can convert to a scalar integer load, that will likely
46802   // be folded into a subsequent integer op.
46803   // Note: Unlike the related fold for this in DAGCombiner, this is not limited
46804   //       to a single-use of the loaded vector. For the reasons above, we
46805   //       expect this to be profitable even if it creates an extra load.
46806   bool LikelyUsedAsVector = any_of(N->uses(), [](SDNode *Use) {
46807     return Use->getOpcode() == ISD::STORE ||
46808            Use->getOpcode() == ISD::INSERT_VECTOR_ELT ||
46809            Use->getOpcode() == ISD::SCALAR_TO_VECTOR;
46810   });
46811   auto *LoadVec = dyn_cast<LoadSDNode>(InputVector);
46812   if (LoadVec && CIdx && ISD::isNormalLoad(LoadVec) && VT.isInteger() &&
46813       SrcVT.getVectorElementType() == VT && DCI.isAfterLegalizeDAG() &&
46814       !LikelyUsedAsVector && LoadVec->isSimple()) {
46815     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46816     SDValue NewPtr =
46817         TLI.getVectorElementPointer(DAG, LoadVec->getBasePtr(), SrcVT, EltIdx);
46818     unsigned PtrOff = VT.getSizeInBits() * CIdx->getZExtValue() / 8;
46819     MachinePointerInfo MPI = LoadVec->getPointerInfo().getWithOffset(PtrOff);
46820     Align Alignment = commonAlignment(LoadVec->getAlign(), PtrOff);
46821     SDValue Load =
46822         DAG.getLoad(VT, dl, LoadVec->getChain(), NewPtr, MPI, Alignment,
46823                     LoadVec->getMemOperand()->getFlags(), LoadVec->getAAInfo());
46824     DAG.makeEquivalentMemoryOrdering(LoadVec, Load);
46825     return Load;
46826   }
46827 
46828   return SDValue();
46829 }
46830 
46831 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
46832 // This is more or less the reverse of combineBitcastvxi1.
46833 static SDValue combineToExtendBoolVectorInReg(
46834     unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N0, SelectionDAG &DAG,
46835     TargetLowering::DAGCombinerInfo &DCI, const X86Subtarget &Subtarget) {
46836   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
46837       Opcode != ISD::ANY_EXTEND)
46838     return SDValue();
46839   if (!DCI.isBeforeLegalizeOps())
46840     return SDValue();
46841   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
46842     return SDValue();
46843 
46844   EVT SVT = VT.getScalarType();
46845   EVT InSVT = N0.getValueType().getScalarType();
46846   unsigned EltSizeInBits = SVT.getSizeInBits();
46847 
46848   // Input type must be extending a bool vector (bit-casted from a scalar
46849   // integer) to legal integer types.
46850   if (!VT.isVector())
46851     return SDValue();
46852   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
46853     return SDValue();
46854   if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
46855     return SDValue();
46856 
46857   SDValue N00 = N0.getOperand(0);
46858   EVT SclVT = N00.getValueType();
46859   if (!SclVT.isScalarInteger())
46860     return SDValue();
46861 
46862   SDValue Vec;
46863   SmallVector<int> ShuffleMask;
46864   unsigned NumElts = VT.getVectorNumElements();
46865   assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
46866 
46867   // Broadcast the scalar integer to the vector elements.
46868   if (NumElts > EltSizeInBits) {
46869     // If the scalar integer is greater than the vector element size, then we
46870     // must split it down into sub-sections for broadcasting. For example:
46871     //   i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
46872     //   i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
46873     assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
46874     unsigned Scale = NumElts / EltSizeInBits;
46875     EVT BroadcastVT = EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
46876     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
46877     Vec = DAG.getBitcast(VT, Vec);
46878 
46879     for (unsigned i = 0; i != Scale; ++i)
46880       ShuffleMask.append(EltSizeInBits, i);
46881     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
46882   } else if (Subtarget.hasAVX2() && NumElts < EltSizeInBits &&
46883              (SclVT == MVT::i8 || SclVT == MVT::i16 || SclVT == MVT::i32)) {
46884     // If we have register broadcast instructions, use the scalar size as the
46885     // element type for the shuffle. Then cast to the wider element type. The
46886     // widened bits won't be used, and this might allow the use of a broadcast
46887     // load.
46888     assert((EltSizeInBits % NumElts) == 0 && "Unexpected integer scale");
46889     unsigned Scale = EltSizeInBits / NumElts;
46890     EVT BroadcastVT =
46891         EVT::getVectorVT(*DAG.getContext(), SclVT, NumElts * Scale);
46892     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
46893     ShuffleMask.append(NumElts * Scale, 0);
46894     Vec = DAG.getVectorShuffle(BroadcastVT, DL, Vec, Vec, ShuffleMask);
46895     Vec = DAG.getBitcast(VT, Vec);
46896   } else {
46897     // For smaller scalar integers, we can simply any-extend it to the vector
46898     // element size (we don't care about the upper bits) and broadcast it to all
46899     // elements.
46900     SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
46901     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
46902     ShuffleMask.append(NumElts, 0);
46903     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
46904   }
46905 
46906   // Now, mask the relevant bit in each element.
46907   SmallVector<SDValue, 32> Bits;
46908   for (unsigned i = 0; i != NumElts; ++i) {
46909     int BitIdx = (i % EltSizeInBits);
46910     APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
46911     Bits.push_back(DAG.getConstant(Bit, DL, SVT));
46912   }
46913   SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
46914   Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
46915 
46916   // Compare against the bitmask and extend the result.
46917   EVT CCVT = VT.changeVectorElementType(MVT::i1);
46918   Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
46919   Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
46920 
46921   // For SEXT, this is now done, otherwise shift the result down for
46922   // zero-extension.
46923   if (Opcode == ISD::SIGN_EXTEND)
46924     return Vec;
46925   return DAG.getNode(ISD::SRL, DL, VT, Vec,
46926                      DAG.getConstant(EltSizeInBits - 1, DL, VT));
46927 }
46928 
46929 /// If a vector select has an operand that is -1 or 0, try to simplify the
46930 /// select to a bitwise logic operation.
46931 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
46932 static SDValue
46933 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
46934                                  TargetLowering::DAGCombinerInfo &DCI,
46935                                  const X86Subtarget &Subtarget) {
46936   SDValue Cond = N->getOperand(0);
46937   SDValue LHS = N->getOperand(1);
46938   SDValue RHS = N->getOperand(2);
46939   EVT VT = LHS.getValueType();
46940   EVT CondVT = Cond.getValueType();
46941   SDLoc DL(N);
46942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46943 
46944   if (N->getOpcode() != ISD::VSELECT)
46945     return SDValue();
46946 
46947   assert(CondVT.isVector() && "Vector select expects a vector selector!");
46948 
46949   // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
46950   // TODO: Can we assert that both operands are not zeros (because that should
46951   //       get simplified at node creation time)?
46952   bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
46953   bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
46954 
46955   // If both inputs are 0/undef, create a complete zero vector.
46956   // FIXME: As noted above this should be handled by DAGCombiner/getNode.
46957   if (TValIsAllZeros && FValIsAllZeros) {
46958     if (VT.isFloatingPoint())
46959       return DAG.getConstantFP(0.0, DL, VT);
46960     return DAG.getConstant(0, DL, VT);
46961   }
46962 
46963   // To use the condition operand as a bitwise mask, it must have elements that
46964   // are the same size as the select elements. Ie, the condition operand must
46965   // have already been promoted from the IR select condition type <N x i1>.
46966   // Don't check if the types themselves are equal because that excludes
46967   // vector floating-point selects.
46968   if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
46969     return SDValue();
46970 
46971   // Try to invert the condition if true value is not all 1s and false value is
46972   // not all 0s. Only do this if the condition has one use.
46973   bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
46974   if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
46975       // Check if the selector will be produced by CMPP*/PCMP*.
46976       Cond.getOpcode() == ISD::SETCC &&
46977       // Check if SETCC has already been promoted.
46978       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
46979           CondVT) {
46980     bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
46981 
46982     if (TValIsAllZeros || FValIsAllOnes) {
46983       SDValue CC = Cond.getOperand(2);
46984       ISD::CondCode NewCC = ISD::getSetCCInverse(
46985           cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
46986       Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
46987                           NewCC);
46988       std::swap(LHS, RHS);
46989       TValIsAllOnes = FValIsAllOnes;
46990       FValIsAllZeros = TValIsAllZeros;
46991     }
46992   }
46993 
46994   // Cond value must be 'sign splat' to be converted to a logical op.
46995   if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
46996     return SDValue();
46997 
46998   // vselect Cond, 111..., 000... -> Cond
46999   if (TValIsAllOnes && FValIsAllZeros)
47000     return DAG.getBitcast(VT, Cond);
47001 
47002   if (!TLI.isTypeLegal(CondVT))
47003     return SDValue();
47004 
47005   // vselect Cond, 111..., X -> or Cond, X
47006   if (TValIsAllOnes) {
47007     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
47008     SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
47009     return DAG.getBitcast(VT, Or);
47010   }
47011 
47012   // vselect Cond, X, 000... -> and Cond, X
47013   if (FValIsAllZeros) {
47014     SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
47015     SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
47016     return DAG.getBitcast(VT, And);
47017   }
47018 
47019   // vselect Cond, 000..., X -> andn Cond, X
47020   if (TValIsAllZeros) {
47021     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
47022     SDValue AndN;
47023     // The canonical form differs for i1 vectors - x86andnp is not used
47024     if (CondVT.getScalarType() == MVT::i1)
47025       AndN = DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT),
47026                          CastRHS);
47027     else
47028       AndN = DAG.getNode(X86ISD::ANDNP, DL, CondVT, Cond, CastRHS);
47029     return DAG.getBitcast(VT, AndN);
47030   }
47031 
47032   return SDValue();
47033 }
47034 
47035 /// If both arms of a vector select are concatenated vectors, split the select,
47036 /// and concatenate the result to eliminate a wide (256-bit) vector instruction:
47037 ///   vselect Cond, (concat T0, T1), (concat F0, F1) -->
47038 ///   concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
47039 static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG,
47040                                   const X86Subtarget &Subtarget) {
47041   unsigned Opcode = N->getOpcode();
47042   if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
47043     return SDValue();
47044 
47045   // TODO: Split 512-bit vectors too?
47046   EVT VT = N->getValueType(0);
47047   if (!VT.is256BitVector())
47048     return SDValue();
47049 
47050   // TODO: Split as long as any 2 of the 3 operands are concatenated?
47051   SDValue Cond = N->getOperand(0);
47052   SDValue TVal = N->getOperand(1);
47053   SDValue FVal = N->getOperand(2);
47054   if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
47055       !isFreeToSplitVector(TVal.getNode(), DAG) ||
47056       !isFreeToSplitVector(FVal.getNode(), DAG))
47057     return SDValue();
47058 
47059   auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
47060                             ArrayRef<SDValue> Ops) {
47061     return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
47062   };
47063   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { Cond, TVal, FVal },
47064                           makeBlend, /*CheckBWI*/ false);
47065 }
47066 
47067 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
47068   SDValue Cond = N->getOperand(0);
47069   SDValue LHS = N->getOperand(1);
47070   SDValue RHS = N->getOperand(2);
47071   SDLoc DL(N);
47072 
47073   auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
47074   auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
47075   if (!TrueC || !FalseC)
47076     return SDValue();
47077 
47078   // Don't do this for crazy integer types.
47079   EVT VT = N->getValueType(0);
47080   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
47081     return SDValue();
47082 
47083   // We're going to use the condition bit in math or logic ops. We could allow
47084   // this with a wider condition value (post-legalization it becomes an i8),
47085   // but if nothing is creating selects that late, it doesn't matter.
47086   if (Cond.getValueType() != MVT::i1)
47087     return SDValue();
47088 
47089   // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
47090   // 3, 5, or 9 with i32/i64, so those get transformed too.
47091   // TODO: For constants that overflow or do not differ by power-of-2 or small
47092   // multiplier, convert to 'and' + 'add'.
47093   const APInt &TrueVal = TrueC->getAPIntValue();
47094   const APInt &FalseVal = FalseC->getAPIntValue();
47095 
47096   // We have a more efficient lowering for "(X == 0) ? Y : -1" using SBB.
47097   if ((TrueVal.isAllOnes() || FalseVal.isAllOnes()) &&
47098       Cond.getOpcode() == ISD::SETCC && isNullConstant(Cond.getOperand(1))) {
47099     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
47100     if (CC == ISD::SETEQ || CC == ISD::SETNE)
47101       return SDValue();
47102   }
47103 
47104   bool OV;
47105   APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
47106   if (OV)
47107     return SDValue();
47108 
47109   APInt AbsDiff = Diff.abs();
47110   if (AbsDiff.isPowerOf2() ||
47111       ((VT == MVT::i32 || VT == MVT::i64) &&
47112        (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
47113 
47114     // We need a positive multiplier constant for shift/LEA codegen. The 'not'
47115     // of the condition can usually be folded into a compare predicate, but even
47116     // without that, the sequence should be cheaper than a CMOV alternative.
47117     if (TrueVal.slt(FalseVal)) {
47118       Cond = DAG.getNOT(DL, Cond, MVT::i1);
47119       std::swap(TrueC, FalseC);
47120     }
47121 
47122     // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
47123     SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
47124 
47125     // Multiply condition by the difference if non-one.
47126     if (!AbsDiff.isOne())
47127       R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
47128 
47129     // Add the base if non-zero.
47130     if (!FalseC->isZero())
47131       R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
47132 
47133     return R;
47134   }
47135 
47136   return SDValue();
47137 }
47138 
47139 /// If this is a *dynamic* select (non-constant condition) and we can match
47140 /// this node with one of the variable blend instructions, restructure the
47141 /// condition so that blends can use the high (sign) bit of each element.
47142 /// This function will also call SimplifyDemandedBits on already created
47143 /// BLENDV to perform additional simplifications.
47144 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
47145                                       TargetLowering::DAGCombinerInfo &DCI,
47146                                       const X86Subtarget &Subtarget) {
47147   SDValue Cond = N->getOperand(0);
47148   if ((N->getOpcode() != ISD::VSELECT &&
47149        N->getOpcode() != X86ISD::BLENDV) ||
47150       ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
47151     return SDValue();
47152 
47153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47154   unsigned BitWidth = Cond.getScalarValueSizeInBits();
47155   EVT VT = N->getValueType(0);
47156 
47157   // We can only handle the cases where VSELECT is directly legal on the
47158   // subtarget. We custom lower VSELECT nodes with constant conditions and
47159   // this makes it hard to see whether a dynamic VSELECT will correctly
47160   // lower, so we both check the operation's status and explicitly handle the
47161   // cases where a *dynamic* blend will fail even though a constant-condition
47162   // blend could be custom lowered.
47163   // FIXME: We should find a better way to handle this class of problems.
47164   // Potentially, we should combine constant-condition vselect nodes
47165   // pre-legalization into shuffles and not mark as many types as custom
47166   // lowered.
47167   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
47168     return SDValue();
47169   // FIXME: We don't support i16-element blends currently. We could and
47170   // should support them by making *all* the bits in the condition be set
47171   // rather than just the high bit and using an i8-element blend.
47172   if (VT.getVectorElementType() == MVT::i16)
47173     return SDValue();
47174   // Dynamic blending was only available from SSE4.1 onward.
47175   if (VT.is128BitVector() && !Subtarget.hasSSE41())
47176     return SDValue();
47177   // Byte blends are only available in AVX2
47178   if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
47179     return SDValue();
47180   // There are no 512-bit blend instructions that use sign bits.
47181   if (VT.is512BitVector())
47182     return SDValue();
47183 
47184   // Don't optimize before the condition has been transformed to a legal type
47185   // and don't ever optimize vector selects that map to AVX512 mask-registers.
47186   if (BitWidth < 8 || BitWidth > 64)
47187     return SDValue();
47188 
47189   auto OnlyUsedAsSelectCond = [](SDValue Cond) {
47190     for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
47191          UI != UE; ++UI)
47192       if ((UI->getOpcode() != ISD::VSELECT &&
47193            UI->getOpcode() != X86ISD::BLENDV) ||
47194           UI.getOperandNo() != 0)
47195         return false;
47196 
47197     return true;
47198   };
47199 
47200   APInt DemandedBits(APInt::getSignMask(BitWidth));
47201 
47202   if (OnlyUsedAsSelectCond(Cond)) {
47203     KnownBits Known;
47204     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
47205                                           !DCI.isBeforeLegalizeOps());
47206     if (!TLI.SimplifyDemandedBits(Cond, DemandedBits, Known, TLO, 0, true))
47207       return SDValue();
47208 
47209     // If we changed the computation somewhere in the DAG, this change will
47210     // affect all users of Cond. Update all the nodes so that we do not use
47211     // the generic VSELECT anymore. Otherwise, we may perform wrong
47212     // optimizations as we messed with the actual expectation for the vector
47213     // boolean values.
47214     for (SDNode *U : Cond->uses()) {
47215       if (U->getOpcode() == X86ISD::BLENDV)
47216         continue;
47217 
47218       SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
47219                                Cond, U->getOperand(1), U->getOperand(2));
47220       DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
47221       DCI.AddToWorklist(U);
47222     }
47223     DCI.CommitTargetLoweringOpt(TLO);
47224     return SDValue(N, 0);
47225   }
47226 
47227   // Otherwise we can still at least try to simplify multiple use bits.
47228   if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedBits, DAG))
47229       return DAG.getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0), V,
47230                          N->getOperand(1), N->getOperand(2));
47231 
47232   return SDValue();
47233 }
47234 
47235 // Try to match:
47236 //   (or (and (M, (sub 0, X)), (pandn M, X)))
47237 // which is a special case of:
47238 //   (select M, (sub 0, X), X)
47239 // Per:
47240 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
47241 // We know that, if fNegate is 0 or 1:
47242 //   (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
47243 //
47244 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
47245 //   ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
47246 //   ( M      ? -X : X) == ((X ^   M     ) + (M & 1))
47247 // This lets us transform our vselect to:
47248 //   (add (xor X, M), (and M, 1))
47249 // And further to:
47250 //   (sub (xor X, M), M)
47251 static SDValue combineLogicBlendIntoConditionalNegate(
47252     EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
47253     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
47254   EVT MaskVT = Mask.getValueType();
47255   assert(MaskVT.isInteger() &&
47256          DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
47257          "Mask must be zero/all-bits");
47258 
47259   if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
47260     return SDValue();
47261   if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
47262     return SDValue();
47263 
47264   auto IsNegV = [](SDNode *N, SDValue V) {
47265     return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
47266            ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
47267   };
47268 
47269   SDValue V;
47270   if (IsNegV(Y.getNode(), X))
47271     V = X;
47272   else if (IsNegV(X.getNode(), Y))
47273     V = Y;
47274   else
47275     return SDValue();
47276 
47277   SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
47278   SDValue SubOp2 = Mask;
47279 
47280   // If the negate was on the false side of the select, then
47281   // the operands of the SUB need to be swapped. PR 27251.
47282   // This is because the pattern being matched above is
47283   // (vselect M, (sub (0, X), X)  -> (sub (xor X, M), M)
47284   // but if the pattern matched was
47285   // (vselect M, X, (sub (0, X))), that is really negation of the pattern
47286   // above, -(vselect M, (sub 0, X), X), and therefore the replacement
47287   // pattern also needs to be a negation of the replacement pattern above.
47288   // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
47289   // sub accomplishes the negation of the replacement pattern.
47290   if (V == Y)
47291     std::swap(SubOp1, SubOp2);
47292 
47293   SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
47294   return DAG.getBitcast(VT, Res);
47295 }
47296 
47297 static SDValue commuteSelect(SDNode *N, SelectionDAG &DAG,
47298                                   const X86Subtarget &Subtarget) {
47299   if (!Subtarget.hasAVX512())
47300     return SDValue();
47301   if (N->getOpcode() != ISD::VSELECT)
47302     return SDValue();
47303 
47304   SDLoc DL(N);
47305   SDValue Cond = N->getOperand(0);
47306   SDValue LHS = N->getOperand(1);
47307   SDValue RHS = N->getOperand(2);
47308 
47309   if (canCombineAsMaskOperation(LHS, Subtarget))
47310     return SDValue();
47311 
47312   if (!canCombineAsMaskOperation(RHS, Subtarget))
47313     return SDValue();
47314 
47315   if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse())
47316     return SDValue();
47317 
47318   // Commute LHS and RHS to create opportunity to select mask instruction.
47319   // (vselect M, L, R) -> (vselect ~M, R, L)
47320   ISD::CondCode NewCC =
47321       ISD::getSetCCInverse(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
47322                            Cond.getOperand(0).getValueType());
47323   Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(), Cond.getOperand(0),
47324 		                        Cond.getOperand(1), NewCC);
47325   return DAG.getSelect(DL, LHS.getValueType(), Cond, RHS, LHS);
47326 }
47327 
47328 /// Do target-specific dag combines on SELECT and VSELECT nodes.
47329 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
47330                              TargetLowering::DAGCombinerInfo &DCI,
47331                              const X86Subtarget &Subtarget) {
47332   SDLoc DL(N);
47333   SDValue Cond = N->getOperand(0);
47334   SDValue LHS = N->getOperand(1);
47335   SDValue RHS = N->getOperand(2);
47336 
47337   // Try simplification again because we use this function to optimize
47338   // BLENDV nodes that are not handled by the generic combiner.
47339   if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
47340     return V;
47341 
47342   // When avx512 is available the lhs operand of select instruction can be
47343   // folded with mask instruction, while the rhs operand can't. Commute the
47344   // lhs and rhs of the select instruction to create the opportunity of
47345   // folding.
47346   if (SDValue V = commuteSelect(N, DAG, Subtarget))
47347     return V;
47348 
47349   EVT VT = LHS.getValueType();
47350   EVT CondVT = Cond.getValueType();
47351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47352   bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
47353 
47354   // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
47355   // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
47356   // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
47357   if (CondVT.isVector() && CondVT.isInteger() &&
47358       CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
47359       (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
47360       DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
47361     if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
47362                                                            DL, DAG, Subtarget))
47363       return V;
47364 
47365   // Convert vselects with constant condition into shuffles.
47366   if (CondConstantVector && DCI.isBeforeLegalizeOps() &&
47367       (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::BLENDV)) {
47368     SmallVector<int, 64> Mask;
47369     if (createShuffleMaskFromVSELECT(Mask, Cond,
47370                                      N->getOpcode() == X86ISD::BLENDV))
47371       return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
47372   }
47373 
47374   // fold vselect(cond, pshufb(x), pshufb(y)) -> or (pshufb(x), pshufb(y))
47375   // by forcing the unselected elements to zero.
47376   // TODO: Can we handle more shuffles with this?
47377   if (N->getOpcode() == ISD::VSELECT && CondVT.isVector() &&
47378       LHS.getOpcode() == X86ISD::PSHUFB && RHS.getOpcode() == X86ISD::PSHUFB &&
47379       LHS.hasOneUse() && RHS.hasOneUse()) {
47380     MVT SimpleVT = VT.getSimpleVT();
47381     SmallVector<SDValue, 1> LHSOps, RHSOps;
47382     SmallVector<int, 64> LHSMask, RHSMask, CondMask;
47383     if (createShuffleMaskFromVSELECT(CondMask, Cond) &&
47384         getTargetShuffleMask(LHS.getNode(), SimpleVT, true, LHSOps, LHSMask) &&
47385         getTargetShuffleMask(RHS.getNode(), SimpleVT, true, RHSOps, RHSMask)) {
47386       int NumElts = VT.getVectorNumElements();
47387       for (int i = 0; i != NumElts; ++i) {
47388         // getConstVector sets negative shuffle mask values as undef, so ensure
47389         // we hardcode SM_SentinelZero values to zero (0x80).
47390         if (CondMask[i] < NumElts) {
47391           LHSMask[i] = isUndefOrZero(LHSMask[i]) ? 0x80 : LHSMask[i];
47392           RHSMask[i] = 0x80;
47393         } else {
47394           LHSMask[i] = 0x80;
47395           RHSMask[i] = isUndefOrZero(RHSMask[i]) ? 0x80 : RHSMask[i];
47396         }
47397       }
47398       LHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, LHS.getOperand(0),
47399                         getConstVector(LHSMask, SimpleVT, DAG, DL, true));
47400       RHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, RHS.getOperand(0),
47401                         getConstVector(RHSMask, SimpleVT, DAG, DL, true));
47402       return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
47403     }
47404   }
47405 
47406   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
47407   // instructions match the semantics of the common C idiom x<y?x:y but not
47408   // x<=y?x:y, because of how they handle negative zero (which can be
47409   // ignored in unsafe-math mode).
47410   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
47411   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
47412       VT != MVT::f80 && VT != MVT::f128 && !isSoftF16(VT, Subtarget) &&
47413       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
47414       (Subtarget.hasSSE2() ||
47415        (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
47416     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
47417 
47418     unsigned Opcode = 0;
47419     // Check for x CC y ? x : y.
47420     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
47421         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
47422       switch (CC) {
47423       default: break;
47424       case ISD::SETULT:
47425         // Converting this to a min would handle NaNs incorrectly, and swapping
47426         // the operands would cause it to handle comparisons between positive
47427         // and negative zero incorrectly.
47428         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
47429           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
47430               !(DAG.isKnownNeverZeroFloat(LHS) ||
47431                 DAG.isKnownNeverZeroFloat(RHS)))
47432             break;
47433           std::swap(LHS, RHS);
47434         }
47435         Opcode = X86ISD::FMIN;
47436         break;
47437       case ISD::SETOLE:
47438         // Converting this to a min would handle comparisons between positive
47439         // and negative zero incorrectly.
47440         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
47441             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
47442           break;
47443         Opcode = X86ISD::FMIN;
47444         break;
47445       case ISD::SETULE:
47446         // Converting this to a min would handle both negative zeros and NaNs
47447         // incorrectly, but we can swap the operands to fix both.
47448         std::swap(LHS, RHS);
47449         [[fallthrough]];
47450       case ISD::SETOLT:
47451       case ISD::SETLT:
47452       case ISD::SETLE:
47453         Opcode = X86ISD::FMIN;
47454         break;
47455 
47456       case ISD::SETOGE:
47457         // Converting this to a max would handle comparisons between positive
47458         // and negative zero incorrectly.
47459         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
47460             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
47461           break;
47462         Opcode = X86ISD::FMAX;
47463         break;
47464       case ISD::SETUGT:
47465         // Converting this to a max would handle NaNs incorrectly, and swapping
47466         // the operands would cause it to handle comparisons between positive
47467         // and negative zero incorrectly.
47468         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
47469           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
47470               !(DAG.isKnownNeverZeroFloat(LHS) ||
47471                 DAG.isKnownNeverZeroFloat(RHS)))
47472             break;
47473           std::swap(LHS, RHS);
47474         }
47475         Opcode = X86ISD::FMAX;
47476         break;
47477       case ISD::SETUGE:
47478         // Converting this to a max would handle both negative zeros and NaNs
47479         // incorrectly, but we can swap the operands to fix both.
47480         std::swap(LHS, RHS);
47481         [[fallthrough]];
47482       case ISD::SETOGT:
47483       case ISD::SETGT:
47484       case ISD::SETGE:
47485         Opcode = X86ISD::FMAX;
47486         break;
47487       }
47488     // Check for x CC y ? y : x -- a min/max with reversed arms.
47489     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
47490                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
47491       switch (CC) {
47492       default: break;
47493       case ISD::SETOGE:
47494         // Converting this to a min would handle comparisons between positive
47495         // and negative zero incorrectly, and swapping the operands would
47496         // cause it to handle NaNs incorrectly.
47497         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
47498             !(DAG.isKnownNeverZeroFloat(LHS) ||
47499               DAG.isKnownNeverZeroFloat(RHS))) {
47500           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
47501             break;
47502           std::swap(LHS, RHS);
47503         }
47504         Opcode = X86ISD::FMIN;
47505         break;
47506       case ISD::SETUGT:
47507         // Converting this to a min would handle NaNs incorrectly.
47508         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
47509           break;
47510         Opcode = X86ISD::FMIN;
47511         break;
47512       case ISD::SETUGE:
47513         // Converting this to a min would handle both negative zeros and NaNs
47514         // incorrectly, but we can swap the operands to fix both.
47515         std::swap(LHS, RHS);
47516         [[fallthrough]];
47517       case ISD::SETOGT:
47518       case ISD::SETGT:
47519       case ISD::SETGE:
47520         Opcode = X86ISD::FMIN;
47521         break;
47522 
47523       case ISD::SETULT:
47524         // Converting this to a max would handle NaNs incorrectly.
47525         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
47526           break;
47527         Opcode = X86ISD::FMAX;
47528         break;
47529       case ISD::SETOLE:
47530         // Converting this to a max would handle comparisons between positive
47531         // and negative zero incorrectly, and swapping the operands would
47532         // cause it to handle NaNs incorrectly.
47533         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
47534             !DAG.isKnownNeverZeroFloat(LHS) &&
47535             !DAG.isKnownNeverZeroFloat(RHS)) {
47536           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
47537             break;
47538           std::swap(LHS, RHS);
47539         }
47540         Opcode = X86ISD::FMAX;
47541         break;
47542       case ISD::SETULE:
47543         // Converting this to a max would handle both negative zeros and NaNs
47544         // incorrectly, but we can swap the operands to fix both.
47545         std::swap(LHS, RHS);
47546         [[fallthrough]];
47547       case ISD::SETOLT:
47548       case ISD::SETLT:
47549       case ISD::SETLE:
47550         Opcode = X86ISD::FMAX;
47551         break;
47552       }
47553     }
47554 
47555     if (Opcode)
47556       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
47557   }
47558 
47559   // Some mask scalar intrinsics rely on checking if only one bit is set
47560   // and implement it in C code like this:
47561   // A[0] = (U & 1) ? A[0] : W[0];
47562   // This creates some redundant instructions that break pattern matching.
47563   // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
47564   if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
47565       Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
47566     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
47567     SDValue AndNode = Cond.getOperand(0);
47568     if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
47569         isNullConstant(Cond.getOperand(1)) &&
47570         isOneConstant(AndNode.getOperand(1))) {
47571       // LHS and RHS swapped due to
47572       // setcc outputting 1 when AND resulted in 0 and vice versa.
47573       AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
47574       return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
47575     }
47576   }
47577 
47578   // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
47579   // lowering on KNL. In this case we convert it to
47580   // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
47581   // The same situation all vectors of i8 and i16 without BWI.
47582   // Make sure we extend these even before type legalization gets a chance to
47583   // split wide vectors.
47584   // Since SKX these selects have a proper lowering.
47585   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
47586       CondVT.getVectorElementType() == MVT::i1 &&
47587       (VT.getVectorElementType() == MVT::i8 ||
47588        VT.getVectorElementType() == MVT::i16)) {
47589     Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
47590     return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
47591   }
47592 
47593   // AVX512 - Extend select with zero to merge with target shuffle.
47594   // select(mask, extract_subvector(shuffle(x)), zero) -->
47595   // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
47596   // TODO - support non target shuffles as well.
47597   if (Subtarget.hasAVX512() && CondVT.isVector() &&
47598       CondVT.getVectorElementType() == MVT::i1) {
47599     auto SelectableOp = [&TLI](SDValue Op) {
47600       return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
47601              isTargetShuffle(Op.getOperand(0).getOpcode()) &&
47602              isNullConstant(Op.getOperand(1)) &&
47603              TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
47604              Op.hasOneUse() && Op.getOperand(0).hasOneUse();
47605     };
47606 
47607     bool SelectableLHS = SelectableOp(LHS);
47608     bool SelectableRHS = SelectableOp(RHS);
47609     bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
47610     bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
47611 
47612     if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
47613       EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
47614                                 : RHS.getOperand(0).getValueType();
47615       EVT SrcCondVT = SrcVT.changeVectorElementType(MVT::i1);
47616       LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
47617                             VT.getSizeInBits());
47618       RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
47619                             VT.getSizeInBits());
47620       Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
47621                          DAG.getUNDEF(SrcCondVT), Cond,
47622                          DAG.getIntPtrConstant(0, DL));
47623       SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
47624       return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
47625     }
47626   }
47627 
47628   if (SDValue V = combineSelectOfTwoConstants(N, DAG))
47629     return V;
47630 
47631   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
47632       Cond.hasOneUse()) {
47633     EVT CondVT = Cond.getValueType();
47634     SDValue Cond0 = Cond.getOperand(0);
47635     SDValue Cond1 = Cond.getOperand(1);
47636     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
47637 
47638     // Canonicalize min/max:
47639     // (x > 0) ? x : 0 -> (x >= 0) ? x : 0
47640     // (x < -1) ? x : -1 -> (x <= -1) ? x : -1
47641     // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
47642     // the need for an extra compare against zero. e.g.
47643     // (a - b) > 0 : (a - b) ? 0 -> (a - b) >= 0 : (a - b) ? 0
47644     // subl   %esi, %edi
47645     // testl  %edi, %edi
47646     // movl   $0, %eax
47647     // cmovgl %edi, %eax
47648     // =>
47649     // xorl   %eax, %eax
47650     // subl   %esi, $edi
47651     // cmovsl %eax, %edi
47652     //
47653     // We can also canonicalize
47654     //  (x s> 1) ? x : 1 -> (x s>= 1) ? x : 1 -> (x s> 0) ? x : 1
47655     //  (x u> 1) ? x : 1 -> (x u>= 1) ? x : 1 -> (x != 0) ? x : 1
47656     // This allows the use of a test instruction for the compare.
47657     if (LHS == Cond0 && RHS == Cond1) {
47658       if ((CC == ISD::SETGT && (isNullConstant(RHS) || isOneConstant(RHS))) ||
47659           (CC == ISD::SETLT && isAllOnesConstant(RHS))) {
47660         ISD::CondCode NewCC = CC == ISD::SETGT ? ISD::SETGE : ISD::SETLE;
47661         Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
47662         return DAG.getSelect(DL, VT, Cond, LHS, RHS);
47663       }
47664       if (CC == ISD::SETUGT && isOneConstant(RHS)) {
47665         ISD::CondCode NewCC = ISD::SETUGE;
47666         Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
47667         return DAG.getSelect(DL, VT, Cond, LHS, RHS);
47668       }
47669     }
47670 
47671     // Similar to DAGCombine's select(or(CC0,CC1),X,Y) fold but for legal types.
47672     // fold eq + gt/lt nested selects into ge/le selects
47673     // select (cmpeq Cond0, Cond1), LHS, (select (cmpugt Cond0, Cond1), LHS, Y)
47674     // --> (select (cmpuge Cond0, Cond1), LHS, Y)
47675     // select (cmpslt Cond0, Cond1), LHS, (select (cmpeq Cond0, Cond1), LHS, Y)
47676     // --> (select (cmpsle Cond0, Cond1), LHS, Y)
47677     // .. etc ..
47678     if (RHS.getOpcode() == ISD::SELECT && RHS.getOperand(1) == LHS &&
47679         RHS.getOperand(0).getOpcode() == ISD::SETCC) {
47680       SDValue InnerSetCC = RHS.getOperand(0);
47681       ISD::CondCode InnerCC =
47682           cast<CondCodeSDNode>(InnerSetCC.getOperand(2))->get();
47683       if ((CC == ISD::SETEQ || InnerCC == ISD::SETEQ) &&
47684           Cond0 == InnerSetCC.getOperand(0) &&
47685           Cond1 == InnerSetCC.getOperand(1)) {
47686         ISD::CondCode NewCC;
47687         switch (CC == ISD::SETEQ ? InnerCC : CC) {
47688         case ISD::SETGT:  NewCC = ISD::SETGE; break;
47689         case ISD::SETLT:  NewCC = ISD::SETLE; break;
47690         case ISD::SETUGT: NewCC = ISD::SETUGE; break;
47691         case ISD::SETULT: NewCC = ISD::SETULE; break;
47692         default: NewCC = ISD::SETCC_INVALID; break;
47693         }
47694         if (NewCC != ISD::SETCC_INVALID) {
47695           Cond = DAG.getSetCC(DL, CondVT, Cond0, Cond1, NewCC);
47696           return DAG.getSelect(DL, VT, Cond, LHS, RHS.getOperand(2));
47697         }
47698       }
47699     }
47700   }
47701 
47702   // Check if the first operand is all zeros and Cond type is vXi1.
47703   // If this an avx512 target we can improve the use of zero masking by
47704   // swapping the operands and inverting the condition.
47705   if (N->getOpcode() == ISD::VSELECT && Cond.hasOneUse() &&
47706       Subtarget.hasAVX512() && CondVT.getVectorElementType() == MVT::i1 &&
47707       ISD::isBuildVectorAllZeros(LHS.getNode()) &&
47708       !ISD::isBuildVectorAllZeros(RHS.getNode())) {
47709     // Invert the cond to not(cond) : xor(op,allones)=not(op)
47710     SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
47711     // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
47712     return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
47713   }
47714 
47715   // Attempt to convert a (vXi1 bitcast(iX Cond)) selection mask before it might
47716   // get split by legalization.
47717   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::BITCAST &&
47718       CondVT.getVectorElementType() == MVT::i1 &&
47719       TLI.isTypeLegal(VT.getScalarType())) {
47720     EVT ExtCondVT = VT.changeVectorElementTypeToInteger();
47721     if (SDValue ExtCond = combineToExtendBoolVectorInReg(
47722             ISD::SIGN_EXTEND, DL, ExtCondVT, Cond, DAG, DCI, Subtarget)) {
47723       ExtCond = DAG.getNode(ISD::TRUNCATE, DL, CondVT, ExtCond);
47724       return DAG.getSelect(DL, VT, ExtCond, LHS, RHS);
47725     }
47726   }
47727 
47728   // Early exit check
47729   if (!TLI.isTypeLegal(VT) || isSoftF16(VT, Subtarget))
47730     return SDValue();
47731 
47732   if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
47733     return V;
47734 
47735   if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
47736     return V;
47737 
47738   if (SDValue V = narrowVectorSelect(N, DAG, Subtarget))
47739     return V;
47740 
47741   // select(~Cond, X, Y) -> select(Cond, Y, X)
47742   if (CondVT.getScalarType() != MVT::i1) {
47743     if (SDValue CondNot = IsNOT(Cond, DAG))
47744       return DAG.getNode(N->getOpcode(), DL, VT,
47745                          DAG.getBitcast(CondVT, CondNot), RHS, LHS);
47746 
47747     // pcmpgt(X, -1) -> pcmpgt(0, X) to help select/blendv just use the
47748     // signbit.
47749     if (Cond.getOpcode() == X86ISD::PCMPGT &&
47750         ISD::isBuildVectorAllOnes(Cond.getOperand(1).getNode()) &&
47751         Cond.hasOneUse()) {
47752       Cond = DAG.getNode(X86ISD::PCMPGT, DL, CondVT,
47753                          DAG.getConstant(0, DL, CondVT), Cond.getOperand(0));
47754       return DAG.getNode(N->getOpcode(), DL, VT, Cond, RHS, LHS);
47755     }
47756   }
47757 
47758   // Try to optimize vXi1 selects if both operands are either all constants or
47759   // bitcasts from scalar integer type. In that case we can convert the operands
47760   // to integer and use an integer select which will be converted to a CMOV.
47761   // We need to take a little bit of care to avoid creating an i64 type after
47762   // type legalization.
47763   if (N->getOpcode() == ISD::SELECT && VT.isVector() &&
47764       VT.getVectorElementType() == MVT::i1 &&
47765       (DCI.isBeforeLegalize() || (VT != MVT::v64i1 || Subtarget.is64Bit()))) {
47766     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
47767     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(IntVT)) {
47768       bool LHSIsConst = ISD::isBuildVectorOfConstantSDNodes(LHS.getNode());
47769       bool RHSIsConst = ISD::isBuildVectorOfConstantSDNodes(RHS.getNode());
47770 
47771       if ((LHSIsConst || (LHS.getOpcode() == ISD::BITCAST &&
47772                           LHS.getOperand(0).getValueType() == IntVT)) &&
47773           (RHSIsConst || (RHS.getOpcode() == ISD::BITCAST &&
47774                           RHS.getOperand(0).getValueType() == IntVT))) {
47775         if (LHSIsConst)
47776           LHS = combinevXi1ConstantToInteger(LHS, DAG);
47777         else
47778           LHS = LHS.getOperand(0);
47779 
47780         if (RHSIsConst)
47781           RHS = combinevXi1ConstantToInteger(RHS, DAG);
47782         else
47783           RHS = RHS.getOperand(0);
47784 
47785         SDValue Select = DAG.getSelect(DL, IntVT, Cond, LHS, RHS);
47786         return DAG.getBitcast(VT, Select);
47787       }
47788     }
47789   }
47790 
47791   // If this is "((X & C) == 0) ? Y : Z" and C is a constant mask vector of
47792   // single bits, then invert the predicate and swap the select operands.
47793   // This can lower using a vector shift bit-hack rather than mask and compare.
47794   if (DCI.isBeforeLegalize() && !Subtarget.hasAVX512() &&
47795       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
47796       Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1 &&
47797       Cond.getOperand(0).getOpcode() == ISD::AND &&
47798       isNullOrNullSplat(Cond.getOperand(1)) &&
47799       cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
47800       Cond.getOperand(0).getValueType() == VT) {
47801     // The 'and' mask must be composed of power-of-2 constants.
47802     SDValue And = Cond.getOperand(0);
47803     auto *C = isConstOrConstSplat(And.getOperand(1));
47804     if (C && C->getAPIntValue().isPowerOf2()) {
47805       // vselect (X & C == 0), LHS, RHS --> vselect (X & C != 0), RHS, LHS
47806       SDValue NotCond =
47807           DAG.getSetCC(DL, CondVT, And, Cond.getOperand(1), ISD::SETNE);
47808       return DAG.getSelect(DL, VT, NotCond, RHS, LHS);
47809     }
47810 
47811     // If we have a non-splat but still powers-of-2 mask, AVX1 can use pmulld
47812     // and AVX2 can use vpsllv{dq}. 8-bit lacks a proper shift or multiply.
47813     // 16-bit lacks a proper blendv.
47814     unsigned EltBitWidth = VT.getScalarSizeInBits();
47815     bool CanShiftBlend =
47816         TLI.isTypeLegal(VT) && ((Subtarget.hasAVX() && EltBitWidth == 32) ||
47817                                 (Subtarget.hasAVX2() && EltBitWidth == 64) ||
47818                                 (Subtarget.hasXOP()));
47819     if (CanShiftBlend &&
47820         ISD::matchUnaryPredicate(And.getOperand(1), [](ConstantSDNode *C) {
47821           return C->getAPIntValue().isPowerOf2();
47822         })) {
47823       // Create a left-shift constant to get the mask bits over to the sign-bit.
47824       SDValue Mask = And.getOperand(1);
47825       SmallVector<int, 32> ShlVals;
47826       for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
47827         auto *MaskVal = cast<ConstantSDNode>(Mask.getOperand(i));
47828         ShlVals.push_back(EltBitWidth - 1 -
47829                           MaskVal->getAPIntValue().exactLogBase2());
47830       }
47831       // vsel ((X & C) == 0), LHS, RHS --> vsel ((shl X, C') < 0), RHS, LHS
47832       SDValue ShlAmt = getConstVector(ShlVals, VT.getSimpleVT(), DAG, DL);
47833       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And.getOperand(0), ShlAmt);
47834       SDValue NewCond =
47835           DAG.getSetCC(DL, CondVT, Shl, Cond.getOperand(1), ISD::SETLT);
47836       return DAG.getSelect(DL, VT, NewCond, RHS, LHS);
47837     }
47838   }
47839 
47840   return SDValue();
47841 }
47842 
47843 /// Combine:
47844 ///   (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
47845 /// to:
47846 ///   (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
47847 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
47848 /// Note that this is only legal for some op/cc combinations.
47849 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
47850                                        SelectionDAG &DAG,
47851                                        const X86Subtarget &Subtarget) {
47852   // This combine only operates on CMP-like nodes.
47853   if (!(Cmp.getOpcode() == X86ISD::CMP ||
47854         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
47855     return SDValue();
47856 
47857   // Can't replace the cmp if it has more uses than the one we're looking at.
47858   // FIXME: We would like to be able to handle this, but would need to make sure
47859   // all uses were updated.
47860   if (!Cmp.hasOneUse())
47861     return SDValue();
47862 
47863   // This only applies to variations of the common case:
47864   //   (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
47865   //   (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
47866   //   (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
47867   //   (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
47868   // Using the proper condcodes (see below), overflow is checked for.
47869 
47870   // FIXME: We can generalize both constraints:
47871   // - XOR/OR/AND (if they were made to survive AtomicExpand)
47872   // - LHS != 1
47873   // if the result is compared.
47874 
47875   SDValue CmpLHS = Cmp.getOperand(0);
47876   SDValue CmpRHS = Cmp.getOperand(1);
47877   EVT CmpVT = CmpLHS.getValueType();
47878 
47879   if (!CmpLHS.hasOneUse())
47880     return SDValue();
47881 
47882   unsigned Opc = CmpLHS.getOpcode();
47883   if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
47884     return SDValue();
47885 
47886   SDValue OpRHS = CmpLHS.getOperand(2);
47887   auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
47888   if (!OpRHSC)
47889     return SDValue();
47890 
47891   APInt Addend = OpRHSC->getAPIntValue();
47892   if (Opc == ISD::ATOMIC_LOAD_SUB)
47893     Addend = -Addend;
47894 
47895   auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
47896   if (!CmpRHSC)
47897     return SDValue();
47898 
47899   APInt Comparison = CmpRHSC->getAPIntValue();
47900   APInt NegAddend = -Addend;
47901 
47902   // See if we can adjust the CC to make the comparison match the negated
47903   // addend.
47904   if (Comparison != NegAddend) {
47905     APInt IncComparison = Comparison + 1;
47906     if (IncComparison == NegAddend) {
47907       if (CC == X86::COND_A && !Comparison.isMaxValue()) {
47908         Comparison = IncComparison;
47909         CC = X86::COND_AE;
47910       } else if (CC == X86::COND_LE && !Comparison.isMaxSignedValue()) {
47911         Comparison = IncComparison;
47912         CC = X86::COND_L;
47913       }
47914     }
47915     APInt DecComparison = Comparison - 1;
47916     if (DecComparison == NegAddend) {
47917       if (CC == X86::COND_AE && !Comparison.isMinValue()) {
47918         Comparison = DecComparison;
47919         CC = X86::COND_A;
47920       } else if (CC == X86::COND_L && !Comparison.isMinSignedValue()) {
47921         Comparison = DecComparison;
47922         CC = X86::COND_LE;
47923       }
47924     }
47925   }
47926 
47927   // If the addend is the negation of the comparison value, then we can do
47928   // a full comparison by emitting the atomic arithmetic as a locked sub.
47929   if (Comparison == NegAddend) {
47930     // The CC is fine, but we need to rewrite the LHS of the comparison as an
47931     // atomic sub.
47932     auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
47933     auto AtomicSub = DAG.getAtomic(
47934         ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpVT,
47935         /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
47936         /*RHS*/ DAG.getConstant(NegAddend, SDLoc(CmpRHS), CmpVT),
47937         AN->getMemOperand());
47938     auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
47939     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
47940     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
47941     return LockOp;
47942   }
47943 
47944   // We can handle comparisons with zero in a number of cases by manipulating
47945   // the CC used.
47946   if (!Comparison.isZero())
47947     return SDValue();
47948 
47949   if (CC == X86::COND_S && Addend == 1)
47950     CC = X86::COND_LE;
47951   else if (CC == X86::COND_NS && Addend == 1)
47952     CC = X86::COND_G;
47953   else if (CC == X86::COND_G && Addend == -1)
47954     CC = X86::COND_GE;
47955   else if (CC == X86::COND_LE && Addend == -1)
47956     CC = X86::COND_L;
47957   else
47958     return SDValue();
47959 
47960   SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
47961   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
47962   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
47963   return LockOp;
47964 }
47965 
47966 // Check whether a boolean test is testing a boolean value generated by
47967 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
47968 // code.
47969 //
47970 // Simplify the following patterns:
47971 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
47972 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
47973 // to (Op EFLAGS Cond)
47974 //
47975 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
47976 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
47977 // to (Op EFLAGS !Cond)
47978 //
47979 // where Op could be BRCOND or CMOV.
47980 //
47981 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
47982   // This combine only operates on CMP-like nodes.
47983   if (!(Cmp.getOpcode() == X86ISD::CMP ||
47984         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
47985     return SDValue();
47986 
47987   // Quit if not used as a boolean value.
47988   if (CC != X86::COND_E && CC != X86::COND_NE)
47989     return SDValue();
47990 
47991   // Check CMP operands. One of them should be 0 or 1 and the other should be
47992   // an SetCC or extended from it.
47993   SDValue Op1 = Cmp.getOperand(0);
47994   SDValue Op2 = Cmp.getOperand(1);
47995 
47996   SDValue SetCC;
47997   const ConstantSDNode* C = nullptr;
47998   bool needOppositeCond = (CC == X86::COND_E);
47999   bool checkAgainstTrue = false; // Is it a comparison against 1?
48000 
48001   if ((C = dyn_cast<ConstantSDNode>(Op1)))
48002     SetCC = Op2;
48003   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
48004     SetCC = Op1;
48005   else // Quit if all operands are not constants.
48006     return SDValue();
48007 
48008   if (C->getZExtValue() == 1) {
48009     needOppositeCond = !needOppositeCond;
48010     checkAgainstTrue = true;
48011   } else if (C->getZExtValue() != 0)
48012     // Quit if the constant is neither 0 or 1.
48013     return SDValue();
48014 
48015   bool truncatedToBoolWithAnd = false;
48016   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
48017   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
48018          SetCC.getOpcode() == ISD::TRUNCATE ||
48019          SetCC.getOpcode() == ISD::AND) {
48020     if (SetCC.getOpcode() == ISD::AND) {
48021       int OpIdx = -1;
48022       if (isOneConstant(SetCC.getOperand(0)))
48023         OpIdx = 1;
48024       if (isOneConstant(SetCC.getOperand(1)))
48025         OpIdx = 0;
48026       if (OpIdx < 0)
48027         break;
48028       SetCC = SetCC.getOperand(OpIdx);
48029       truncatedToBoolWithAnd = true;
48030     } else
48031       SetCC = SetCC.getOperand(0);
48032   }
48033 
48034   switch (SetCC.getOpcode()) {
48035   case X86ISD::SETCC_CARRY:
48036     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
48037     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
48038     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
48039     // truncated to i1 using 'and'.
48040     if (checkAgainstTrue && !truncatedToBoolWithAnd)
48041       break;
48042     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
48043            "Invalid use of SETCC_CARRY!");
48044     [[fallthrough]];
48045   case X86ISD::SETCC:
48046     // Set the condition code or opposite one if necessary.
48047     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
48048     if (needOppositeCond)
48049       CC = X86::GetOppositeBranchCondition(CC);
48050     return SetCC.getOperand(1);
48051   case X86ISD::CMOV: {
48052     // Check whether false/true value has canonical one, i.e. 0 or 1.
48053     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
48054     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
48055     // Quit if true value is not a constant.
48056     if (!TVal)
48057       return SDValue();
48058     // Quit if false value is not a constant.
48059     if (!FVal) {
48060       SDValue Op = SetCC.getOperand(0);
48061       // Skip 'zext' or 'trunc' node.
48062       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
48063           Op.getOpcode() == ISD::TRUNCATE)
48064         Op = Op.getOperand(0);
48065       // A special case for rdrand/rdseed, where 0 is set if false cond is
48066       // found.
48067       if ((Op.getOpcode() != X86ISD::RDRAND &&
48068            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
48069         return SDValue();
48070     }
48071     // Quit if false value is not the constant 0 or 1.
48072     bool FValIsFalse = true;
48073     if (FVal && FVal->getZExtValue() != 0) {
48074       if (FVal->getZExtValue() != 1)
48075         return SDValue();
48076       // If FVal is 1, opposite cond is needed.
48077       needOppositeCond = !needOppositeCond;
48078       FValIsFalse = false;
48079     }
48080     // Quit if TVal is not the constant opposite of FVal.
48081     if (FValIsFalse && TVal->getZExtValue() != 1)
48082       return SDValue();
48083     if (!FValIsFalse && TVal->getZExtValue() != 0)
48084       return SDValue();
48085     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
48086     if (needOppositeCond)
48087       CC = X86::GetOppositeBranchCondition(CC);
48088     return SetCC.getOperand(3);
48089   }
48090   }
48091 
48092   return SDValue();
48093 }
48094 
48095 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
48096 /// Match:
48097 ///   (X86or (X86setcc) (X86setcc))
48098 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
48099 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
48100                                            X86::CondCode &CC1, SDValue &Flags,
48101                                            bool &isAnd) {
48102   if (Cond->getOpcode() == X86ISD::CMP) {
48103     if (!isNullConstant(Cond->getOperand(1)))
48104       return false;
48105 
48106     Cond = Cond->getOperand(0);
48107   }
48108 
48109   isAnd = false;
48110 
48111   SDValue SetCC0, SetCC1;
48112   switch (Cond->getOpcode()) {
48113   default: return false;
48114   case ISD::AND:
48115   case X86ISD::AND:
48116     isAnd = true;
48117     [[fallthrough]];
48118   case ISD::OR:
48119   case X86ISD::OR:
48120     SetCC0 = Cond->getOperand(0);
48121     SetCC1 = Cond->getOperand(1);
48122     break;
48123   };
48124 
48125   // Make sure we have SETCC nodes, using the same flags value.
48126   if (SetCC0.getOpcode() != X86ISD::SETCC ||
48127       SetCC1.getOpcode() != X86ISD::SETCC ||
48128       SetCC0->getOperand(1) != SetCC1->getOperand(1))
48129     return false;
48130 
48131   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
48132   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
48133   Flags = SetCC0->getOperand(1);
48134   return true;
48135 }
48136 
48137 // When legalizing carry, we create carries via add X, -1
48138 // If that comes from an actual carry, via setcc, we use the
48139 // carry directly.
48140 static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
48141   if (EFLAGS.getOpcode() == X86ISD::ADD) {
48142     if (isAllOnesConstant(EFLAGS.getOperand(1))) {
48143       bool FoundAndLSB = false;
48144       SDValue Carry = EFLAGS.getOperand(0);
48145       while (Carry.getOpcode() == ISD::TRUNCATE ||
48146              Carry.getOpcode() == ISD::ZERO_EXTEND ||
48147              (Carry.getOpcode() == ISD::AND &&
48148               isOneConstant(Carry.getOperand(1)))) {
48149         FoundAndLSB |= Carry.getOpcode() == ISD::AND;
48150         Carry = Carry.getOperand(0);
48151       }
48152       if (Carry.getOpcode() == X86ISD::SETCC ||
48153           Carry.getOpcode() == X86ISD::SETCC_CARRY) {
48154         // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
48155         uint64_t CarryCC = Carry.getConstantOperandVal(0);
48156         SDValue CarryOp1 = Carry.getOperand(1);
48157         if (CarryCC == X86::COND_B)
48158           return CarryOp1;
48159         if (CarryCC == X86::COND_A) {
48160           // Try to convert COND_A into COND_B in an attempt to facilitate
48161           // materializing "setb reg".
48162           //
48163           // Do not flip "e > c", where "c" is a constant, because Cmp
48164           // instruction cannot take an immediate as its first operand.
48165           //
48166           if (CarryOp1.getOpcode() == X86ISD::SUB &&
48167               CarryOp1.getNode()->hasOneUse() &&
48168               CarryOp1.getValueType().isInteger() &&
48169               !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
48170             SDValue SubCommute =
48171                 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
48172                             CarryOp1.getOperand(1), CarryOp1.getOperand(0));
48173             return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
48174           }
48175         }
48176         // If this is a check of the z flag of an add with 1, switch to the
48177         // C flag.
48178         if (CarryCC == X86::COND_E &&
48179             CarryOp1.getOpcode() == X86ISD::ADD &&
48180             isOneConstant(CarryOp1.getOperand(1)))
48181           return CarryOp1;
48182       } else if (FoundAndLSB) {
48183         SDLoc DL(Carry);
48184         SDValue BitNo = DAG.getConstant(0, DL, Carry.getValueType());
48185         if (Carry.getOpcode() == ISD::SRL) {
48186           BitNo = Carry.getOperand(1);
48187           Carry = Carry.getOperand(0);
48188         }
48189         return getBT(Carry, BitNo, DL, DAG);
48190       }
48191     }
48192   }
48193 
48194   return SDValue();
48195 }
48196 
48197 /// If we are inverting an PTEST/TESTP operand, attempt to adjust the CC
48198 /// to avoid the inversion.
48199 static SDValue combinePTESTCC(SDValue EFLAGS, X86::CondCode &CC,
48200                               SelectionDAG &DAG,
48201                               const X86Subtarget &Subtarget) {
48202   // TODO: Handle X86ISD::KTEST/X86ISD::KORTEST.
48203   if (EFLAGS.getOpcode() != X86ISD::PTEST &&
48204       EFLAGS.getOpcode() != X86ISD::TESTP)
48205     return SDValue();
48206 
48207   // PTEST/TESTP sets EFLAGS as:
48208   // TESTZ: ZF = (Op0 & Op1) == 0
48209   // TESTC: CF = (~Op0 & Op1) == 0
48210   // TESTNZC: ZF == 0 && CF == 0
48211   MVT VT = EFLAGS.getSimpleValueType();
48212   SDValue Op0 = EFLAGS.getOperand(0);
48213   SDValue Op1 = EFLAGS.getOperand(1);
48214   MVT OpVT = Op0.getSimpleValueType();
48215 
48216   // TEST*(~X,Y) == TEST*(X,Y)
48217   if (SDValue NotOp0 = IsNOT(Op0, DAG)) {
48218     X86::CondCode InvCC;
48219     switch (CC) {
48220     case X86::COND_B:
48221       // testc -> testz.
48222       InvCC = X86::COND_E;
48223       break;
48224     case X86::COND_AE:
48225       // !testc -> !testz.
48226       InvCC = X86::COND_NE;
48227       break;
48228     case X86::COND_E:
48229       // testz -> testc.
48230       InvCC = X86::COND_B;
48231       break;
48232     case X86::COND_NE:
48233       // !testz -> !testc.
48234       InvCC = X86::COND_AE;
48235       break;
48236     case X86::COND_A:
48237     case X86::COND_BE:
48238       // testnzc -> testnzc (no change).
48239       InvCC = CC;
48240       break;
48241     default:
48242       InvCC = X86::COND_INVALID;
48243       break;
48244     }
48245 
48246     if (InvCC != X86::COND_INVALID) {
48247       CC = InvCC;
48248       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
48249                          DAG.getBitcast(OpVT, NotOp0), Op1);
48250     }
48251   }
48252 
48253   if (CC == X86::COND_B || CC == X86::COND_AE) {
48254     // TESTC(X,~X) == TESTC(X,-1)
48255     if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
48256       if (peekThroughBitcasts(NotOp1) == peekThroughBitcasts(Op0)) {
48257         SDLoc DL(EFLAGS);
48258         return DAG.getNode(
48259             EFLAGS.getOpcode(), DL, VT, DAG.getBitcast(OpVT, NotOp1),
48260             DAG.getBitcast(OpVT,
48261                            DAG.getAllOnesConstant(DL, NotOp1.getValueType())));
48262       }
48263     }
48264   }
48265 
48266   if (CC == X86::COND_E || CC == X86::COND_NE) {
48267     // TESTZ(X,~Y) == TESTC(Y,X)
48268     if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
48269       CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
48270       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
48271                          DAG.getBitcast(OpVT, NotOp1), Op0);
48272     }
48273 
48274     if (Op0 == Op1) {
48275       SDValue BC = peekThroughBitcasts(Op0);
48276       EVT BCVT = BC.getValueType();
48277 
48278       // TESTZ(AND(X,Y),AND(X,Y)) == TESTZ(X,Y)
48279       if (BC.getOpcode() == ISD::AND || BC.getOpcode() == X86ISD::FAND) {
48280         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
48281                            DAG.getBitcast(OpVT, BC.getOperand(0)),
48282                            DAG.getBitcast(OpVT, BC.getOperand(1)));
48283       }
48284 
48285       // TESTZ(AND(~X,Y),AND(~X,Y)) == TESTC(X,Y)
48286       if (BC.getOpcode() == X86ISD::ANDNP || BC.getOpcode() == X86ISD::FANDN) {
48287         CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
48288         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
48289                            DAG.getBitcast(OpVT, BC.getOperand(0)),
48290                            DAG.getBitcast(OpVT, BC.getOperand(1)));
48291       }
48292 
48293       // If every element is an all-sign value, see if we can use TESTP/MOVMSK
48294       // to more efficiently extract the sign bits and compare that.
48295       // TODO: Handle TESTC with comparison inversion.
48296       // TODO: Can we remove SimplifyMultipleUseDemandedBits and rely on
48297       // TESTP/MOVMSK combines to make sure its never worse than PTEST?
48298       if (BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT)) {
48299         unsigned EltBits = BCVT.getScalarSizeInBits();
48300         if (DAG.ComputeNumSignBits(BC) == EltBits) {
48301           assert(VT == MVT::i32 && "Expected i32 EFLAGS comparison result");
48302           APInt SignMask = APInt::getSignMask(EltBits);
48303           const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48304           if (SDValue Res =
48305                   TLI.SimplifyMultipleUseDemandedBits(BC, SignMask, DAG)) {
48306             // For vXi16 cases we need to use pmovmksb and extract every other
48307             // sign bit.
48308             SDLoc DL(EFLAGS);
48309             if ((EltBits == 32 || EltBits == 64) && Subtarget.hasAVX()) {
48310               MVT FloatSVT = MVT::getFloatingPointVT(EltBits);
48311               MVT FloatVT =
48312                   MVT::getVectorVT(FloatSVT, OpVT.getSizeInBits() / EltBits);
48313               Res = DAG.getBitcast(FloatVT, Res);
48314               return DAG.getNode(X86ISD::TESTP, SDLoc(EFLAGS), VT, Res, Res);
48315             } else if (EltBits == 16) {
48316               MVT MovmskVT = BCVT.is128BitVector() ? MVT::v16i8 : MVT::v32i8;
48317               Res = DAG.getBitcast(MovmskVT, Res);
48318               Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
48319               Res = DAG.getNode(ISD::AND, DL, MVT::i32, Res,
48320                                 DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
48321             } else {
48322               Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
48323             }
48324             return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Res,
48325                                DAG.getConstant(0, DL, MVT::i32));
48326           }
48327         }
48328       }
48329     }
48330 
48331     // TESTZ(-1,X) == TESTZ(X,X)
48332     if (ISD::isBuildVectorAllOnes(Op0.getNode()))
48333       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op1, Op1);
48334 
48335     // TESTZ(X,-1) == TESTZ(X,X)
48336     if (ISD::isBuildVectorAllOnes(Op1.getNode()))
48337       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op0, Op0);
48338 
48339     // TESTZ(OR(LO(X),HI(X)),OR(LO(Y),HI(Y))) -> TESTZ(X,Y)
48340     // TODO: Add COND_NE handling?
48341     if (CC == X86::COND_E && OpVT.is128BitVector() && Subtarget.hasAVX()) {
48342       SDValue Src0 = peekThroughBitcasts(Op0);
48343       SDValue Src1 = peekThroughBitcasts(Op1);
48344       if (Src0.getOpcode() == ISD::OR && Src1.getOpcode() == ISD::OR) {
48345         Src0 = getSplitVectorSrc(peekThroughBitcasts(Src0.getOperand(0)),
48346                                  peekThroughBitcasts(Src0.getOperand(1)), true);
48347         Src1 = getSplitVectorSrc(peekThroughBitcasts(Src1.getOperand(0)),
48348                                  peekThroughBitcasts(Src1.getOperand(1)), true);
48349         if (Src0 && Src1) {
48350           MVT OpVT2 = OpVT.getDoubleNumVectorElementsVT();
48351           return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
48352                              DAG.getBitcast(OpVT2, Src0),
48353                              DAG.getBitcast(OpVT2, Src1));
48354         }
48355       }
48356     }
48357   }
48358 
48359   return SDValue();
48360 }
48361 
48362 // Attempt to simplify the MOVMSK input based on the comparison type.
48363 static SDValue combineSetCCMOVMSK(SDValue EFLAGS, X86::CondCode &CC,
48364                                   SelectionDAG &DAG,
48365                                   const X86Subtarget &Subtarget) {
48366   // Handle eq/ne against zero (any_of).
48367   // Handle eq/ne against -1 (all_of).
48368   if (!(CC == X86::COND_E || CC == X86::COND_NE))
48369     return SDValue();
48370   if (EFLAGS.getValueType() != MVT::i32)
48371     return SDValue();
48372   unsigned CmpOpcode = EFLAGS.getOpcode();
48373   if (CmpOpcode != X86ISD::CMP && CmpOpcode != X86ISD::SUB)
48374     return SDValue();
48375   auto *CmpConstant = dyn_cast<ConstantSDNode>(EFLAGS.getOperand(1));
48376   if (!CmpConstant)
48377     return SDValue();
48378   const APInt &CmpVal = CmpConstant->getAPIntValue();
48379 
48380   SDValue CmpOp = EFLAGS.getOperand(0);
48381   unsigned CmpBits = CmpOp.getValueSizeInBits();
48382   assert(CmpBits == CmpVal.getBitWidth() && "Value size mismatch");
48383 
48384   // Peek through any truncate.
48385   if (CmpOp.getOpcode() == ISD::TRUNCATE)
48386     CmpOp = CmpOp.getOperand(0);
48387 
48388   // Bail if we don't find a MOVMSK.
48389   if (CmpOp.getOpcode() != X86ISD::MOVMSK)
48390     return SDValue();
48391 
48392   SDValue Vec = CmpOp.getOperand(0);
48393   MVT VecVT = Vec.getSimpleValueType();
48394   assert((VecVT.is128BitVector() || VecVT.is256BitVector()) &&
48395          "Unexpected MOVMSK operand");
48396   unsigned NumElts = VecVT.getVectorNumElements();
48397   unsigned NumEltBits = VecVT.getScalarSizeInBits();
48398 
48399   bool IsAnyOf = CmpOpcode == X86ISD::CMP && CmpVal.isZero();
48400   bool IsAllOf = (CmpOpcode == X86ISD::SUB || CmpOpcode == X86ISD::CMP) &&
48401                  NumElts <= CmpBits && CmpVal.isMask(NumElts);
48402   if (!IsAnyOf && !IsAllOf)
48403     return SDValue();
48404 
48405   // TODO: Check more combining cases for me.
48406   // Here we check the cmp use number to decide do combining or not.
48407   // Currently we only get 2 tests about combining "MOVMSK(CONCAT(..))"
48408   // and "MOVMSK(PCMPEQ(..))" are fit to use this constraint.
48409   bool IsOneUse = CmpOp.getNode()->hasOneUse();
48410 
48411   // See if we can peek through to a vector with a wider element type, if the
48412   // signbits extend down to all the sub-elements as well.
48413   // Calling MOVMSK with the wider type, avoiding the bitcast, helps expose
48414   // potential SimplifyDemandedBits/Elts cases.
48415   // If we looked through a truncate that discard bits, we can't do this
48416   // transform.
48417   // FIXME: We could do this transform for truncates that discarded bits by
48418   // inserting an AND mask between the new MOVMSK and the CMP.
48419   if (Vec.getOpcode() == ISD::BITCAST && NumElts <= CmpBits) {
48420     SDValue BC = peekThroughBitcasts(Vec);
48421     MVT BCVT = BC.getSimpleValueType();
48422     unsigned BCNumElts = BCVT.getVectorNumElements();
48423     unsigned BCNumEltBits = BCVT.getScalarSizeInBits();
48424     if ((BCNumEltBits == 32 || BCNumEltBits == 64) &&
48425         BCNumEltBits > NumEltBits &&
48426         DAG.ComputeNumSignBits(BC) > (BCNumEltBits - NumEltBits)) {
48427       SDLoc DL(EFLAGS);
48428       APInt CmpMask = APInt::getLowBitsSet(32, IsAnyOf ? 0 : BCNumElts);
48429       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
48430                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, BC),
48431                          DAG.getConstant(CmpMask, DL, MVT::i32));
48432     }
48433   }
48434 
48435   // MOVMSK(CONCAT(X,Y)) == 0 ->  MOVMSK(OR(X,Y)).
48436   // MOVMSK(CONCAT(X,Y)) != 0 ->  MOVMSK(OR(X,Y)).
48437   // MOVMSK(CONCAT(X,Y)) == -1 ->  MOVMSK(AND(X,Y)).
48438   // MOVMSK(CONCAT(X,Y)) != -1 ->  MOVMSK(AND(X,Y)).
48439   if (VecVT.is256BitVector() && NumElts <= CmpBits && IsOneUse) {
48440     SmallVector<SDValue> Ops;
48441     if (collectConcatOps(peekThroughBitcasts(Vec).getNode(), Ops, DAG) &&
48442         Ops.size() == 2) {
48443       SDLoc DL(EFLAGS);
48444       EVT SubVT = Ops[0].getValueType().changeTypeToInteger();
48445       APInt CmpMask = APInt::getLowBitsSet(32, IsAnyOf ? 0 : NumElts / 2);
48446       SDValue V = DAG.getNode(IsAnyOf ? ISD::OR : ISD::AND, DL, SubVT,
48447                               DAG.getBitcast(SubVT, Ops[0]),
48448                               DAG.getBitcast(SubVT, Ops[1]));
48449       V = DAG.getBitcast(VecVT.getHalfNumVectorElementsVT(), V);
48450       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
48451                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V),
48452                          DAG.getConstant(CmpMask, DL, MVT::i32));
48453     }
48454   }
48455 
48456   // MOVMSK(PCMPEQ(X,0)) == -1 -> PTESTZ(X,X).
48457   // MOVMSK(PCMPEQ(X,0)) != -1 -> !PTESTZ(X,X).
48458   // MOVMSK(PCMPEQ(X,Y)) == -1 -> PTESTZ(XOR(X,Y),XOR(X,Y)).
48459   // MOVMSK(PCMPEQ(X,Y)) != -1 -> !PTESTZ(XOR(X,Y),XOR(X,Y)).
48460   if (IsAllOf && Subtarget.hasSSE41() && IsOneUse) {
48461     MVT TestVT = VecVT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
48462     SDValue BC = peekThroughBitcasts(Vec);
48463     // Ensure MOVMSK was testing every signbit of BC.
48464     if (BC.getValueType().getVectorNumElements() <= NumElts) {
48465       if (BC.getOpcode() == X86ISD::PCMPEQ) {
48466         SDValue V = DAG.getNode(ISD::XOR, SDLoc(BC), BC.getValueType(),
48467                                 BC.getOperand(0), BC.getOperand(1));
48468         V = DAG.getBitcast(TestVT, V);
48469         return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
48470       }
48471       // Check for 256-bit split vector cases.
48472       if (BC.getOpcode() == ISD::AND &&
48473           BC.getOperand(0).getOpcode() == X86ISD::PCMPEQ &&
48474           BC.getOperand(1).getOpcode() == X86ISD::PCMPEQ) {
48475         SDValue LHS = BC.getOperand(0);
48476         SDValue RHS = BC.getOperand(1);
48477         LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), LHS.getValueType(),
48478                           LHS.getOperand(0), LHS.getOperand(1));
48479         RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), RHS.getValueType(),
48480                           RHS.getOperand(0), RHS.getOperand(1));
48481         LHS = DAG.getBitcast(TestVT, LHS);
48482         RHS = DAG.getBitcast(TestVT, RHS);
48483         SDValue V = DAG.getNode(ISD::OR, SDLoc(EFLAGS), TestVT, LHS, RHS);
48484         return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
48485       }
48486     }
48487   }
48488 
48489   // See if we can avoid a PACKSS by calling MOVMSK on the sources.
48490   // For vXi16 cases we can use a v2Xi8 PMOVMSKB. We must mask out
48491   // sign bits prior to the comparison with zero unless we know that
48492   // the vXi16 splats the sign bit down to the lower i8 half.
48493   // TODO: Handle all_of patterns.
48494   if (Vec.getOpcode() == X86ISD::PACKSS && VecVT == MVT::v16i8) {
48495     SDValue VecOp0 = Vec.getOperand(0);
48496     SDValue VecOp1 = Vec.getOperand(1);
48497     bool SignExt0 = DAG.ComputeNumSignBits(VecOp0) > 8;
48498     bool SignExt1 = DAG.ComputeNumSignBits(VecOp1) > 8;
48499     // PMOVMSKB(PACKSSBW(X, undef)) -> PMOVMSKB(BITCAST_v16i8(X)) & 0xAAAA.
48500     if (IsAnyOf && CmpBits == 8 && VecOp1.isUndef()) {
48501       SDLoc DL(EFLAGS);
48502       SDValue Result = DAG.getBitcast(MVT::v16i8, VecOp0);
48503       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
48504       Result = DAG.getZExtOrTrunc(Result, DL, MVT::i16);
48505       if (!SignExt0) {
48506         Result = DAG.getNode(ISD::AND, DL, MVT::i16, Result,
48507                              DAG.getConstant(0xAAAA, DL, MVT::i16));
48508       }
48509       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
48510                          DAG.getConstant(0, DL, MVT::i16));
48511     }
48512     // PMOVMSKB(PACKSSBW(LO(X), HI(X)))
48513     // -> PMOVMSKB(BITCAST_v32i8(X)) & 0xAAAAAAAA.
48514     if (CmpBits >= 16 && Subtarget.hasInt256() &&
48515         (IsAnyOf || (SignExt0 && SignExt1))) {
48516       if (SDValue Src = getSplitVectorSrc(VecOp0, VecOp1, true)) {
48517         SDLoc DL(EFLAGS);
48518         SDValue Result = peekThroughBitcasts(Src);
48519         if (IsAllOf && Result.getOpcode() == X86ISD::PCMPEQ &&
48520             Result.getValueType().getVectorNumElements() <= NumElts) {
48521           SDValue V = DAG.getNode(ISD::XOR, DL, Result.getValueType(),
48522                                   Result.getOperand(0), Result.getOperand(1));
48523           V = DAG.getBitcast(MVT::v4i64, V);
48524           return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
48525         }
48526         Result = DAG.getBitcast(MVT::v32i8, Result);
48527         Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
48528         unsigned CmpMask = IsAnyOf ? 0 : 0xFFFFFFFF;
48529         if (!SignExt0 || !SignExt1) {
48530           assert(IsAnyOf &&
48531                  "Only perform v16i16 signmasks for any_of patterns");
48532           Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
48533                                DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
48534         }
48535         return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
48536                            DAG.getConstant(CmpMask, DL, MVT::i32));
48537       }
48538     }
48539   }
48540 
48541   // MOVMSK(SHUFFLE(X,u)) -> MOVMSK(X) iff every element is referenced.
48542   // Since we peek through a bitcast, we need to be careful if the base vector
48543   // type has smaller elements than the MOVMSK type.  In that case, even if
48544   // all the elements are demanded by the shuffle mask, only the "high"
48545   // elements which have highbits that align with highbits in the MOVMSK vec
48546   // elements are actually demanded. A simplification of spurious operations
48547   // on the "low" elements take place during other simplifications.
48548   //
48549   // For example:
48550   // MOVMSK64(BITCAST(SHUF32 X, (1,0,3,2))) even though all the elements are
48551   // demanded, because we are swapping around the result can change.
48552   //
48553   // To address this, we check that we can scale the shuffle mask to MOVMSK
48554   // element width (this will ensure "high" elements match). Its slightly overly
48555   // conservative, but fine for an edge case fold.
48556   SmallVector<int, 32> ShuffleMask, ScaledMaskUnused;
48557   SmallVector<SDValue, 2> ShuffleInputs;
48558   if (NumElts <= CmpBits &&
48559       getTargetShuffleInputs(peekThroughBitcasts(Vec), ShuffleInputs,
48560                              ShuffleMask, DAG) &&
48561       ShuffleInputs.size() == 1 && !isAnyZeroOrUndef(ShuffleMask) &&
48562       ShuffleInputs[0].getValueSizeInBits() == VecVT.getSizeInBits() &&
48563       scaleShuffleElements(ShuffleMask, NumElts, ScaledMaskUnused)) {
48564     unsigned NumShuffleElts = ShuffleMask.size();
48565     APInt DemandedElts = APInt::getZero(NumShuffleElts);
48566     for (int M : ShuffleMask) {
48567       assert(0 <= M && M < (int)NumShuffleElts && "Bad unary shuffle index");
48568       DemandedElts.setBit(M);
48569     }
48570     if (DemandedElts.isAllOnes()) {
48571       SDLoc DL(EFLAGS);
48572       SDValue Result = DAG.getBitcast(VecVT, ShuffleInputs[0]);
48573       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
48574       Result =
48575           DAG.getZExtOrTrunc(Result, DL, EFLAGS.getOperand(0).getValueType());
48576       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
48577                          EFLAGS.getOperand(1));
48578     }
48579   }
48580 
48581   // MOVMSKPS(V) !=/== 0 -> TESTPS(V,V)
48582   // MOVMSKPD(V) !=/== 0 -> TESTPD(V,V)
48583   // MOVMSKPS(V) !=/== -1 -> TESTPS(V,V)
48584   // MOVMSKPD(V) !=/== -1 -> TESTPD(V,V)
48585   // iff every element is referenced.
48586   if (NumElts <= CmpBits && Subtarget.hasAVX() &&
48587       !Subtarget.preferMovmskOverVTest() && IsOneUse &&
48588       (NumEltBits == 32 || NumEltBits == 64)) {
48589     SDLoc DL(EFLAGS);
48590     MVT FloatSVT = MVT::getFloatingPointVT(NumEltBits);
48591     MVT FloatVT = MVT::getVectorVT(FloatSVT, NumElts);
48592     MVT IntVT = FloatVT.changeVectorElementTypeToInteger();
48593     SDValue LHS = Vec;
48594     SDValue RHS = IsAnyOf ? Vec : DAG.getAllOnesConstant(DL, IntVT);
48595     CC = IsAnyOf ? CC : (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
48596     return DAG.getNode(X86ISD::TESTP, DL, MVT::i32,
48597                        DAG.getBitcast(FloatVT, LHS),
48598                        DAG.getBitcast(FloatVT, RHS));
48599   }
48600 
48601   return SDValue();
48602 }
48603 
48604 /// Optimize an EFLAGS definition used according to the condition code \p CC
48605 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
48606 /// uses of chain values.
48607 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
48608                                   SelectionDAG &DAG,
48609                                   const X86Subtarget &Subtarget) {
48610   if (CC == X86::COND_B)
48611     if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
48612       return Flags;
48613 
48614   if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
48615     return R;
48616 
48617   if (SDValue R = combinePTESTCC(EFLAGS, CC, DAG, Subtarget))
48618     return R;
48619 
48620   if (SDValue R = combineSetCCMOVMSK(EFLAGS, CC, DAG, Subtarget))
48621     return R;
48622 
48623   return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
48624 }
48625 
48626 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
48627 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
48628                            TargetLowering::DAGCombinerInfo &DCI,
48629                            const X86Subtarget &Subtarget) {
48630   SDLoc DL(N);
48631 
48632   SDValue FalseOp = N->getOperand(0);
48633   SDValue TrueOp = N->getOperand(1);
48634   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
48635   SDValue Cond = N->getOperand(3);
48636 
48637   // cmov X, X, ?, ? --> X
48638   if (TrueOp == FalseOp)
48639     return TrueOp;
48640 
48641   // Try to simplify the EFLAGS and condition code operands.
48642   // We can't always do this as FCMOV only supports a subset of X86 cond.
48643   if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
48644     if (!(FalseOp.getValueType() == MVT::f80 ||
48645           (FalseOp.getValueType() == MVT::f64 && !Subtarget.hasSSE2()) ||
48646           (FalseOp.getValueType() == MVT::f32 && !Subtarget.hasSSE1())) ||
48647         !Subtarget.canUseCMOV() || hasFPCMov(CC)) {
48648       SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
48649                        Flags};
48650       return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
48651     }
48652   }
48653 
48654   // If this is a select between two integer constants, try to do some
48655   // optimizations.  Note that the operands are ordered the opposite of SELECT
48656   // operands.
48657   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
48658     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
48659       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
48660       // larger than FalseC (the false value).
48661       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
48662         CC = X86::GetOppositeBranchCondition(CC);
48663         std::swap(TrueC, FalseC);
48664         std::swap(TrueOp, FalseOp);
48665       }
48666 
48667       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
48668       // This is efficient for any integer data type (including i8/i16) and
48669       // shift amount.
48670       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
48671         Cond = getSETCC(CC, Cond, DL, DAG);
48672 
48673         // Zero extend the condition if needed.
48674         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
48675 
48676         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
48677         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
48678                            DAG.getConstant(ShAmt, DL, MVT::i8));
48679         return Cond;
48680       }
48681 
48682       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
48683       // for any integer data type, including i8/i16.
48684       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
48685         Cond = getSETCC(CC, Cond, DL, DAG);
48686 
48687         // Zero extend the condition if needed.
48688         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
48689                            FalseC->getValueType(0), Cond);
48690         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
48691                            SDValue(FalseC, 0));
48692         return Cond;
48693       }
48694 
48695       // Optimize cases that will turn into an LEA instruction.  This requires
48696       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
48697       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
48698         APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
48699         assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&
48700                "Implicit constant truncation");
48701 
48702         bool isFastMultiplier = false;
48703         if (Diff.ult(10)) {
48704           switch (Diff.getZExtValue()) {
48705           default: break;
48706           case 1:  // result = add base, cond
48707           case 2:  // result = lea base(    , cond*2)
48708           case 3:  // result = lea base(cond, cond*2)
48709           case 4:  // result = lea base(    , cond*4)
48710           case 5:  // result = lea base(cond, cond*4)
48711           case 8:  // result = lea base(    , cond*8)
48712           case 9:  // result = lea base(cond, cond*8)
48713             isFastMultiplier = true;
48714             break;
48715           }
48716         }
48717 
48718         if (isFastMultiplier) {
48719           Cond = getSETCC(CC, Cond, DL ,DAG);
48720           // Zero extend the condition if needed.
48721           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
48722                              Cond);
48723           // Scale the condition by the difference.
48724           if (Diff != 1)
48725             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
48726                                DAG.getConstant(Diff, DL, Cond.getValueType()));
48727 
48728           // Add the base if non-zero.
48729           if (FalseC->getAPIntValue() != 0)
48730             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
48731                                SDValue(FalseC, 0));
48732           return Cond;
48733         }
48734       }
48735     }
48736   }
48737 
48738   // Handle these cases:
48739   //   (select (x != c), e, c) -> select (x != c), e, x),
48740   //   (select (x == c), c, e) -> select (x == c), x, e)
48741   // where the c is an integer constant, and the "select" is the combination
48742   // of CMOV and CMP.
48743   //
48744   // The rationale for this change is that the conditional-move from a constant
48745   // needs two instructions, however, conditional-move from a register needs
48746   // only one instruction.
48747   //
48748   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
48749   //  some instruction-combining opportunities. This opt needs to be
48750   //  postponed as late as possible.
48751   //
48752   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
48753     // the DCI.xxxx conditions are provided to postpone the optimization as
48754     // late as possible.
48755 
48756     ConstantSDNode *CmpAgainst = nullptr;
48757     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
48758         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
48759         !isa<ConstantSDNode>(Cond.getOperand(0))) {
48760 
48761       if (CC == X86::COND_NE &&
48762           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
48763         CC = X86::GetOppositeBranchCondition(CC);
48764         std::swap(TrueOp, FalseOp);
48765       }
48766 
48767       if (CC == X86::COND_E &&
48768           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
48769         SDValue Ops[] = {FalseOp, Cond.getOperand(0),
48770                          DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
48771         return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
48772       }
48773     }
48774   }
48775 
48776   // Transform:
48777   //
48778   //   (cmov 1 T (uge T 2))
48779   //
48780   // to:
48781   //
48782   //   (adc T 0 (sub T 1))
48783   if (CC == X86::COND_AE && isOneConstant(FalseOp) &&
48784       Cond.getOpcode() == X86ISD::SUB && Cond->hasOneUse()) {
48785     SDValue Cond0 = Cond.getOperand(0);
48786     if (Cond0.getOpcode() == ISD::TRUNCATE)
48787       Cond0 = Cond0.getOperand(0);
48788     auto *Sub1C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
48789     if (Cond0 == TrueOp && Sub1C && Sub1C->getZExtValue() == 2) {
48790       EVT CondVT = Cond->getValueType(0);
48791       EVT OuterVT = N->getValueType(0);
48792       // Subtract 1 and generate a carry.
48793       SDValue NewSub =
48794           DAG.getNode(X86ISD::SUB, DL, Cond->getVTList(), Cond.getOperand(0),
48795                       DAG.getConstant(1, DL, CondVT));
48796       SDValue EFLAGS(NewSub.getNode(), 1);
48797       return DAG.getNode(X86ISD::ADC, DL, DAG.getVTList(OuterVT, MVT::i32),
48798                          TrueOp, DAG.getConstant(0, DL, OuterVT), EFLAGS);
48799     }
48800   }
48801 
48802   // Fold and/or of setcc's to double CMOV:
48803   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
48804   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
48805   //
48806   // This combine lets us generate:
48807   //   cmovcc1 (jcc1 if we don't have CMOV)
48808   //   cmovcc2 (same)
48809   // instead of:
48810   //   setcc1
48811   //   setcc2
48812   //   and/or
48813   //   cmovne (jne if we don't have CMOV)
48814   // When we can't use the CMOV instruction, it might increase branch
48815   // mispredicts.
48816   // When we can use CMOV, or when there is no mispredict, this improves
48817   // throughput and reduces register pressure.
48818   //
48819   if (CC == X86::COND_NE) {
48820     SDValue Flags;
48821     X86::CondCode CC0, CC1;
48822     bool isAndSetCC;
48823     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
48824       if (isAndSetCC) {
48825         std::swap(FalseOp, TrueOp);
48826         CC0 = X86::GetOppositeBranchCondition(CC0);
48827         CC1 = X86::GetOppositeBranchCondition(CC1);
48828       }
48829 
48830       SDValue LOps[] = {FalseOp, TrueOp,
48831                         DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
48832       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
48833       SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
48834                        Flags};
48835       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
48836       return CMOV;
48837     }
48838   }
48839 
48840   // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
48841   //      (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
48842   // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
48843   //    (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
48844   if ((CC == X86::COND_NE || CC == X86::COND_E) &&
48845       Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
48846     SDValue Add = TrueOp;
48847     SDValue Const = FalseOp;
48848     // Canonicalize the condition code for easier matching and output.
48849     if (CC == X86::COND_E)
48850       std::swap(Add, Const);
48851 
48852     // We might have replaced the constant in the cmov with the LHS of the
48853     // compare. If so change it to the RHS of the compare.
48854     if (Const == Cond.getOperand(0))
48855       Const = Cond.getOperand(1);
48856 
48857     // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
48858     if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
48859         Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
48860         (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
48861          Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
48862         Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
48863       EVT VT = N->getValueType(0);
48864       // This should constant fold.
48865       SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
48866       SDValue CMov =
48867           DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
48868                       DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
48869       return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
48870     }
48871   }
48872 
48873   return SDValue();
48874 }
48875 
48876 /// Different mul shrinking modes.
48877 enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
48878 
48879 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
48880   EVT VT = N->getOperand(0).getValueType();
48881   if (VT.getScalarSizeInBits() != 32)
48882     return false;
48883 
48884   assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
48885   unsigned SignBits[2] = {1, 1};
48886   bool IsPositive[2] = {false, false};
48887   for (unsigned i = 0; i < 2; i++) {
48888     SDValue Opd = N->getOperand(i);
48889 
48890     SignBits[i] = DAG.ComputeNumSignBits(Opd);
48891     IsPositive[i] = DAG.SignBitIsZero(Opd);
48892   }
48893 
48894   bool AllPositive = IsPositive[0] && IsPositive[1];
48895   unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
48896   // When ranges are from -128 ~ 127, use MULS8 mode.
48897   if (MinSignBits >= 25)
48898     Mode = ShrinkMode::MULS8;
48899   // When ranges are from 0 ~ 255, use MULU8 mode.
48900   else if (AllPositive && MinSignBits >= 24)
48901     Mode = ShrinkMode::MULU8;
48902   // When ranges are from -32768 ~ 32767, use MULS16 mode.
48903   else if (MinSignBits >= 17)
48904     Mode = ShrinkMode::MULS16;
48905   // When ranges are from 0 ~ 65535, use MULU16 mode.
48906   else if (AllPositive && MinSignBits >= 16)
48907     Mode = ShrinkMode::MULU16;
48908   else
48909     return false;
48910   return true;
48911 }
48912 
48913 /// When the operands of vector mul are extended from smaller size values,
48914 /// like i8 and i16, the type of mul may be shrinked to generate more
48915 /// efficient code. Two typical patterns are handled:
48916 /// Pattern1:
48917 ///     %2 = sext/zext <N x i8> %1 to <N x i32>
48918 ///     %4 = sext/zext <N x i8> %3 to <N x i32>
48919 //   or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
48920 ///     %5 = mul <N x i32> %2, %4
48921 ///
48922 /// Pattern2:
48923 ///     %2 = zext/sext <N x i16> %1 to <N x i32>
48924 ///     %4 = zext/sext <N x i16> %3 to <N x i32>
48925 ///  or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
48926 ///     %5 = mul <N x i32> %2, %4
48927 ///
48928 /// There are four mul shrinking modes:
48929 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
48930 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
48931 /// generate pmullw+sext32 for it (MULS8 mode).
48932 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
48933 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
48934 /// generate pmullw+zext32 for it (MULU8 mode).
48935 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
48936 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
48937 /// generate pmullw+pmulhw for it (MULS16 mode).
48938 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
48939 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
48940 /// generate pmullw+pmulhuw for it (MULU16 mode).
48941 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
48942                                const X86Subtarget &Subtarget) {
48943   // Check for legality
48944   // pmullw/pmulhw are not supported by SSE.
48945   if (!Subtarget.hasSSE2())
48946     return SDValue();
48947 
48948   // Check for profitability
48949   // pmulld is supported since SSE41. It is better to use pmulld
48950   // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
48951   // the expansion.
48952   bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
48953   if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
48954     return SDValue();
48955 
48956   ShrinkMode Mode;
48957   if (!canReduceVMulWidth(N, DAG, Mode))
48958     return SDValue();
48959 
48960   SDLoc DL(N);
48961   SDValue N0 = N->getOperand(0);
48962   SDValue N1 = N->getOperand(1);
48963   EVT VT = N->getOperand(0).getValueType();
48964   unsigned NumElts = VT.getVectorNumElements();
48965   if ((NumElts % 2) != 0)
48966     return SDValue();
48967 
48968   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
48969 
48970   // Shrink the operands of mul.
48971   SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
48972   SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
48973 
48974   // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
48975   // lower part is needed.
48976   SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
48977   if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
48978     return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
48979                                                    : ISD::SIGN_EXTEND,
48980                        DL, VT, MulLo);
48981 
48982   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts / 2);
48983   // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
48984   // the higher part is also needed.
48985   SDValue MulHi =
48986       DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
48987                   ReducedVT, NewN0, NewN1);
48988 
48989   // Repack the lower part and higher part result of mul into a wider
48990   // result.
48991   // Generate shuffle functioning as punpcklwd.
48992   SmallVector<int, 16> ShuffleMask(NumElts);
48993   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
48994     ShuffleMask[2 * i] = i;
48995     ShuffleMask[2 * i + 1] = i + NumElts;
48996   }
48997   SDValue ResLo =
48998       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
48999   ResLo = DAG.getBitcast(ResVT, ResLo);
49000   // Generate shuffle functioning as punpckhwd.
49001   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
49002     ShuffleMask[2 * i] = i + NumElts / 2;
49003     ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
49004   }
49005   SDValue ResHi =
49006       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
49007   ResHi = DAG.getBitcast(ResVT, ResHi);
49008   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
49009 }
49010 
49011 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
49012                                  EVT VT, const SDLoc &DL) {
49013 
49014   auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
49015     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
49016                                  DAG.getConstant(Mult, DL, VT));
49017     Result = DAG.getNode(ISD::SHL, DL, VT, Result,
49018                          DAG.getConstant(Shift, DL, MVT::i8));
49019     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
49020                          N->getOperand(0));
49021     return Result;
49022   };
49023 
49024   auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
49025     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
49026                                  DAG.getConstant(Mul1, DL, VT));
49027     Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
49028                          DAG.getConstant(Mul2, DL, VT));
49029     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
49030                          N->getOperand(0));
49031     return Result;
49032   };
49033 
49034   switch (MulAmt) {
49035   default:
49036     break;
49037   case 11:
49038     // mul x, 11 => add ((shl (mul x, 5), 1), x)
49039     return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
49040   case 21:
49041     // mul x, 21 => add ((shl (mul x, 5), 2), x)
49042     return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
49043   case 41:
49044     // mul x, 41 => add ((shl (mul x, 5), 3), x)
49045     return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
49046   case 22:
49047     // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
49048     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
49049                        combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
49050   case 19:
49051     // mul x, 19 => add ((shl (mul x, 9), 1), x)
49052     return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
49053   case 37:
49054     // mul x, 37 => add ((shl (mul x, 9), 2), x)
49055     return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
49056   case 73:
49057     // mul x, 73 => add ((shl (mul x, 9), 3), x)
49058     return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
49059   case 13:
49060     // mul x, 13 => add ((shl (mul x, 3), 2), x)
49061     return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
49062   case 23:
49063     // mul x, 23 => sub ((shl (mul x, 3), 3), x)
49064     return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
49065   case 26:
49066     // mul x, 26 => add ((mul (mul x, 5), 5), x)
49067     return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
49068   case 28:
49069     // mul x, 28 => add ((mul (mul x, 9), 3), x)
49070     return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
49071   case 29:
49072     // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
49073     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
49074                        combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
49075   }
49076 
49077   // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
49078   // by a single LEA.
49079   // First check if this a sum of two power of 2s because that's easy. Then
49080   // count how many zeros are up to the first bit.
49081   // TODO: We can do this even without LEA at a cost of two shifts and an add.
49082   if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
49083     unsigned ScaleShift = llvm::countr_zero(MulAmt);
49084     if (ScaleShift >= 1 && ScaleShift < 4) {
49085       unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
49086       SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49087                                    DAG.getConstant(ShiftAmt, DL, MVT::i8));
49088       SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49089                                    DAG.getConstant(ScaleShift, DL, MVT::i8));
49090       return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
49091     }
49092   }
49093 
49094   return SDValue();
49095 }
49096 
49097 // If the upper 17 bits of either element are zero and the other element are
49098 // zero/sign bits then we can use PMADDWD, which is always at least as quick as
49099 // PMULLD, except on KNL.
49100 static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
49101                                    const X86Subtarget &Subtarget) {
49102   if (!Subtarget.hasSSE2())
49103     return SDValue();
49104 
49105   if (Subtarget.isPMADDWDSlow())
49106     return SDValue();
49107 
49108   EVT VT = N->getValueType(0);
49109 
49110   // Only support vXi32 vectors.
49111   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
49112     return SDValue();
49113 
49114   // Make sure the type is legal or can split/widen to a legal type.
49115   // With AVX512 but without BWI, we would need to split v32i16.
49116   unsigned NumElts = VT.getVectorNumElements();
49117   if (NumElts == 1 || !isPowerOf2_32(NumElts))
49118     return SDValue();
49119 
49120   // With AVX512 but without BWI, we would need to split v32i16.
49121   if (32 <= (2 * NumElts) && Subtarget.hasAVX512() && !Subtarget.hasBWI())
49122     return SDValue();
49123 
49124   SDValue N0 = N->getOperand(0);
49125   SDValue N1 = N->getOperand(1);
49126 
49127   // If we are zero/sign extending two steps without SSE4.1, its better to
49128   // reduce the vmul width instead.
49129   if (!Subtarget.hasSSE41() &&
49130       (((N0.getOpcode() == ISD::ZERO_EXTEND &&
49131          N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
49132         (N1.getOpcode() == ISD::ZERO_EXTEND &&
49133          N1.getOperand(0).getScalarValueSizeInBits() <= 8)) ||
49134        ((N0.getOpcode() == ISD::SIGN_EXTEND &&
49135          N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
49136         (N1.getOpcode() == ISD::SIGN_EXTEND &&
49137          N1.getOperand(0).getScalarValueSizeInBits() <= 8))))
49138     return SDValue();
49139 
49140   // If we are sign extending a wide vector without SSE4.1, its better to reduce
49141   // the vmul width instead.
49142   if (!Subtarget.hasSSE41() &&
49143       (N0.getOpcode() == ISD::SIGN_EXTEND &&
49144        N0.getOperand(0).getValueSizeInBits() > 128) &&
49145       (N1.getOpcode() == ISD::SIGN_EXTEND &&
49146        N1.getOperand(0).getValueSizeInBits() > 128))
49147     return SDValue();
49148 
49149   // Sign bits must extend down to the lowest i16.
49150   if (DAG.ComputeMaxSignificantBits(N1) > 16 ||
49151       DAG.ComputeMaxSignificantBits(N0) > 16)
49152     return SDValue();
49153 
49154   // At least one of the elements must be zero in the upper 17 bits, or can be
49155   // safely made zero without altering the final result.
49156   auto GetZeroableOp = [&](SDValue Op) {
49157     APInt Mask17 = APInt::getHighBitsSet(32, 17);
49158     if (DAG.MaskedValueIsZero(Op, Mask17))
49159       return Op;
49160     // Mask off upper 16-bits of sign-extended constants.
49161     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()))
49162       return DAG.getNode(ISD::AND, SDLoc(N), VT, Op,
49163                          DAG.getConstant(0xFFFF, SDLoc(N), VT));
49164     if (Op.getOpcode() == ISD::SIGN_EXTEND && N->isOnlyUserOf(Op.getNode())) {
49165       SDValue Src = Op.getOperand(0);
49166       // Convert sext(vXi16) to zext(vXi16).
49167       if (Src.getScalarValueSizeInBits() == 16 && VT.getSizeInBits() <= 128)
49168         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Src);
49169       // Convert sext(vXi8) to zext(vXi16 sext(vXi8)) on pre-SSE41 targets
49170       // which will expand the extension.
49171       if (Src.getScalarValueSizeInBits() < 16 && !Subtarget.hasSSE41()) {
49172         EVT ExtVT = VT.changeVectorElementType(MVT::i16);
49173         Src = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), ExtVT, Src);
49174         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Src);
49175       }
49176     }
49177     // Convert SIGN_EXTEND_VECTOR_INREG to ZEXT_EXTEND_VECTOR_INREG.
49178     if (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG &&
49179         N->isOnlyUserOf(Op.getNode())) {
49180       SDValue Src = Op.getOperand(0);
49181       if (Src.getScalarValueSizeInBits() == 16)
49182         return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(N), VT, Src);
49183     }
49184     // Convert VSRAI(Op, 16) to VSRLI(Op, 16).
49185     if (Op.getOpcode() == X86ISD::VSRAI && Op.getConstantOperandVal(1) == 16 &&
49186         N->isOnlyUserOf(Op.getNode())) {
49187       return DAG.getNode(X86ISD::VSRLI, SDLoc(N), VT, Op.getOperand(0),
49188                          Op.getOperand(1));
49189     }
49190     return SDValue();
49191   };
49192   SDValue ZeroN0 = GetZeroableOp(N0);
49193   SDValue ZeroN1 = GetZeroableOp(N1);
49194   if (!ZeroN0 && !ZeroN1)
49195     return SDValue();
49196   N0 = ZeroN0 ? ZeroN0 : N0;
49197   N1 = ZeroN1 ? ZeroN1 : N1;
49198 
49199   // Use SplitOpsAndApply to handle AVX splitting.
49200   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
49201                            ArrayRef<SDValue> Ops) {
49202     MVT ResVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
49203     MVT OpVT = MVT::getVectorVT(MVT::i16, Ops[0].getValueSizeInBits() / 16);
49204     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT,
49205                        DAG.getBitcast(OpVT, Ops[0]),
49206                        DAG.getBitcast(OpVT, Ops[1]));
49207   };
49208   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {N0, N1},
49209                           PMADDWDBuilder);
49210 }
49211 
49212 static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
49213                                   const X86Subtarget &Subtarget) {
49214   if (!Subtarget.hasSSE2())
49215     return SDValue();
49216 
49217   EVT VT = N->getValueType(0);
49218 
49219   // Only support vXi64 vectors.
49220   if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
49221       VT.getVectorNumElements() < 2 ||
49222       !isPowerOf2_32(VT.getVectorNumElements()))
49223     return SDValue();
49224 
49225   SDValue N0 = N->getOperand(0);
49226   SDValue N1 = N->getOperand(1);
49227 
49228   // MULDQ returns the 64-bit result of the signed multiplication of the lower
49229   // 32-bits. We can lower with this if the sign bits stretch that far.
49230   if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
49231       DAG.ComputeNumSignBits(N1) > 32) {
49232     auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
49233                             ArrayRef<SDValue> Ops) {
49234       return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
49235     };
49236     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
49237                             PMULDQBuilder, /*CheckBWI*/false);
49238   }
49239 
49240   // If the upper bits are zero we can use a single pmuludq.
49241   APInt Mask = APInt::getHighBitsSet(64, 32);
49242   if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
49243     auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
49244                              ArrayRef<SDValue> Ops) {
49245       return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
49246     };
49247     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
49248                             PMULUDQBuilder, /*CheckBWI*/false);
49249   }
49250 
49251   return SDValue();
49252 }
49253 
49254 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
49255                           TargetLowering::DAGCombinerInfo &DCI,
49256                           const X86Subtarget &Subtarget) {
49257   EVT VT = N->getValueType(0);
49258 
49259   if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
49260     return V;
49261 
49262   if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
49263     return V;
49264 
49265   if (DCI.isBeforeLegalize() && VT.isVector())
49266     return reduceVMULWidth(N, DAG, Subtarget);
49267 
49268   // Optimize a single multiply with constant into two operations in order to
49269   // implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
49270   if (!MulConstantOptimization)
49271     return SDValue();
49272 
49273   // An imul is usually smaller than the alternative sequence.
49274   if (DAG.getMachineFunction().getFunction().hasMinSize())
49275     return SDValue();
49276 
49277   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
49278     return SDValue();
49279 
49280   if (VT != MVT::i64 && VT != MVT::i32 &&
49281       (!VT.isVector() || !VT.isSimple() || !VT.isInteger()))
49282     return SDValue();
49283 
49284   ConstantSDNode *CNode = isConstOrConstSplat(
49285       N->getOperand(1), /*AllowUndefs*/ true, /*AllowTrunc*/ false);
49286   const APInt *C = nullptr;
49287   if (!CNode) {
49288     if (VT.isVector())
49289       if (auto *RawC = getTargetConstantFromNode(N->getOperand(1)))
49290         if (auto *SplatC = RawC->getSplatValue())
49291           C = &(SplatC->getUniqueInteger());
49292 
49293     if (!C || C->getBitWidth() != VT.getScalarSizeInBits())
49294       return SDValue();
49295   } else {
49296     C = &(CNode->getAPIntValue());
49297   }
49298 
49299   if (isPowerOf2_64(C->getZExtValue()))
49300     return SDValue();
49301 
49302   int64_t SignMulAmt = C->getSExtValue();
49303   assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
49304   uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
49305 
49306   SDLoc DL(N);
49307   SDValue NewMul = SDValue();
49308   if (VT == MVT::i64 || VT == MVT::i32) {
49309     if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
49310       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
49311                            DAG.getConstant(AbsMulAmt, DL, VT));
49312       if (SignMulAmt < 0)
49313         NewMul =
49314             DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), NewMul);
49315 
49316       return NewMul;
49317     }
49318 
49319     uint64_t MulAmt1 = 0;
49320     uint64_t MulAmt2 = 0;
49321     if ((AbsMulAmt % 9) == 0) {
49322       MulAmt1 = 9;
49323       MulAmt2 = AbsMulAmt / 9;
49324     } else if ((AbsMulAmt % 5) == 0) {
49325       MulAmt1 = 5;
49326       MulAmt2 = AbsMulAmt / 5;
49327     } else if ((AbsMulAmt % 3) == 0) {
49328       MulAmt1 = 3;
49329       MulAmt2 = AbsMulAmt / 3;
49330     }
49331 
49332     // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
49333     if (MulAmt2 &&
49334         (isPowerOf2_64(MulAmt2) ||
49335          (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
49336 
49337       if (isPowerOf2_64(MulAmt2) && !(SignMulAmt >= 0 && N->hasOneUse() &&
49338                                       N->use_begin()->getOpcode() == ISD::ADD))
49339         // If second multiplifer is pow2, issue it first. We want the multiply
49340         // by 3, 5, or 9 to be folded into the addressing mode unless the lone
49341         // use is an add. Only do this for positive multiply amounts since the
49342         // negate would prevent it from being used as an address mode anyway.
49343         std::swap(MulAmt1, MulAmt2);
49344 
49345       if (isPowerOf2_64(MulAmt1))
49346         NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49347                              DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
49348       else
49349         NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
49350                              DAG.getConstant(MulAmt1, DL, VT));
49351 
49352       if (isPowerOf2_64(MulAmt2))
49353         NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
49354                              DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
49355       else
49356         NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
49357                              DAG.getConstant(MulAmt2, DL, VT));
49358 
49359       // Negate the result.
49360       if (SignMulAmt < 0)
49361         NewMul =
49362             DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), NewMul);
49363     } else if (!Subtarget.slowLEA())
49364       NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
49365   }
49366   if (!NewMul) {
49367     EVT ShiftVT = VT.isVector() ? VT : MVT::i8;
49368     assert(C->getZExtValue() != 0 &&
49369            C->getZExtValue() != maxUIntN(VT.getScalarSizeInBits()) &&
49370            "Both cases that could cause potential overflows should have "
49371            "already been handled.");
49372     if (isPowerOf2_64(AbsMulAmt - 1)) {
49373       // (mul x, 2^N + 1) => (add (shl x, N), x)
49374       NewMul = DAG.getNode(
49375           ISD::ADD, DL, VT, N->getOperand(0),
49376           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49377                       DAG.getConstant(Log2_64(AbsMulAmt - 1), DL, ShiftVT)));
49378       // To negate, subtract the number from zero
49379       if (SignMulAmt < 0)
49380         NewMul =
49381             DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), NewMul);
49382     } else if (isPowerOf2_64(AbsMulAmt + 1)) {
49383       // (mul x, 2^N - 1) => (sub (shl x, N), x)
49384       NewMul =
49385           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49386                       DAG.getConstant(Log2_64(AbsMulAmt + 1), DL, ShiftVT));
49387       // To negate, reverse the operands of the subtract.
49388       if (SignMulAmt < 0)
49389         NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
49390       else
49391         NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
49392     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2) &&
49393                (!VT.isVector() || Subtarget.fastImmVectorShift())) {
49394       // (mul x, 2^N + 2) => (add (shl x, N), (add x, x))
49395       NewMul =
49396           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49397                       DAG.getConstant(Log2_64(AbsMulAmt - 2), DL, ShiftVT));
49398       NewMul = DAG.getNode(
49399           ISD::ADD, DL, VT, NewMul,
49400           DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0), N->getOperand(0)));
49401     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2) &&
49402                (!VT.isVector() || Subtarget.fastImmVectorShift())) {
49403       // (mul x, 2^N - 2) => (sub (shl x, N), (add x, x))
49404       NewMul =
49405           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49406                       DAG.getConstant(Log2_64(AbsMulAmt + 2), DL, ShiftVT));
49407       NewMul = DAG.getNode(
49408           ISD::SUB, DL, VT, NewMul,
49409           DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0), N->getOperand(0)));
49410     } else if (SignMulAmt >= 0 && VT.isVector() &&
49411                Subtarget.fastImmVectorShift()) {
49412       uint64_t AbsMulAmtLowBit = AbsMulAmt & (-AbsMulAmt);
49413       uint64_t ShiftAmt1;
49414       std::optional<unsigned> Opc;
49415       if (isPowerOf2_64(AbsMulAmt - AbsMulAmtLowBit)) {
49416         ShiftAmt1 = AbsMulAmt - AbsMulAmtLowBit;
49417         Opc = ISD::ADD;
49418       } else if (isPowerOf2_64(AbsMulAmt + AbsMulAmtLowBit)) {
49419         ShiftAmt1 = AbsMulAmt + AbsMulAmtLowBit;
49420         Opc = ISD::SUB;
49421       }
49422 
49423       if (Opc) {
49424         SDValue Shift1 =
49425             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49426                         DAG.getConstant(Log2_64(ShiftAmt1), DL, ShiftVT));
49427         SDValue Shift2 =
49428             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
49429                         DAG.getConstant(Log2_64(AbsMulAmtLowBit), DL, ShiftVT));
49430         NewMul = DAG.getNode(*Opc, DL, VT, Shift1, Shift2);
49431       }
49432     }
49433   }
49434 
49435   return NewMul;
49436 }
49437 
49438 // Try to form a MULHU or MULHS node by looking for
49439 // (srl (mul ext, ext), 16)
49440 // TODO: This is X86 specific because we want to be able to handle wide types
49441 // before type legalization. But we can only do it if the vector will be
49442 // legalized via widening/splitting. Type legalization can't handle promotion
49443 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
49444 // combiner.
49445 static SDValue combineShiftToPMULH(SDNode *N, SelectionDAG &DAG,
49446                                    const X86Subtarget &Subtarget) {
49447   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
49448            "SRL or SRA node is required here!");
49449   SDLoc DL(N);
49450 
49451   if (!Subtarget.hasSSE2())
49452     return SDValue();
49453 
49454   // The operation feeding into the shift must be a multiply.
49455   SDValue ShiftOperand = N->getOperand(0);
49456   if (ShiftOperand.getOpcode() != ISD::MUL || !ShiftOperand.hasOneUse())
49457     return SDValue();
49458 
49459   // Input type should be at least vXi32.
49460   EVT VT = N->getValueType(0);
49461   if (!VT.isVector() || VT.getVectorElementType().getSizeInBits() < 32)
49462     return SDValue();
49463 
49464   // Need a shift by 16.
49465   APInt ShiftAmt;
49466   if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), ShiftAmt) ||
49467       ShiftAmt != 16)
49468     return SDValue();
49469 
49470   SDValue LHS = ShiftOperand.getOperand(0);
49471   SDValue RHS = ShiftOperand.getOperand(1);
49472 
49473   unsigned ExtOpc = LHS.getOpcode();
49474   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
49475       RHS.getOpcode() != ExtOpc)
49476     return SDValue();
49477 
49478   // Peek through the extends.
49479   LHS = LHS.getOperand(0);
49480   RHS = RHS.getOperand(0);
49481 
49482   // Ensure the input types match.
49483   EVT MulVT = LHS.getValueType();
49484   if (MulVT.getVectorElementType() != MVT::i16 || RHS.getValueType() != MulVT)
49485     return SDValue();
49486 
49487   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
49488   SDValue Mulh = DAG.getNode(Opc, DL, MulVT, LHS, RHS);
49489 
49490   ExtOpc = N->getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
49491   return DAG.getNode(ExtOpc, DL, VT, Mulh);
49492 }
49493 
49494 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
49495   SDValue N0 = N->getOperand(0);
49496   SDValue N1 = N->getOperand(1);
49497   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
49498   EVT VT = N0.getValueType();
49499 
49500   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
49501   // since the result of setcc_c is all zero's or all ones.
49502   if (VT.isInteger() && !VT.isVector() &&
49503       N1C && N0.getOpcode() == ISD::AND &&
49504       N0.getOperand(1).getOpcode() == ISD::Constant) {
49505     SDValue N00 = N0.getOperand(0);
49506     APInt Mask = N0.getConstantOperandAPInt(1);
49507     Mask <<= N1C->getAPIntValue();
49508     bool MaskOK = false;
49509     // We can handle cases concerning bit-widening nodes containing setcc_c if
49510     // we carefully interrogate the mask to make sure we are semantics
49511     // preserving.
49512     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
49513     // of the underlying setcc_c operation if the setcc_c was zero extended.
49514     // Consider the following example:
49515     //   zext(setcc_c)                 -> i32 0x0000FFFF
49516     //   c1                            -> i32 0x0000FFFF
49517     //   c2                            -> i32 0x00000001
49518     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
49519     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
49520     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
49521       MaskOK = true;
49522     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
49523                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
49524       MaskOK = true;
49525     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
49526                 N00.getOpcode() == ISD::ANY_EXTEND) &&
49527                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
49528       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
49529     }
49530     if (MaskOK && Mask != 0) {
49531       SDLoc DL(N);
49532       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
49533     }
49534   }
49535 
49536   return SDValue();
49537 }
49538 
49539 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG,
49540                                            const X86Subtarget &Subtarget) {
49541   SDValue N0 = N->getOperand(0);
49542   SDValue N1 = N->getOperand(1);
49543   EVT VT = N0.getValueType();
49544   unsigned Size = VT.getSizeInBits();
49545 
49546   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
49547     return V;
49548 
49549   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
49550   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
49551   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
49552   // depending on sign of (SarConst - [56,48,32,24,16])
49553 
49554   // sexts in X86 are MOVs. The MOVs have the same code size
49555   // as above SHIFTs (only SHIFT on 1 has lower code size).
49556   // However the MOVs have 2 advantages to a SHIFT:
49557   // 1. MOVs can write to a register that differs from source
49558   // 2. MOVs accept memory operands
49559 
49560   if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
49561       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
49562       N0.getOperand(1).getOpcode() != ISD::Constant)
49563     return SDValue();
49564 
49565   SDValue N00 = N0.getOperand(0);
49566   SDValue N01 = N0.getOperand(1);
49567   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
49568   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
49569   EVT CVT = N1.getValueType();
49570 
49571   if (SarConst.isNegative())
49572     return SDValue();
49573 
49574   for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
49575     unsigned ShiftSize = SVT.getSizeInBits();
49576     // skipping types without corresponding sext/zext and
49577     // ShlConst that is not one of [56,48,32,24,16]
49578     if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
49579       continue;
49580     SDLoc DL(N);
49581     SDValue NN =
49582         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
49583     SarConst = SarConst - (Size - ShiftSize);
49584     if (SarConst == 0)
49585       return NN;
49586     if (SarConst.isNegative())
49587       return DAG.getNode(ISD::SHL, DL, VT, NN,
49588                          DAG.getConstant(-SarConst, DL, CVT));
49589     return DAG.getNode(ISD::SRA, DL, VT, NN,
49590                        DAG.getConstant(SarConst, DL, CVT));
49591   }
49592   return SDValue();
49593 }
49594 
49595 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
49596                                         TargetLowering::DAGCombinerInfo &DCI,
49597                                         const X86Subtarget &Subtarget) {
49598   SDValue N0 = N->getOperand(0);
49599   SDValue N1 = N->getOperand(1);
49600   EVT VT = N0.getValueType();
49601 
49602   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
49603     return V;
49604 
49605   // Only do this on the last DAG combine as it can interfere with other
49606   // combines.
49607   if (!DCI.isAfterLegalizeDAG())
49608     return SDValue();
49609 
49610   // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
49611   // TODO: This is a generic DAG combine that became an x86-only combine to
49612   // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
49613   // and-not ('andn').
49614   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
49615     return SDValue();
49616 
49617   auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
49618   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
49619   if (!ShiftC || !AndC)
49620     return SDValue();
49621 
49622   // If we can shrink the constant mask below 8-bits or 32-bits, then this
49623   // transform should reduce code size. It may also enable secondary transforms
49624   // from improved known-bits analysis or instruction selection.
49625   APInt MaskVal = AndC->getAPIntValue();
49626 
49627   // If this can be matched by a zero extend, don't optimize.
49628   if (MaskVal.isMask()) {
49629     unsigned TO = MaskVal.countr_one();
49630     if (TO >= 8 && isPowerOf2_32(TO))
49631       return SDValue();
49632   }
49633 
49634   APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
49635   unsigned OldMaskSize = MaskVal.getSignificantBits();
49636   unsigned NewMaskSize = NewMaskVal.getSignificantBits();
49637   if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
49638       (OldMaskSize > 32 && NewMaskSize <= 32)) {
49639     // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
49640     SDLoc DL(N);
49641     SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
49642     SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
49643     return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
49644   }
49645   return SDValue();
49646 }
49647 
49648 static SDValue combineHorizOpWithShuffle(SDNode *N, SelectionDAG &DAG,
49649                                          const X86Subtarget &Subtarget) {
49650   unsigned Opcode = N->getOpcode();
49651   assert(isHorizOp(Opcode) && "Unexpected hadd/hsub/pack opcode");
49652 
49653   SDLoc DL(N);
49654   EVT VT = N->getValueType(0);
49655   SDValue N0 = N->getOperand(0);
49656   SDValue N1 = N->getOperand(1);
49657   EVT SrcVT = N0.getValueType();
49658 
49659   SDValue BC0 =
49660       N->isOnlyUserOf(N0.getNode()) ? peekThroughOneUseBitcasts(N0) : N0;
49661   SDValue BC1 =
49662       N->isOnlyUserOf(N1.getNode()) ? peekThroughOneUseBitcasts(N1) : N1;
49663 
49664   // Attempt to fold HOP(LOSUBVECTOR(SHUFFLE(X)),HISUBVECTOR(SHUFFLE(X)))
49665   // to SHUFFLE(HOP(LOSUBVECTOR(X),HISUBVECTOR(X))), this is mainly for
49666   // truncation trees that help us avoid lane crossing shuffles.
49667   // TODO: There's a lot more we can do for PACK/HADD style shuffle combines.
49668   // TODO: We don't handle vXf64 shuffles yet.
49669   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
49670     if (SDValue BCSrc = getSplitVectorSrc(BC0, BC1, false)) {
49671       SmallVector<SDValue> ShuffleOps;
49672       SmallVector<int> ShuffleMask, ScaledMask;
49673       SDValue Vec = peekThroughBitcasts(BCSrc);
49674       if (getTargetShuffleInputs(Vec, ShuffleOps, ShuffleMask, DAG)) {
49675         resolveTargetShuffleInputsAndMask(ShuffleOps, ShuffleMask);
49676         // To keep the HOP LHS/RHS coherency, we must be able to scale the unary
49677         // shuffle to a v4X64 width - we can probably relax this in the future.
49678         if (!isAnyZero(ShuffleMask) && ShuffleOps.size() == 1 &&
49679             ShuffleOps[0].getValueType().is256BitVector() &&
49680             scaleShuffleElements(ShuffleMask, 4, ScaledMask)) {
49681           SDValue Lo, Hi;
49682           MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
49683           std::tie(Lo, Hi) = DAG.SplitVector(ShuffleOps[0], DL);
49684           Lo = DAG.getBitcast(SrcVT, Lo);
49685           Hi = DAG.getBitcast(SrcVT, Hi);
49686           SDValue Res = DAG.getNode(Opcode, DL, VT, Lo, Hi);
49687           Res = DAG.getBitcast(ShufVT, Res);
49688           Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ScaledMask);
49689           return DAG.getBitcast(VT, Res);
49690         }
49691       }
49692     }
49693   }
49694 
49695   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(Z,W)) -> SHUFFLE(HOP()).
49696   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
49697     // If either/both ops are a shuffle that can scale to v2x64,
49698     // then see if we can perform this as a v4x32 post shuffle.
49699     SmallVector<SDValue> Ops0, Ops1;
49700     SmallVector<int> Mask0, Mask1, ScaledMask0, ScaledMask1;
49701     bool IsShuf0 =
49702         getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
49703         scaleShuffleElements(Mask0, 2, ScaledMask0) &&
49704         all_of(Ops0, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
49705     bool IsShuf1 =
49706         getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
49707         scaleShuffleElements(Mask1, 2, ScaledMask1) &&
49708         all_of(Ops1, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
49709     if (IsShuf0 || IsShuf1) {
49710       if (!IsShuf0) {
49711         Ops0.assign({BC0});
49712         ScaledMask0.assign({0, 1});
49713       }
49714       if (!IsShuf1) {
49715         Ops1.assign({BC1});
49716         ScaledMask1.assign({0, 1});
49717       }
49718 
49719       SDValue LHS, RHS;
49720       int PostShuffle[4] = {-1, -1, -1, -1};
49721       auto FindShuffleOpAndIdx = [&](int M, int &Idx, ArrayRef<SDValue> Ops) {
49722         if (M < 0)
49723           return true;
49724         Idx = M % 2;
49725         SDValue Src = Ops[M / 2];
49726         if (!LHS || LHS == Src) {
49727           LHS = Src;
49728           return true;
49729         }
49730         if (!RHS || RHS == Src) {
49731           Idx += 2;
49732           RHS = Src;
49733           return true;
49734         }
49735         return false;
49736       };
49737       if (FindShuffleOpAndIdx(ScaledMask0[0], PostShuffle[0], Ops0) &&
49738           FindShuffleOpAndIdx(ScaledMask0[1], PostShuffle[1], Ops0) &&
49739           FindShuffleOpAndIdx(ScaledMask1[0], PostShuffle[2], Ops1) &&
49740           FindShuffleOpAndIdx(ScaledMask1[1], PostShuffle[3], Ops1)) {
49741         LHS = DAG.getBitcast(SrcVT, LHS);
49742         RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
49743         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
49744         SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
49745         Res = DAG.getBitcast(ShufVT, Res);
49746         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, PostShuffle);
49747         return DAG.getBitcast(VT, Res);
49748       }
49749     }
49750   }
49751 
49752   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(X,Y)) -> SHUFFLE(HOP(X,Y)).
49753   if (VT.is256BitVector() && Subtarget.hasInt256()) {
49754     SmallVector<int> Mask0, Mask1;
49755     SmallVector<SDValue> Ops0, Ops1;
49756     SmallVector<int, 2> ScaledMask0, ScaledMask1;
49757     if (getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
49758         getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
49759         !Ops0.empty() && !Ops1.empty() &&
49760         all_of(Ops0,
49761                [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
49762         all_of(Ops1,
49763                [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
49764         scaleShuffleElements(Mask0, 2, ScaledMask0) &&
49765         scaleShuffleElements(Mask1, 2, ScaledMask1)) {
49766       SDValue Op00 = peekThroughBitcasts(Ops0.front());
49767       SDValue Op10 = peekThroughBitcasts(Ops1.front());
49768       SDValue Op01 = peekThroughBitcasts(Ops0.back());
49769       SDValue Op11 = peekThroughBitcasts(Ops1.back());
49770       if ((Op00 == Op11) && (Op01 == Op10)) {
49771         std::swap(Op10, Op11);
49772         ShuffleVectorSDNode::commuteMask(ScaledMask1);
49773       }
49774       if ((Op00 == Op10) && (Op01 == Op11)) {
49775         const int Map[4] = {0, 2, 1, 3};
49776         SmallVector<int, 4> ShuffleMask(
49777             {Map[ScaledMask0[0]], Map[ScaledMask1[0]], Map[ScaledMask0[1]],
49778              Map[ScaledMask1[1]]});
49779         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
49780         SDValue Res = DAG.getNode(Opcode, DL, VT, DAG.getBitcast(SrcVT, Op00),
49781                                   DAG.getBitcast(SrcVT, Op01));
49782         Res = DAG.getBitcast(ShufVT, Res);
49783         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ShuffleMask);
49784         return DAG.getBitcast(VT, Res);
49785       }
49786     }
49787   }
49788 
49789   return SDValue();
49790 }
49791 
49792 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
49793                                  TargetLowering::DAGCombinerInfo &DCI,
49794                                  const X86Subtarget &Subtarget) {
49795   unsigned Opcode = N->getOpcode();
49796   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
49797          "Unexpected pack opcode");
49798 
49799   EVT VT = N->getValueType(0);
49800   SDValue N0 = N->getOperand(0);
49801   SDValue N1 = N->getOperand(1);
49802   unsigned NumDstElts = VT.getVectorNumElements();
49803   unsigned DstBitsPerElt = VT.getScalarSizeInBits();
49804   unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
49805   assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
49806          N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
49807          "Unexpected PACKSS/PACKUS input type");
49808 
49809   bool IsSigned = (X86ISD::PACKSS == Opcode);
49810 
49811   // Constant Folding.
49812   APInt UndefElts0, UndefElts1;
49813   SmallVector<APInt, 32> EltBits0, EltBits1;
49814   if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
49815       (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
49816       getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
49817       getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
49818     unsigned NumLanes = VT.getSizeInBits() / 128;
49819     unsigned NumSrcElts = NumDstElts / 2;
49820     unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
49821     unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
49822 
49823     APInt Undefs(NumDstElts, 0);
49824     SmallVector<APInt, 32> Bits(NumDstElts, APInt::getZero(DstBitsPerElt));
49825     for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
49826       for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
49827         unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
49828         auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
49829         auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
49830 
49831         if (UndefElts[SrcIdx]) {
49832           Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
49833           continue;
49834         }
49835 
49836         APInt &Val = EltBits[SrcIdx];
49837         if (IsSigned) {
49838           // PACKSS: Truncate signed value with signed saturation.
49839           // Source values less than dst minint are saturated to minint.
49840           // Source values greater than dst maxint are saturated to maxint.
49841           if (Val.isSignedIntN(DstBitsPerElt))
49842             Val = Val.trunc(DstBitsPerElt);
49843           else if (Val.isNegative())
49844             Val = APInt::getSignedMinValue(DstBitsPerElt);
49845           else
49846             Val = APInt::getSignedMaxValue(DstBitsPerElt);
49847         } else {
49848           // PACKUS: Truncate signed value with unsigned saturation.
49849           // Source values less than zero are saturated to zero.
49850           // Source values greater than dst maxuint are saturated to maxuint.
49851           if (Val.isIntN(DstBitsPerElt))
49852             Val = Val.trunc(DstBitsPerElt);
49853           else if (Val.isNegative())
49854             Val = APInt::getZero(DstBitsPerElt);
49855           else
49856             Val = APInt::getAllOnes(DstBitsPerElt);
49857         }
49858         Bits[Lane * NumDstEltsPerLane + Elt] = Val;
49859       }
49860     }
49861 
49862     return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
49863   }
49864 
49865   // Try to fold PACK(SHUFFLE(),SHUFFLE()) -> SHUFFLE(PACK()).
49866   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
49867     return V;
49868 
49869   // Try to fold PACKSS(NOT(X),NOT(Y)) -> NOT(PACKSS(X,Y)).
49870   // Currently limit this to allsignbits cases only.
49871   if (IsSigned &&
49872       (N0.isUndef() || DAG.ComputeNumSignBits(N0) == SrcBitsPerElt) &&
49873       (N1.isUndef() || DAG.ComputeNumSignBits(N1) == SrcBitsPerElt)) {
49874     SDValue Not0 = N0.isUndef() ? N0 : IsNOT(N0, DAG);
49875     SDValue Not1 = N1.isUndef() ? N1 : IsNOT(N1, DAG);
49876     if (Not0 && Not1) {
49877       SDLoc DL(N);
49878       MVT SrcVT = N0.getSimpleValueType();
49879       SDValue Pack =
49880           DAG.getNode(X86ISD::PACKSS, DL, VT, DAG.getBitcast(SrcVT, Not0),
49881                       DAG.getBitcast(SrcVT, Not1));
49882       return DAG.getNOT(DL, Pack, VT);
49883     }
49884   }
49885 
49886   // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
49887   // truncate to create a larger truncate.
49888   if (Subtarget.hasAVX512() &&
49889       N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
49890       N0.getOperand(0).getValueType() == MVT::v8i32) {
49891     if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
49892         (!IsSigned &&
49893          DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
49894       if (Subtarget.hasVLX())
49895         return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
49896 
49897       // Widen input to v16i32 so we can truncate that.
49898       SDLoc dl(N);
49899       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
49900                                    N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
49901       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
49902     }
49903   }
49904 
49905   // Try to fold PACK(EXTEND(X),EXTEND(Y)) -> CONCAT(X,Y) subvectors.
49906   if (VT.is128BitVector()) {
49907     unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
49908     SDValue Src0, Src1;
49909     if (N0.getOpcode() == ExtOpc &&
49910         N0.getOperand(0).getValueType().is64BitVector() &&
49911         N0.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
49912       Src0 = N0.getOperand(0);
49913     }
49914     if (N1.getOpcode() == ExtOpc &&
49915         N1.getOperand(0).getValueType().is64BitVector() &&
49916         N1.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
49917       Src1 = N1.getOperand(0);
49918     }
49919     if ((Src0 || N0.isUndef()) && (Src1 || N1.isUndef())) {
49920       assert((Src0 || Src1) && "Found PACK(UNDEF,UNDEF)");
49921       Src0 = Src0 ? Src0 : DAG.getUNDEF(Src1.getValueType());
49922       Src1 = Src1 ? Src1 : DAG.getUNDEF(Src0.getValueType());
49923       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Src0, Src1);
49924     }
49925 
49926     // Try again with pack(*_extend_vector_inreg, undef).
49927     unsigned VecInRegOpc = IsSigned ? ISD::SIGN_EXTEND_VECTOR_INREG
49928                                     : ISD::ZERO_EXTEND_VECTOR_INREG;
49929     if (N0.getOpcode() == VecInRegOpc && N1.isUndef() &&
49930         N0.getOperand(0).getScalarValueSizeInBits() < DstBitsPerElt)
49931       return getEXTEND_VECTOR_INREG(ExtOpc, SDLoc(N), VT, N0.getOperand(0),
49932                                     DAG);
49933   }
49934 
49935   // Attempt to combine as shuffle.
49936   SDValue Op(N, 0);
49937   if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
49938     return Res;
49939 
49940   return SDValue();
49941 }
49942 
49943 static SDValue combineVectorHADDSUB(SDNode *N, SelectionDAG &DAG,
49944                                     TargetLowering::DAGCombinerInfo &DCI,
49945                                     const X86Subtarget &Subtarget) {
49946   assert((X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() ||
49947           X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
49948          "Unexpected horizontal add/sub opcode");
49949 
49950   if (!shouldUseHorizontalOp(true, DAG, Subtarget)) {
49951     MVT VT = N->getSimpleValueType(0);
49952     SDValue LHS = N->getOperand(0);
49953     SDValue RHS = N->getOperand(1);
49954 
49955     // HOP(HOP'(X,X),HOP'(Y,Y)) -> HOP(PERMUTE(HOP'(X,Y)),PERMUTE(HOP'(X,Y)).
49956     if (LHS != RHS && LHS.getOpcode() == N->getOpcode() &&
49957         LHS.getOpcode() == RHS.getOpcode() &&
49958         LHS.getValueType() == RHS.getValueType() &&
49959         N->isOnlyUserOf(LHS.getNode()) && N->isOnlyUserOf(RHS.getNode())) {
49960       SDValue LHS0 = LHS.getOperand(0);
49961       SDValue LHS1 = LHS.getOperand(1);
49962       SDValue RHS0 = RHS.getOperand(0);
49963       SDValue RHS1 = RHS.getOperand(1);
49964       if ((LHS0 == LHS1 || LHS0.isUndef() || LHS1.isUndef()) &&
49965           (RHS0 == RHS1 || RHS0.isUndef() || RHS1.isUndef())) {
49966         SDLoc DL(N);
49967         SDValue Res = DAG.getNode(LHS.getOpcode(), DL, LHS.getValueType(),
49968                                   LHS0.isUndef() ? LHS1 : LHS0,
49969                                   RHS0.isUndef() ? RHS1 : RHS0);
49970         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
49971         Res = DAG.getBitcast(ShufVT, Res);
49972         SDValue NewLHS =
49973             DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
49974                         getV4X86ShuffleImm8ForMask({0, 1, 0, 1}, DL, DAG));
49975         SDValue NewRHS =
49976             DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
49977                         getV4X86ShuffleImm8ForMask({2, 3, 2, 3}, DL, DAG));
49978         return DAG.getNode(N->getOpcode(), DL, VT, DAG.getBitcast(VT, NewLHS),
49979                            DAG.getBitcast(VT, NewRHS));
49980       }
49981     }
49982   }
49983 
49984   // Try to fold HOP(SHUFFLE(),SHUFFLE()) -> SHUFFLE(HOP()).
49985   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
49986     return V;
49987 
49988   return SDValue();
49989 }
49990 
49991 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
49992                                      TargetLowering::DAGCombinerInfo &DCI,
49993                                      const X86Subtarget &Subtarget) {
49994   assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
49995           X86ISD::VSRL == N->getOpcode()) &&
49996          "Unexpected shift opcode");
49997   EVT VT = N->getValueType(0);
49998   SDValue N0 = N->getOperand(0);
49999   SDValue N1 = N->getOperand(1);
50000 
50001   // Shift zero -> zero.
50002   if (ISD::isBuildVectorAllZeros(N0.getNode()))
50003     return DAG.getConstant(0, SDLoc(N), VT);
50004 
50005   // Detect constant shift amounts.
50006   APInt UndefElts;
50007   SmallVector<APInt, 32> EltBits;
50008   if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
50009     unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
50010     return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
50011                                       EltBits[0].getZExtValue(), DAG);
50012   }
50013 
50014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50015   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
50016   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
50017     return SDValue(N, 0);
50018 
50019   return SDValue();
50020 }
50021 
50022 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
50023                                      TargetLowering::DAGCombinerInfo &DCI,
50024                                      const X86Subtarget &Subtarget) {
50025   unsigned Opcode = N->getOpcode();
50026   assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
50027           X86ISD::VSRLI == Opcode) &&
50028          "Unexpected shift opcode");
50029   bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
50030   EVT VT = N->getValueType(0);
50031   SDValue N0 = N->getOperand(0);
50032   SDValue N1 = N->getOperand(1);
50033   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
50034   assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
50035          "Unexpected value type");
50036   assert(N1.getValueType() == MVT::i8 && "Unexpected shift amount type");
50037 
50038   // (shift undef, X) -> 0
50039   if (N0.isUndef())
50040     return DAG.getConstant(0, SDLoc(N), VT);
50041 
50042   // Out of range logical bit shifts are guaranteed to be zero.
50043   // Out of range arithmetic bit shifts splat the sign bit.
50044   unsigned ShiftVal = N->getConstantOperandVal(1);
50045   if (ShiftVal >= NumBitsPerElt) {
50046     if (LogicalShift)
50047       return DAG.getConstant(0, SDLoc(N), VT);
50048     ShiftVal = NumBitsPerElt - 1;
50049   }
50050 
50051   // (shift X, 0) -> X
50052   if (!ShiftVal)
50053     return N0;
50054 
50055   // (shift 0, C) -> 0
50056   if (ISD::isBuildVectorAllZeros(N0.getNode()))
50057     // N0 is all zeros or undef. We guarantee that the bits shifted into the
50058     // result are all zeros, not undef.
50059     return DAG.getConstant(0, SDLoc(N), VT);
50060 
50061   // (VSRAI -1, C) -> -1
50062   if (!LogicalShift && ISD::isBuildVectorAllOnes(N0.getNode()))
50063     // N0 is all ones or undef. We guarantee that the bits shifted into the
50064     // result are all ones, not undef.
50065     return DAG.getConstant(-1, SDLoc(N), VT);
50066 
50067   auto MergeShifts = [&](SDValue X, uint64_t Amt0, uint64_t Amt1) {
50068     unsigned NewShiftVal = Amt0 + Amt1;
50069     if (NewShiftVal >= NumBitsPerElt) {
50070       // Out of range logical bit shifts are guaranteed to be zero.
50071       // Out of range arithmetic bit shifts splat the sign bit.
50072       if (LogicalShift)
50073         return DAG.getConstant(0, SDLoc(N), VT);
50074       NewShiftVal = NumBitsPerElt - 1;
50075     }
50076     return DAG.getNode(Opcode, SDLoc(N), VT, N0.getOperand(0),
50077                        DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
50078   };
50079 
50080   // (shift (shift X, C2), C1) -> (shift X, (C1 + C2))
50081   if (Opcode == N0.getOpcode())
50082     return MergeShifts(N0.getOperand(0), ShiftVal, N0.getConstantOperandVal(1));
50083 
50084   // (shl (add X, X), C) -> (shl X, (C + 1))
50085   if (Opcode == X86ISD::VSHLI && N0.getOpcode() == ISD::ADD &&
50086       N0.getOperand(0) == N0.getOperand(1))
50087     return MergeShifts(N0.getOperand(0), ShiftVal, 1);
50088 
50089   // We can decode 'whole byte' logical bit shifts as shuffles.
50090   if (LogicalShift && (ShiftVal % 8) == 0) {
50091     SDValue Op(N, 0);
50092     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
50093       return Res;
50094   }
50095 
50096   // Attempt to detect an expanded vXi64 SIGN_EXTEND_INREG vXi1 pattern, and
50097   // convert to a splatted v2Xi32 SIGN_EXTEND_INREG pattern:
50098   // psrad(pshufd(psllq(X,63),1,1,3,3),31) ->
50099   // pshufd(psrad(pslld(X,31),31),0,0,2,2).
50100   if (Opcode == X86ISD::VSRAI && NumBitsPerElt == 32 && ShiftVal == 31 &&
50101       N0.getOpcode() == X86ISD::PSHUFD &&
50102       N0.getConstantOperandVal(1) == getV4X86ShuffleImm({1, 1, 3, 3}) &&
50103       N0->hasOneUse()) {
50104     SDValue BC = peekThroughOneUseBitcasts(N0.getOperand(0));
50105     if (BC.getOpcode() == X86ISD::VSHLI &&
50106         BC.getScalarValueSizeInBits() == 64 &&
50107         BC.getConstantOperandVal(1) == 63) {
50108       SDLoc DL(N);
50109       SDValue Src = BC.getOperand(0);
50110       Src = DAG.getBitcast(VT, Src);
50111       Src = DAG.getNode(X86ISD::PSHUFD, DL, VT, Src,
50112                         getV4X86ShuffleImm8ForMask({0, 0, 2, 2}, DL, DAG));
50113       Src = DAG.getNode(X86ISD::VSHLI, DL, VT, Src, N1);
50114       Src = DAG.getNode(X86ISD::VSRAI, DL, VT, Src, N1);
50115       return Src;
50116     }
50117   }
50118 
50119   auto TryConstantFold = [&](SDValue V) {
50120     APInt UndefElts;
50121     SmallVector<APInt, 32> EltBits;
50122     if (!getTargetConstantBitsFromNode(V, NumBitsPerElt, UndefElts, EltBits))
50123       return SDValue();
50124     assert(EltBits.size() == VT.getVectorNumElements() &&
50125            "Unexpected shift value type");
50126     // Undef elements need to fold to 0. It's possible SimplifyDemandedBits
50127     // created an undef input due to no input bits being demanded, but user
50128     // still expects 0 in other bits.
50129     for (unsigned i = 0, e = EltBits.size(); i != e; ++i) {
50130       APInt &Elt = EltBits[i];
50131       if (UndefElts[i])
50132         Elt = 0;
50133       else if (X86ISD::VSHLI == Opcode)
50134         Elt <<= ShiftVal;
50135       else if (X86ISD::VSRAI == Opcode)
50136         Elt.ashrInPlace(ShiftVal);
50137       else
50138         Elt.lshrInPlace(ShiftVal);
50139     }
50140     // Reset undef elements since they were zeroed above.
50141     UndefElts = 0;
50142     return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
50143   };
50144 
50145   // Constant Folding.
50146   if (N->isOnlyUserOf(N0.getNode())) {
50147     if (SDValue C = TryConstantFold(N0))
50148       return C;
50149 
50150     // Fold (shift (logic X, C2), C1) -> (logic (shift X, C1), (shift C2, C1))
50151     // Don't break NOT patterns.
50152     SDValue BC = peekThroughOneUseBitcasts(N0);
50153     if (ISD::isBitwiseLogicOp(BC.getOpcode()) &&
50154         BC->isOnlyUserOf(BC.getOperand(1).getNode()) &&
50155         !ISD::isBuildVectorAllOnes(BC.getOperand(1).getNode())) {
50156       if (SDValue RHS = TryConstantFold(BC.getOperand(1))) {
50157         SDLoc DL(N);
50158         SDValue LHS = DAG.getNode(Opcode, DL, VT,
50159                                   DAG.getBitcast(VT, BC.getOperand(0)), N1);
50160         return DAG.getNode(BC.getOpcode(), DL, VT, LHS, RHS);
50161       }
50162     }
50163   }
50164 
50165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50166   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBitsPerElt),
50167                                DCI))
50168     return SDValue(N, 0);
50169 
50170   return SDValue();
50171 }
50172 
50173 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
50174                                    TargetLowering::DAGCombinerInfo &DCI,
50175                                    const X86Subtarget &Subtarget) {
50176   EVT VT = N->getValueType(0);
50177   unsigned Opcode = N->getOpcode();
50178   assert(((Opcode == X86ISD::PINSRB && VT == MVT::v16i8) ||
50179           (Opcode == X86ISD::PINSRW && VT == MVT::v8i16) ||
50180           Opcode == ISD::INSERT_VECTOR_ELT) &&
50181          "Unexpected vector insertion");
50182 
50183   SDValue Vec = N->getOperand(0);
50184   SDValue Scl = N->getOperand(1);
50185   SDValue Idx = N->getOperand(2);
50186 
50187   // Fold insert_vector_elt(undef, elt, 0) --> scalar_to_vector(elt).
50188   if (Opcode == ISD::INSERT_VECTOR_ELT && Vec.isUndef() && isNullConstant(Idx))
50189     return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Scl);
50190 
50191   if (Opcode == X86ISD::PINSRB || Opcode == X86ISD::PINSRW) {
50192     unsigned NumBitsPerElt = VT.getScalarSizeInBits();
50193     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50194     if (TLI.SimplifyDemandedBits(SDValue(N, 0),
50195                                  APInt::getAllOnes(NumBitsPerElt), DCI))
50196       return SDValue(N, 0);
50197   }
50198 
50199   // Attempt to combine insertion patterns to a shuffle.
50200   if (VT.isSimple() && DCI.isAfterLegalizeDAG()) {
50201     SDValue Op(N, 0);
50202     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
50203       return Res;
50204   }
50205 
50206   return SDValue();
50207 }
50208 
50209 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
50210 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
50211 /// OR -> CMPNEQSS.
50212 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
50213                                    TargetLowering::DAGCombinerInfo &DCI,
50214                                    const X86Subtarget &Subtarget) {
50215   unsigned opcode;
50216 
50217   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
50218   // we're requiring SSE2 for both.
50219   if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
50220     SDValue N0 = N->getOperand(0);
50221     SDValue N1 = N->getOperand(1);
50222     SDValue CMP0 = N0.getOperand(1);
50223     SDValue CMP1 = N1.getOperand(1);
50224     SDLoc DL(N);
50225 
50226     // The SETCCs should both refer to the same CMP.
50227     if (CMP0.getOpcode() != X86ISD::FCMP || CMP0 != CMP1)
50228       return SDValue();
50229 
50230     SDValue CMP00 = CMP0->getOperand(0);
50231     SDValue CMP01 = CMP0->getOperand(1);
50232     EVT     VT    = CMP00.getValueType();
50233 
50234     if (VT == MVT::f32 || VT == MVT::f64 ||
50235         (VT == MVT::f16 && Subtarget.hasFP16())) {
50236       bool ExpectingFlags = false;
50237       // Check for any users that want flags:
50238       for (const SDNode *U : N->uses()) {
50239         if (ExpectingFlags)
50240           break;
50241 
50242         switch (U->getOpcode()) {
50243         default:
50244         case ISD::BR_CC:
50245         case ISD::BRCOND:
50246         case ISD::SELECT:
50247           ExpectingFlags = true;
50248           break;
50249         case ISD::CopyToReg:
50250         case ISD::SIGN_EXTEND:
50251         case ISD::ZERO_EXTEND:
50252         case ISD::ANY_EXTEND:
50253           break;
50254         }
50255       }
50256 
50257       if (!ExpectingFlags) {
50258         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
50259         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
50260 
50261         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
50262           X86::CondCode tmp = cc0;
50263           cc0 = cc1;
50264           cc1 = tmp;
50265         }
50266 
50267         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
50268             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
50269           // FIXME: need symbolic constants for these magic numbers.
50270           // See X86ATTInstPrinter.cpp:printSSECC().
50271           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
50272           if (Subtarget.hasAVX512()) {
50273             SDValue FSetCC =
50274                 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
50275                             DAG.getTargetConstant(x86cc, DL, MVT::i8));
50276             // Need to fill with zeros to ensure the bitcast will produce zeroes
50277             // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
50278             SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
50279                                       DAG.getConstant(0, DL, MVT::v16i1),
50280                                       FSetCC, DAG.getIntPtrConstant(0, DL));
50281             return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
50282                                       N->getSimpleValueType(0));
50283           }
50284           SDValue OnesOrZeroesF =
50285               DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
50286                           CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
50287 
50288           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
50289           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
50290 
50291           if (is64BitFP && !Subtarget.is64Bit()) {
50292             // On a 32-bit target, we cannot bitcast the 64-bit float to a
50293             // 64-bit integer, since that's not a legal type. Since
50294             // OnesOrZeroesF is all ones or all zeroes, we don't need all the
50295             // bits, but can do this little dance to extract the lowest 32 bits
50296             // and work with those going forward.
50297             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
50298                                            OnesOrZeroesF);
50299             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
50300             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
50301                                         Vector32, DAG.getIntPtrConstant(0, DL));
50302             IntVT = MVT::i32;
50303           }
50304 
50305           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
50306           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
50307                                       DAG.getConstant(1, DL, IntVT));
50308           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
50309                                               ANDed);
50310           return OneBitOfTruth;
50311         }
50312       }
50313     }
50314   }
50315   return SDValue();
50316 }
50317 
50318 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
50319 static SDValue combineAndNotIntoANDNP(SDNode *N, SelectionDAG &DAG) {
50320   assert(N->getOpcode() == ISD::AND && "Unexpected opcode combine into ANDNP");
50321 
50322   MVT VT = N->getSimpleValueType(0);
50323   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
50324     return SDValue();
50325 
50326   SDValue X, Y;
50327   SDValue N0 = N->getOperand(0);
50328   SDValue N1 = N->getOperand(1);
50329 
50330   if (SDValue Not = IsNOT(N0, DAG)) {
50331     X = Not;
50332     Y = N1;
50333   } else if (SDValue Not = IsNOT(N1, DAG)) {
50334     X = Not;
50335     Y = N0;
50336   } else
50337     return SDValue();
50338 
50339   X = DAG.getBitcast(VT, X);
50340   Y = DAG.getBitcast(VT, Y);
50341   return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
50342 }
50343 
50344 /// Try to fold:
50345 ///   and (vector_shuffle<Z,...,Z>
50346 ///            (insert_vector_elt undef, (xor X, -1), Z), undef), Y
50347 ///   ->
50348 ///   andnp (vector_shuffle<Z,...,Z>
50349 ///              (insert_vector_elt undef, X, Z), undef), Y
50350 static SDValue combineAndShuffleNot(SDNode *N, SelectionDAG &DAG,
50351                                     const X86Subtarget &Subtarget) {
50352   assert(N->getOpcode() == ISD::AND && "Unexpected opcode combine into ANDNP");
50353 
50354   EVT VT = N->getValueType(0);
50355   // Do not split 256 and 512 bit vectors with SSE2 as they overwrite original
50356   // value and require extra moves.
50357   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
50358         ((VT.is256BitVector() || VT.is512BitVector()) && Subtarget.hasAVX())))
50359     return SDValue();
50360 
50361   auto GetNot = [&DAG](SDValue V) {
50362     auto *SVN = dyn_cast<ShuffleVectorSDNode>(peekThroughOneUseBitcasts(V));
50363     // TODO: SVN->hasOneUse() is a strong condition. It can be relaxed if all
50364     // end-users are ISD::AND including cases
50365     // (and(extract_vector_element(SVN), Y)).
50366     if (!SVN || !SVN->hasOneUse() || !SVN->isSplat() ||
50367         !SVN->getOperand(1).isUndef()) {
50368       return SDValue();
50369     }
50370     SDValue IVEN = SVN->getOperand(0);
50371     if (IVEN.getOpcode() != ISD::INSERT_VECTOR_ELT ||
50372         !IVEN.getOperand(0).isUndef() || !IVEN.hasOneUse())
50373       return SDValue();
50374     if (!isa<ConstantSDNode>(IVEN.getOperand(2)) ||
50375         IVEN.getConstantOperandAPInt(2) != SVN->getSplatIndex())
50376       return SDValue();
50377     SDValue Src = IVEN.getOperand(1);
50378     if (SDValue Not = IsNOT(Src, DAG)) {
50379       SDValue NotSrc = DAG.getBitcast(Src.getValueType(), Not);
50380       SDValue NotIVEN =
50381           DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(IVEN), IVEN.getValueType(),
50382                       IVEN.getOperand(0), NotSrc, IVEN.getOperand(2));
50383       return DAG.getVectorShuffle(SVN->getValueType(0), SDLoc(SVN), NotIVEN,
50384                                   SVN->getOperand(1), SVN->getMask());
50385     }
50386     return SDValue();
50387   };
50388 
50389   SDValue X, Y;
50390   SDValue N0 = N->getOperand(0);
50391   SDValue N1 = N->getOperand(1);
50392 
50393   if (SDValue Not = GetNot(N0)) {
50394     X = Not;
50395     Y = N1;
50396   } else if (SDValue Not = GetNot(N1)) {
50397     X = Not;
50398     Y = N0;
50399   } else
50400     return SDValue();
50401 
50402   X = DAG.getBitcast(VT, X);
50403   Y = DAG.getBitcast(VT, Y);
50404   SDLoc DL(N);
50405   // We do not split for SSE at all, but we need to split vectors for AVX1 and
50406   // AVX2.
50407   if (!Subtarget.useAVX512Regs() && VT.is512BitVector()) {
50408     SDValue LoX, HiX;
50409     std::tie(LoX, HiX) = splitVector(X, DAG, DL);
50410     SDValue LoY, HiY;
50411     std::tie(LoY, HiY) = splitVector(Y, DAG, DL);
50412     EVT SplitVT = LoX.getValueType();
50413     SDValue LoV = DAG.getNode(X86ISD::ANDNP, DL, SplitVT, {LoX, LoY});
50414     SDValue HiV = DAG.getNode(X86ISD::ANDNP, DL, SplitVT, {HiX, HiY});
50415     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, {LoV, HiV});
50416   }
50417   return DAG.getNode(X86ISD::ANDNP, DL, VT, {X, Y});
50418 }
50419 
50420 // Try to widen AND, OR and XOR nodes to VT in order to remove casts around
50421 // logical operations, like in the example below.
50422 //   or (and (truncate x, truncate y)),
50423 //      (xor (truncate z, build_vector (constants)))
50424 // Given a target type \p VT, we generate
50425 //   or (and x, y), (xor z, zext(build_vector (constants)))
50426 // given x, y and z are of type \p VT. We can do so, if operands are either
50427 // truncates from VT types, the second operand is a vector of constants or can
50428 // be recursively promoted.
50429 static SDValue PromoteMaskArithmetic(SDNode *N, EVT VT, SelectionDAG &DAG,
50430                                      unsigned Depth) {
50431   // Limit recursion to avoid excessive compile times.
50432   if (Depth >= SelectionDAG::MaxRecursionDepth)
50433     return SDValue();
50434 
50435   if (N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND &&
50436       N->getOpcode() != ISD::OR)
50437     return SDValue();
50438 
50439   SDValue N0 = N->getOperand(0);
50440   SDValue N1 = N->getOperand(1);
50441   SDLoc DL(N);
50442 
50443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50444   if (!TLI.isOperationLegalOrPromote(N->getOpcode(), VT))
50445     return SDValue();
50446 
50447   if (SDValue NN0 = PromoteMaskArithmetic(N0.getNode(), VT, DAG, Depth + 1))
50448     N0 = NN0;
50449   else {
50450     // The Left side has to be a trunc.
50451     if (N0.getOpcode() != ISD::TRUNCATE)
50452       return SDValue();
50453 
50454     // The type of the truncated inputs.
50455     if (N0.getOperand(0).getValueType() != VT)
50456       return SDValue();
50457 
50458     N0 = N0.getOperand(0);
50459   }
50460 
50461   if (SDValue NN1 = PromoteMaskArithmetic(N1.getNode(), VT, DAG, Depth + 1))
50462     N1 = NN1;
50463   else {
50464     // The right side has to be a 'trunc' or a constant vector.
50465     bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
50466                     N1.getOperand(0).getValueType() == VT;
50467     if (!RHSTrunc && !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
50468       return SDValue();
50469 
50470     if (RHSTrunc)
50471       N1 = N1.getOperand(0);
50472     else
50473       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
50474   }
50475 
50476   return DAG.getNode(N->getOpcode(), DL, VT, N0, N1);
50477 }
50478 
50479 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
50480 // register. In most cases we actually compare or select YMM-sized registers
50481 // and mixing the two types creates horrible code. This method optimizes
50482 // some of the transition sequences.
50483 // Even with AVX-512 this is still useful for removing casts around logical
50484 // operations on vXi1 mask types.
50485 static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
50486                                      const X86Subtarget &Subtarget) {
50487   EVT VT = N->getValueType(0);
50488   assert(VT.isVector() && "Expected vector type");
50489 
50490   SDLoc DL(N);
50491   assert((N->getOpcode() == ISD::ANY_EXTEND ||
50492           N->getOpcode() == ISD::ZERO_EXTEND ||
50493           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
50494 
50495   SDValue Narrow = N->getOperand(0);
50496   EVT NarrowVT = Narrow.getValueType();
50497 
50498   // Generate the wide operation.
50499   SDValue Op = PromoteMaskArithmetic(Narrow.getNode(), VT, DAG, 0);
50500   if (!Op)
50501     return SDValue();
50502   switch (N->getOpcode()) {
50503   default: llvm_unreachable("Unexpected opcode");
50504   case ISD::ANY_EXTEND:
50505     return Op;
50506   case ISD::ZERO_EXTEND:
50507     return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
50508   case ISD::SIGN_EXTEND:
50509     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
50510                        Op, DAG.getValueType(NarrowVT));
50511   }
50512 }
50513 
50514 static unsigned convertIntLogicToFPLogicOpcode(unsigned Opcode) {
50515   unsigned FPOpcode;
50516   switch (Opcode) {
50517   default: llvm_unreachable("Unexpected input node for FP logic conversion");
50518   case ISD::AND: FPOpcode = X86ISD::FAND; break;
50519   case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
50520   case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
50521   }
50522   return FPOpcode;
50523 }
50524 
50525 /// If both input operands of a logic op are being cast from floating-point
50526 /// types or FP compares, try to convert this into a floating-point logic node
50527 /// to avoid unnecessary moves from SSE to integer registers.
50528 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
50529                                         TargetLowering::DAGCombinerInfo &DCI,
50530                                         const X86Subtarget &Subtarget) {
50531   EVT VT = N->getValueType(0);
50532   SDValue N0 = N->getOperand(0);
50533   SDValue N1 = N->getOperand(1);
50534   SDLoc DL(N);
50535 
50536   if (!((N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) ||
50537         (N0.getOpcode() == ISD::SETCC && N1.getOpcode() == ISD::SETCC)))
50538     return SDValue();
50539 
50540   SDValue N00 = N0.getOperand(0);
50541   SDValue N10 = N1.getOperand(0);
50542   EVT N00Type = N00.getValueType();
50543   EVT N10Type = N10.getValueType();
50544 
50545   // Ensure that both types are the same and are legal scalar fp types.
50546   if (N00Type != N10Type || !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
50547                               (Subtarget.hasSSE2() && N00Type == MVT::f64) ||
50548                               (Subtarget.hasFP16() && N00Type == MVT::f16)))
50549     return SDValue();
50550 
50551   if (N0.getOpcode() == ISD::BITCAST && !DCI.isBeforeLegalizeOps()) {
50552     unsigned FPOpcode = convertIntLogicToFPLogicOpcode(N->getOpcode());
50553     SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
50554     return DAG.getBitcast(VT, FPLogic);
50555   }
50556 
50557   if (VT != MVT::i1 || N0.getOpcode() != ISD::SETCC || !N0.hasOneUse() ||
50558       !N1.hasOneUse())
50559     return SDValue();
50560 
50561   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0.getOperand(2))->get();
50562   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1.getOperand(2))->get();
50563 
50564   // The vector ISA for FP predicates is incomplete before AVX, so converting
50565   // COMIS* to CMPS* may not be a win before AVX.
50566   if (!Subtarget.hasAVX() &&
50567       !(cheapX86FSETCC_SSE(CC0) && cheapX86FSETCC_SSE(CC1)))
50568     return SDValue();
50569 
50570   // Convert scalar FP compares and logic to vector compares (COMIS* to CMPS*)
50571   // and vector logic:
50572   // logic (setcc N00, N01), (setcc N10, N11) -->
50573   // extelt (logic (setcc (s2v N00), (s2v N01)), setcc (s2v N10), (s2v N11))), 0
50574   unsigned NumElts = 128 / N00Type.getSizeInBits();
50575   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), N00Type, NumElts);
50576   EVT BoolVecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
50577   SDValue ZeroIndex = DAG.getVectorIdxConstant(0, DL);
50578   SDValue N01 = N0.getOperand(1);
50579   SDValue N11 = N1.getOperand(1);
50580   SDValue Vec00 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N00);
50581   SDValue Vec01 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N01);
50582   SDValue Vec10 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N10);
50583   SDValue Vec11 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N11);
50584   SDValue Setcc0 = DAG.getSetCC(DL, BoolVecVT, Vec00, Vec01, CC0);
50585   SDValue Setcc1 = DAG.getSetCC(DL, BoolVecVT, Vec10, Vec11, CC1);
50586   SDValue Logic = DAG.getNode(N->getOpcode(), DL, BoolVecVT, Setcc0, Setcc1);
50587   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Logic, ZeroIndex);
50588 }
50589 
50590 // Attempt to fold BITOP(MOVMSK(X),MOVMSK(Y)) -> MOVMSK(BITOP(X,Y))
50591 // to reduce XMM->GPR traffic.
50592 static SDValue combineBitOpWithMOVMSK(SDNode *N, SelectionDAG &DAG) {
50593   unsigned Opc = N->getOpcode();
50594   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
50595          "Unexpected bit opcode");
50596 
50597   SDValue N0 = N->getOperand(0);
50598   SDValue N1 = N->getOperand(1);
50599 
50600   // Both operands must be single use MOVMSK.
50601   if (N0.getOpcode() != X86ISD::MOVMSK || !N0.hasOneUse() ||
50602       N1.getOpcode() != X86ISD::MOVMSK || !N1.hasOneUse())
50603     return SDValue();
50604 
50605   SDValue Vec0 = N0.getOperand(0);
50606   SDValue Vec1 = N1.getOperand(0);
50607   EVT VecVT0 = Vec0.getValueType();
50608   EVT VecVT1 = Vec1.getValueType();
50609 
50610   // Both MOVMSK operands must be from vectors of the same size and same element
50611   // size, but its OK for a fp/int diff.
50612   if (VecVT0.getSizeInBits() != VecVT1.getSizeInBits() ||
50613       VecVT0.getScalarSizeInBits() != VecVT1.getScalarSizeInBits())
50614     return SDValue();
50615 
50616   SDLoc DL(N);
50617   unsigned VecOpc =
50618       VecVT0.isFloatingPoint() ? convertIntLogicToFPLogicOpcode(Opc) : Opc;
50619   SDValue Result =
50620       DAG.getNode(VecOpc, DL, VecVT0, Vec0, DAG.getBitcast(VecVT0, Vec1));
50621   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
50622 }
50623 
50624 // Attempt to fold BITOP(SHIFT(X,Z),SHIFT(Y,Z)) -> SHIFT(BITOP(X,Y),Z).
50625 // NOTE: This is a very limited case of what SimplifyUsingDistributiveLaws
50626 // handles in InstCombine.
50627 static SDValue combineBitOpWithShift(SDNode *N, SelectionDAG &DAG) {
50628   unsigned Opc = N->getOpcode();
50629   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
50630          "Unexpected bit opcode");
50631 
50632   SDValue N0 = N->getOperand(0);
50633   SDValue N1 = N->getOperand(1);
50634   EVT VT = N->getValueType(0);
50635 
50636   // Both operands must be single use.
50637   if (!N0.hasOneUse() || !N1.hasOneUse())
50638     return SDValue();
50639 
50640   // Search for matching shifts.
50641   SDValue BC0 = peekThroughOneUseBitcasts(N0);
50642   SDValue BC1 = peekThroughOneUseBitcasts(N1);
50643 
50644   unsigned BCOpc = BC0.getOpcode();
50645   EVT BCVT = BC0.getValueType();
50646   if (BCOpc != BC1->getOpcode() || BCVT != BC1.getValueType())
50647     return SDValue();
50648 
50649   switch (BCOpc) {
50650   case X86ISD::VSHLI:
50651   case X86ISD::VSRLI:
50652   case X86ISD::VSRAI: {
50653     if (BC0.getOperand(1) != BC1.getOperand(1))
50654       return SDValue();
50655 
50656     SDLoc DL(N);
50657     SDValue BitOp =
50658         DAG.getNode(Opc, DL, BCVT, BC0.getOperand(0), BC1.getOperand(0));
50659     SDValue Shift = DAG.getNode(BCOpc, DL, BCVT, BitOp, BC0.getOperand(1));
50660     return DAG.getBitcast(VT, Shift);
50661   }
50662   }
50663 
50664   return SDValue();
50665 }
50666 
50667 // Attempt to fold:
50668 // BITOP(PACKSS(X,Z),PACKSS(Y,W)) --> PACKSS(BITOP(X,Y),BITOP(Z,W)).
50669 // TODO: Handle PACKUS handling.
50670 static SDValue combineBitOpWithPACK(SDNode *N, SelectionDAG &DAG) {
50671   unsigned Opc = N->getOpcode();
50672   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
50673          "Unexpected bit opcode");
50674 
50675   SDValue N0 = N->getOperand(0);
50676   SDValue N1 = N->getOperand(1);
50677   EVT VT = N->getValueType(0);
50678 
50679   // Both operands must be single use.
50680   if (!N0.hasOneUse() || !N1.hasOneUse())
50681     return SDValue();
50682 
50683   // Search for matching packs.
50684   N0 = peekThroughOneUseBitcasts(N0);
50685   N1 = peekThroughOneUseBitcasts(N1);
50686 
50687   if (N0.getOpcode() != X86ISD::PACKSS || N1.getOpcode() != X86ISD::PACKSS)
50688     return SDValue();
50689 
50690   MVT DstVT = N0.getSimpleValueType();
50691   if (DstVT != N1.getSimpleValueType())
50692     return SDValue();
50693 
50694   MVT SrcVT = N0.getOperand(0).getSimpleValueType();
50695   unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
50696 
50697   // Limit to allsignbits packing.
50698   if (DAG.ComputeNumSignBits(N0.getOperand(0)) != NumSrcBits ||
50699       DAG.ComputeNumSignBits(N0.getOperand(1)) != NumSrcBits ||
50700       DAG.ComputeNumSignBits(N1.getOperand(0)) != NumSrcBits ||
50701       DAG.ComputeNumSignBits(N1.getOperand(1)) != NumSrcBits)
50702     return SDValue();
50703 
50704   SDLoc DL(N);
50705   SDValue LHS = DAG.getNode(Opc, DL, SrcVT, N0.getOperand(0), N1.getOperand(0));
50706   SDValue RHS = DAG.getNode(Opc, DL, SrcVT, N0.getOperand(1), N1.getOperand(1));
50707   return DAG.getBitcast(VT, DAG.getNode(X86ISD::PACKSS, DL, DstVT, LHS, RHS));
50708 }
50709 
50710 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
50711 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
50712 /// with a shift-right to eliminate loading the vector constant mask value.
50713 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
50714                                      const X86Subtarget &Subtarget) {
50715   SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
50716   SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
50717   EVT VT = Op0.getValueType();
50718   if (VT != Op1.getValueType() || !VT.isSimple() || !VT.isInteger())
50719     return SDValue();
50720 
50721   // Try to convert an "is positive" signbit masking operation into arithmetic
50722   // shift and "andn". This saves a materialization of a -1 vector constant.
50723   // The "is negative" variant should be handled more generally because it only
50724   // requires "and" rather than "andn":
50725   // and (pcmpgt X, -1), Y --> pandn (vsrai X, BitWidth - 1), Y
50726   //
50727   // This is limited to the original type to avoid producing even more bitcasts.
50728   // If the bitcasts can't be eliminated, then it is unlikely that this fold
50729   // will be profitable.
50730   if (N->getValueType(0) == VT &&
50731       supportedVectorShiftWithImm(VT, Subtarget, ISD::SRA)) {
50732     SDValue X, Y;
50733     if (Op1.getOpcode() == X86ISD::PCMPGT &&
50734         isAllOnesOrAllOnesSplat(Op1.getOperand(1)) && Op1.hasOneUse()) {
50735       X = Op1.getOperand(0);
50736       Y = Op0;
50737     } else if (Op0.getOpcode() == X86ISD::PCMPGT &&
50738                isAllOnesOrAllOnesSplat(Op0.getOperand(1)) && Op0.hasOneUse()) {
50739       X = Op0.getOperand(0);
50740       Y = Op1;
50741     }
50742     if (X && Y) {
50743       SDLoc DL(N);
50744       SDValue Sra =
50745           getTargetVShiftByConstNode(X86ISD::VSRAI, DL, VT.getSimpleVT(), X,
50746                                      VT.getScalarSizeInBits() - 1, DAG);
50747       return DAG.getNode(X86ISD::ANDNP, DL, VT, Sra, Y);
50748     }
50749   }
50750 
50751   APInt SplatVal;
50752   if (!X86::isConstantSplat(Op1, SplatVal, false) || !SplatVal.isMask())
50753     return SDValue();
50754 
50755   // Don't prevent creation of ANDN.
50756   if (isBitwiseNot(Op0))
50757     return SDValue();
50758 
50759   if (!supportedVectorShiftWithImm(VT, Subtarget, ISD::SRL))
50760     return SDValue();
50761 
50762   unsigned EltBitWidth = VT.getScalarSizeInBits();
50763   if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
50764     return SDValue();
50765 
50766   SDLoc DL(N);
50767   unsigned ShiftVal = SplatVal.countr_one();
50768   SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
50769   SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT, Op0, ShAmt);
50770   return DAG.getBitcast(N->getValueType(0), Shift);
50771 }
50772 
50773 // Get the index node from the lowered DAG of a GEP IR instruction with one
50774 // indexing dimension.
50775 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
50776   if (Ld->isIndexed())
50777     return SDValue();
50778 
50779   SDValue Base = Ld->getBasePtr();
50780 
50781   if (Base.getOpcode() != ISD::ADD)
50782     return SDValue();
50783 
50784   SDValue ShiftedIndex = Base.getOperand(0);
50785 
50786   if (ShiftedIndex.getOpcode() != ISD::SHL)
50787     return SDValue();
50788 
50789   return ShiftedIndex.getOperand(0);
50790 
50791 }
50792 
50793 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
50794   if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
50795     switch (VT.getSizeInBits()) {
50796     default: return false;
50797     case 64: return Subtarget.is64Bit() ? true : false;
50798     case 32: return true;
50799     }
50800   }
50801   return false;
50802 }
50803 
50804 // This function recognizes cases where X86 bzhi instruction can replace and
50805 // 'and-load' sequence.
50806 // In case of loading integer value from an array of constants which is defined
50807 // as follows:
50808 //
50809 //   int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
50810 //
50811 // then applying a bitwise and on the result with another input.
50812 // It's equivalent to performing bzhi (zero high bits) on the input, with the
50813 // same index of the load.
50814 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
50815                                     const X86Subtarget &Subtarget) {
50816   MVT VT = Node->getSimpleValueType(0);
50817   SDLoc dl(Node);
50818 
50819   // Check if subtarget has BZHI instruction for the node's type
50820   if (!hasBZHI(Subtarget, VT))
50821     return SDValue();
50822 
50823   // Try matching the pattern for both operands.
50824   for (unsigned i = 0; i < 2; i++) {
50825     SDValue N = Node->getOperand(i);
50826     LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
50827 
50828      // continue if the operand is not a load instruction
50829     if (!Ld)
50830       return SDValue();
50831 
50832     const Value *MemOp = Ld->getMemOperand()->getValue();
50833 
50834     if (!MemOp)
50835       return SDValue();
50836 
50837     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
50838       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
50839         if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
50840 
50841           Constant *Init = GV->getInitializer();
50842           Type *Ty = Init->getType();
50843           if (!isa<ConstantDataArray>(Init) ||
50844               !Ty->getArrayElementType()->isIntegerTy() ||
50845               Ty->getArrayElementType()->getScalarSizeInBits() !=
50846                   VT.getSizeInBits() ||
50847               Ty->getArrayNumElements() >
50848                   Ty->getArrayElementType()->getScalarSizeInBits())
50849             continue;
50850 
50851           // Check if the array's constant elements are suitable to our case.
50852           uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
50853           bool ConstantsMatch = true;
50854           for (uint64_t j = 0; j < ArrayElementCount; j++) {
50855             auto *Elem = cast<ConstantInt>(Init->getAggregateElement(j));
50856             if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
50857               ConstantsMatch = false;
50858               break;
50859             }
50860           }
50861           if (!ConstantsMatch)
50862             continue;
50863 
50864           // Do the transformation (For 32-bit type):
50865           // -> (and (load arr[idx]), inp)
50866           // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
50867           //    that will be replaced with one bzhi instruction.
50868           SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
50869           SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
50870 
50871           // Get the Node which indexes into the array.
50872           SDValue Index = getIndexFromUnindexedLoad(Ld);
50873           if (!Index)
50874             return SDValue();
50875           Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
50876 
50877           SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
50878           Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
50879 
50880           SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
50881           SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
50882 
50883           return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
50884         }
50885       }
50886     }
50887   }
50888   return SDValue();
50889 }
50890 
50891 // Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
50892 // Where C is a mask containing the same number of bits as the setcc and
50893 // where the setcc will freely 0 upper bits of k-register. We can replace the
50894 // undef in the concat with 0s and remove the AND. This mainly helps with
50895 // v2i1/v4i1 setcc being casted to scalar.
50896 static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
50897                                              const X86Subtarget &Subtarget) {
50898   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
50899 
50900   EVT VT = N->getValueType(0);
50901 
50902   // Make sure this is an AND with constant. We will check the value of the
50903   // constant later.
50904   auto *C1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
50905   if (!C1)
50906     return SDValue();
50907 
50908   // This is implied by the ConstantSDNode.
50909   assert(!VT.isVector() && "Expected scalar VT!");
50910 
50911   SDValue Src = N->getOperand(0);
50912   if (!Src.hasOneUse())
50913     return SDValue();
50914 
50915   // (Optionally) peek through any_extend().
50916   if (Src.getOpcode() == ISD::ANY_EXTEND) {
50917     if (!Src.getOperand(0).hasOneUse())
50918       return SDValue();
50919     Src = Src.getOperand(0);
50920   }
50921 
50922   if (Src.getOpcode() != ISD::BITCAST || !Src.getOperand(0).hasOneUse())
50923     return SDValue();
50924 
50925   Src = Src.getOperand(0);
50926   EVT SrcVT = Src.getValueType();
50927 
50928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50929   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
50930       !TLI.isTypeLegal(SrcVT))
50931     return SDValue();
50932 
50933   if (Src.getOpcode() != ISD::CONCAT_VECTORS)
50934     return SDValue();
50935 
50936   // We only care about the first subvector of the concat, we expect the
50937   // other subvectors to be ignored due to the AND if we make the change.
50938   SDValue SubVec = Src.getOperand(0);
50939   EVT SubVecVT = SubVec.getValueType();
50940 
50941   // The RHS of the AND should be a mask with as many bits as SubVec.
50942   if (!TLI.isTypeLegal(SubVecVT) ||
50943       !C1->getAPIntValue().isMask(SubVecVT.getVectorNumElements()))
50944     return SDValue();
50945 
50946   // First subvector should be a setcc with a legal result type or a
50947   // AND containing at least one setcc with a legal result type.
50948   auto IsLegalSetCC = [&](SDValue V) {
50949     if (V.getOpcode() != ISD::SETCC)
50950       return false;
50951     EVT SetccVT = V.getOperand(0).getValueType();
50952     if (!TLI.isTypeLegal(SetccVT) ||
50953         !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
50954       return false;
50955     if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
50956       return false;
50957     return true;
50958   };
50959   if (!(IsLegalSetCC(SubVec) || (SubVec.getOpcode() == ISD::AND &&
50960                                  (IsLegalSetCC(SubVec.getOperand(0)) ||
50961                                   IsLegalSetCC(SubVec.getOperand(1))))))
50962     return SDValue();
50963 
50964   // We passed all the checks. Rebuild the concat_vectors with zeroes
50965   // and cast it back to VT.
50966   SDLoc dl(N);
50967   SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
50968                               DAG.getConstant(0, dl, SubVecVT));
50969   Ops[0] = SubVec;
50970   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
50971                                Ops);
50972   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcVT.getSizeInBits());
50973   return DAG.getZExtOrTrunc(DAG.getBitcast(IntVT, Concat), dl, VT);
50974 }
50975 
50976 static SDValue getBMIMatchingOp(unsigned Opc, SelectionDAG &DAG,
50977                                 SDValue OpMustEq, SDValue Op, unsigned Depth) {
50978   // We don't want to go crazy with the recursion here. This isn't a super
50979   // important optimization.
50980   static constexpr unsigned kMaxDepth = 2;
50981 
50982   // Only do this re-ordering if op has one use.
50983   if (!Op.hasOneUse())
50984     return SDValue();
50985 
50986   SDLoc DL(Op);
50987   // If we hit another assosiative op, recurse further.
50988   if (Op.getOpcode() == Opc) {
50989     // Done recursing.
50990     if (Depth++ >= kMaxDepth)
50991       return SDValue();
50992 
50993     for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx)
50994       if (SDValue R =
50995               getBMIMatchingOp(Opc, DAG, OpMustEq, Op.getOperand(OpIdx), Depth))
50996         return DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), R,
50997                            Op.getOperand(1 - OpIdx));
50998 
50999   } else if (Op.getOpcode() == ISD::SUB) {
51000     if (Opc == ISD::AND) {
51001       // BLSI: (and x, (sub 0, x))
51002       if (isNullConstant(Op.getOperand(0)) && Op.getOperand(1) == OpMustEq)
51003         return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
51004     }
51005     // Opc must be ISD::AND or ISD::XOR
51006     // BLSR: (and x, (sub x, 1))
51007     // BLSMSK: (xor x, (sub x, 1))
51008     if (isOneConstant(Op.getOperand(1)) && Op.getOperand(0) == OpMustEq)
51009       return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
51010 
51011   } else if (Op.getOpcode() == ISD::ADD) {
51012     // Opc must be ISD::AND or ISD::XOR
51013     // BLSR: (and x, (add x, -1))
51014     // BLSMSK: (xor x, (add x, -1))
51015     if (isAllOnesConstant(Op.getOperand(1)) && Op.getOperand(0) == OpMustEq)
51016       return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
51017   }
51018   return SDValue();
51019 }
51020 
51021 static SDValue combineBMILogicOp(SDNode *N, SelectionDAG &DAG,
51022                                  const X86Subtarget &Subtarget) {
51023   EVT VT = N->getValueType(0);
51024   // Make sure this node is a candidate for BMI instructions.
51025   if (!Subtarget.hasBMI() || !VT.isScalarInteger() ||
51026       (VT != MVT::i32 && VT != MVT::i64))
51027     return SDValue();
51028 
51029   assert(N->getOpcode() == ISD::AND || N->getOpcode() == ISD::XOR);
51030 
51031   // Try and match LHS and RHS.
51032   for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx)
51033     if (SDValue OpMatch =
51034             getBMIMatchingOp(N->getOpcode(), DAG, N->getOperand(OpIdx),
51035                              N->getOperand(1 - OpIdx), 0))
51036       return OpMatch;
51037   return SDValue();
51038 }
51039 
51040 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
51041                           TargetLowering::DAGCombinerInfo &DCI,
51042                           const X86Subtarget &Subtarget) {
51043   SDValue N0 = N->getOperand(0);
51044   SDValue N1 = N->getOperand(1);
51045   EVT VT = N->getValueType(0);
51046   SDLoc dl(N);
51047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51048 
51049   // If this is SSE1 only convert to FAND to avoid scalarization.
51050   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
51051     return DAG.getBitcast(MVT::v4i32,
51052                           DAG.getNode(X86ISD::FAND, dl, MVT::v4f32,
51053                                       DAG.getBitcast(MVT::v4f32, N0),
51054                                       DAG.getBitcast(MVT::v4f32, N1)));
51055   }
51056 
51057   // Use a 32-bit and+zext if upper bits known zero.
51058   if (VT == MVT::i64 && Subtarget.is64Bit() && !isa<ConstantSDNode>(N1)) {
51059     APInt HiMask = APInt::getHighBitsSet(64, 32);
51060     if (DAG.MaskedValueIsZero(N1, HiMask) ||
51061         DAG.MaskedValueIsZero(N0, HiMask)) {
51062       SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N0);
51063       SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N1);
51064       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
51065                          DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
51066     }
51067   }
51068 
51069   // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
51070   // TODO: Support multiple SrcOps.
51071   if (VT == MVT::i1) {
51072     SmallVector<SDValue, 2> SrcOps;
51073     SmallVector<APInt, 2> SrcPartials;
51074     if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps, &SrcPartials) &&
51075         SrcOps.size() == 1) {
51076       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
51077       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
51078       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
51079       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
51080         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
51081       if (Mask) {
51082         assert(SrcPartials[0].getBitWidth() == NumElts &&
51083                "Unexpected partial reduction mask");
51084         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
51085         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
51086         return DAG.getSetCC(dl, MVT::i1, Mask, PartialBits, ISD::SETEQ);
51087       }
51088     }
51089   }
51090 
51091   // InstCombine converts:
51092   //    `(-x << C0) & C1`
51093   // to
51094   //    `(x * (Pow2_Ceil(C1) - (1 << C0))) & C1`
51095   // This saves an IR instruction but on x86 the neg/shift version is preferable
51096   // so undo the transform.
51097 
51098   if (N0.getOpcode() == ISD::MUL && N0.hasOneUse()) {
51099     // TODO: We don't actually need a splat for this, we just need the checks to
51100     // hold for each element.
51101     ConstantSDNode *N1C = isConstOrConstSplat(N1, /*AllowUndefs*/ true,
51102                                               /*AllowTruncation*/ false);
51103     ConstantSDNode *N01C =
51104         isConstOrConstSplat(N0.getOperand(1), /*AllowUndefs*/ true,
51105                             /*AllowTruncation*/ false);
51106     if (N1C && N01C) {
51107       const APInt &MulC = N01C->getAPIntValue();
51108       const APInt &AndC = N1C->getAPIntValue();
51109       APInt MulCLowBit = MulC & (-MulC);
51110       if (MulC.uge(AndC) && !MulC.isPowerOf2() &&
51111           (MulCLowBit + MulC).isPowerOf2()) {
51112         SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
51113                                   N0.getOperand(0));
51114         int32_t MulCLowBitLog = MulCLowBit.exactLogBase2();
51115         assert(MulCLowBitLog != -1 &&
51116                "Isolated lowbit is somehow not a power of 2!");
51117         SDValue Shift = DAG.getNode(ISD::SHL, dl, VT, Neg,
51118                                     DAG.getConstant(MulCLowBitLog, dl, VT));
51119         return DAG.getNode(ISD::AND, dl, VT, Shift, N1);
51120       }
51121     }
51122   }
51123 
51124   if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
51125     return V;
51126 
51127   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
51128     return R;
51129 
51130   if (SDValue R = combineBitOpWithShift(N, DAG))
51131     return R;
51132 
51133   if (SDValue R = combineBitOpWithPACK(N, DAG))
51134     return R;
51135 
51136   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
51137     return FPLogic;
51138 
51139   if (SDValue R = combineAndShuffleNot(N, DAG, Subtarget))
51140     return R;
51141 
51142   if (DCI.isBeforeLegalizeOps())
51143     return SDValue();
51144 
51145   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
51146     return R;
51147 
51148   if (SDValue R = combineAndNotIntoANDNP(N, DAG))
51149     return R;
51150 
51151   if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
51152     return ShiftRight;
51153 
51154   if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
51155     return R;
51156 
51157   // fold (and (mul x, c1), c2) -> (mul x, (and c1, c2))
51158   // iff c2 is all/no bits mask - i.e. a select-with-zero mask.
51159   // TODO: Handle PMULDQ/PMULUDQ/VPMADDWD/VPMADDUBSW?
51160   if (VT.isVector() && getTargetConstantFromNode(N1)) {
51161     unsigned Opc0 = N0.getOpcode();
51162     if ((Opc0 == ISD::MUL || Opc0 == ISD::MULHU || Opc0 == ISD::MULHS) &&
51163         getTargetConstantFromNode(N0.getOperand(1)) &&
51164         DAG.ComputeNumSignBits(N1) == VT.getScalarSizeInBits() &&
51165         N0->hasOneUse() && N0.getOperand(1)->hasOneUse()) {
51166       SDValue MaskMul = DAG.getNode(ISD::AND, dl, VT, N0.getOperand(1), N1);
51167       return DAG.getNode(Opc0, dl, VT, N0.getOperand(0), MaskMul);
51168     }
51169   }
51170 
51171   // Fold AND(SRL(X,Y),1) -> SETCC(BT(X,Y), COND_B) iff Y is not a constant
51172   // avoids slow variable shift (moving shift amount to ECX etc.)
51173   if (isOneConstant(N1) && N0->hasOneUse()) {
51174     SDValue Src = N0;
51175     while ((Src.getOpcode() == ISD::ZERO_EXTEND ||
51176             Src.getOpcode() == ISD::TRUNCATE) &&
51177            Src.getOperand(0)->hasOneUse())
51178       Src = Src.getOperand(0);
51179     bool ContainsNOT = false;
51180     X86::CondCode X86CC = X86::COND_B;
51181     // Peek through AND(NOT(SRL(X,Y)),1).
51182     if (isBitwiseNot(Src)) {
51183       Src = Src.getOperand(0);
51184       X86CC = X86::COND_AE;
51185       ContainsNOT = true;
51186     }
51187     if (Src.getOpcode() == ISD::SRL &&
51188         !isa<ConstantSDNode>(Src.getOperand(1))) {
51189       SDValue BitNo = Src.getOperand(1);
51190       Src = Src.getOperand(0);
51191       // Peek through AND(SRL(NOT(X),Y),1).
51192       if (isBitwiseNot(Src)) {
51193         Src = Src.getOperand(0);
51194         X86CC = X86CC == X86::COND_AE ? X86::COND_B : X86::COND_AE;
51195         ContainsNOT = true;
51196       }
51197       // If we have BMI2 then SHRX should be faster for i32/i64 cases.
51198       if (!(Subtarget.hasBMI2() && !ContainsNOT && VT.getSizeInBits() >= 32))
51199         if (SDValue BT = getBT(Src, BitNo, dl, DAG))
51200           return DAG.getZExtOrTrunc(getSETCC(X86CC, BT, dl, DAG), dl, VT);
51201     }
51202   }
51203 
51204   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
51205     // Attempt to recursively combine a bitmask AND with shuffles.
51206     SDValue Op(N, 0);
51207     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
51208       return Res;
51209 
51210     // If either operand is a constant mask, then only the elements that aren't
51211     // zero are actually demanded by the other operand.
51212     auto GetDemandedMasks = [&](SDValue Op) {
51213       APInt UndefElts;
51214       SmallVector<APInt> EltBits;
51215       int NumElts = VT.getVectorNumElements();
51216       int EltSizeInBits = VT.getScalarSizeInBits();
51217       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
51218       APInt DemandedElts = APInt::getAllOnes(NumElts);
51219       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
51220                                         EltBits)) {
51221         DemandedBits.clearAllBits();
51222         DemandedElts.clearAllBits();
51223         for (int I = 0; I != NumElts; ++I) {
51224           if (UndefElts[I]) {
51225             // We can't assume an undef src element gives an undef dst - the
51226             // other src might be zero.
51227             DemandedBits.setAllBits();
51228             DemandedElts.setBit(I);
51229           } else if (!EltBits[I].isZero()) {
51230             DemandedBits |= EltBits[I];
51231             DemandedElts.setBit(I);
51232           }
51233         }
51234       }
51235       return std::make_pair(DemandedBits, DemandedElts);
51236     };
51237     APInt Bits0, Elts0;
51238     APInt Bits1, Elts1;
51239     std::tie(Bits0, Elts0) = GetDemandedMasks(N1);
51240     std::tie(Bits1, Elts1) = GetDemandedMasks(N0);
51241 
51242     if (TLI.SimplifyDemandedVectorElts(N0, Elts0, DCI) ||
51243         TLI.SimplifyDemandedVectorElts(N1, Elts1, DCI) ||
51244         TLI.SimplifyDemandedBits(N0, Bits0, Elts0, DCI) ||
51245         TLI.SimplifyDemandedBits(N1, Bits1, Elts1, DCI)) {
51246       if (N->getOpcode() != ISD::DELETED_NODE)
51247         DCI.AddToWorklist(N);
51248       return SDValue(N, 0);
51249     }
51250 
51251     SDValue NewN0 = TLI.SimplifyMultipleUseDemandedBits(N0, Bits0, Elts0, DAG);
51252     SDValue NewN1 = TLI.SimplifyMultipleUseDemandedBits(N1, Bits1, Elts1, DAG);
51253     if (NewN0 || NewN1)
51254       return DAG.getNode(ISD::AND, dl, VT, NewN0 ? NewN0 : N0,
51255                          NewN1 ? NewN1 : N1);
51256   }
51257 
51258   // Attempt to combine a scalar bitmask AND with an extracted shuffle.
51259   if ((VT.getScalarSizeInBits() % 8) == 0 &&
51260       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
51261       isa<ConstantSDNode>(N0.getOperand(1))) {
51262     SDValue BitMask = N1;
51263     SDValue SrcVec = N0.getOperand(0);
51264     EVT SrcVecVT = SrcVec.getValueType();
51265 
51266     // Check that the constant bitmask masks whole bytes.
51267     APInt UndefElts;
51268     SmallVector<APInt, 64> EltBits;
51269     if (VT == SrcVecVT.getScalarType() && N0->isOnlyUserOf(SrcVec.getNode()) &&
51270         getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
51271         llvm::all_of(EltBits, [](const APInt &M) {
51272           return M.isZero() || M.isAllOnes();
51273         })) {
51274       unsigned NumElts = SrcVecVT.getVectorNumElements();
51275       unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
51276       unsigned Idx = N0.getConstantOperandVal(1);
51277 
51278       // Create a root shuffle mask from the byte mask and the extracted index.
51279       SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
51280       for (unsigned i = 0; i != Scale; ++i) {
51281         if (UndefElts[i])
51282           continue;
51283         int VecIdx = Scale * Idx + i;
51284         ShuffleMask[VecIdx] = EltBits[i].isZero() ? SM_SentinelZero : VecIdx;
51285       }
51286 
51287       if (SDValue Shuffle = combineX86ShufflesRecursively(
51288               {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
51289               X86::MaxShuffleCombineDepth,
51290               /*HasVarMask*/ false, /*AllowVarCrossLaneMask*/ true,
51291               /*AllowVarPerLaneMask*/ true, DAG, Subtarget))
51292         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Shuffle,
51293                            N0.getOperand(1));
51294     }
51295   }
51296 
51297   if (SDValue R = combineBMILogicOp(N, DAG, Subtarget))
51298     return R;
51299 
51300   return SDValue();
51301 }
51302 
51303 // Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
51304 static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
51305                                      const X86Subtarget &Subtarget) {
51306   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
51307 
51308   MVT VT = N->getSimpleValueType(0);
51309   unsigned EltSizeInBits = VT.getScalarSizeInBits();
51310   if (!VT.isVector() || (EltSizeInBits % 8) != 0)
51311     return SDValue();
51312 
51313   SDValue N0 = peekThroughBitcasts(N->getOperand(0));
51314   SDValue N1 = peekThroughBitcasts(N->getOperand(1));
51315   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
51316     return SDValue();
51317 
51318   // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
51319   // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
51320   if (!(Subtarget.hasXOP() || useVPTERNLOG(Subtarget, VT) ||
51321         !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
51322     return SDValue();
51323 
51324   // Attempt to extract constant byte masks.
51325   APInt UndefElts0, UndefElts1;
51326   SmallVector<APInt, 32> EltBits0, EltBits1;
51327   if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
51328                                      false, false))
51329     return SDValue();
51330   if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
51331                                      false, false))
51332     return SDValue();
51333 
51334   for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
51335     // TODO - add UNDEF elts support.
51336     if (UndefElts0[i] || UndefElts1[i])
51337       return SDValue();
51338     if (EltBits0[i] != ~EltBits1[i])
51339       return SDValue();
51340   }
51341 
51342   SDLoc DL(N);
51343 
51344   if (useVPTERNLOG(Subtarget, VT)) {
51345     // Emit a VPTERNLOG node directly - 0xCA is the imm code for A?B:C.
51346     // VPTERNLOG is only available as vXi32/64-bit types.
51347     MVT OpSVT = EltSizeInBits == 32 ? MVT::i32 : MVT::i64;
51348     MVT OpVT =
51349         MVT::getVectorVT(OpSVT, VT.getSizeInBits() / OpSVT.getSizeInBits());
51350     SDValue A = DAG.getBitcast(OpVT, N0.getOperand(1));
51351     SDValue B = DAG.getBitcast(OpVT, N0.getOperand(0));
51352     SDValue C = DAG.getBitcast(OpVT, N1.getOperand(0));
51353     SDValue Imm = DAG.getTargetConstant(0xCA, DL, MVT::i8);
51354     SDValue Res = getAVX512Node(X86ISD::VPTERNLOG, DL, OpVT, {A, B, C, Imm},
51355                                 DAG, Subtarget);
51356     return DAG.getBitcast(VT, Res);
51357   }
51358 
51359   SDValue X = N->getOperand(0);
51360   SDValue Y =
51361       DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
51362                   DAG.getBitcast(VT, N1.getOperand(0)));
51363   return DAG.getNode(ISD::OR, DL, VT, X, Y);
51364 }
51365 
51366 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
51367 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
51368   if (N->getOpcode() != ISD::OR)
51369     return false;
51370 
51371   SDValue N0 = N->getOperand(0);
51372   SDValue N1 = N->getOperand(1);
51373 
51374   // Canonicalize AND to LHS.
51375   if (N1.getOpcode() == ISD::AND)
51376     std::swap(N0, N1);
51377 
51378   // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
51379   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
51380     return false;
51381 
51382   Mask = N1.getOperand(0);
51383   X = N1.getOperand(1);
51384 
51385   // Check to see if the mask appeared in both the AND and ANDNP.
51386   if (N0.getOperand(0) == Mask)
51387     Y = N0.getOperand(1);
51388   else if (N0.getOperand(1) == Mask)
51389     Y = N0.getOperand(0);
51390   else
51391     return false;
51392 
51393   // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
51394   // ANDNP combine allows other combines to happen that prevent matching.
51395   return true;
51396 }
51397 
51398 // Try to fold:
51399 //   (or (and (m, y), (pandn m, x)))
51400 // into:
51401 //   (vselect m, x, y)
51402 // As a special case, try to fold:
51403 //   (or (and (m, (sub 0, x)), (pandn m, x)))
51404 // into:
51405 //   (sub (xor X, M), M)
51406 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
51407                                             const X86Subtarget &Subtarget) {
51408   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
51409 
51410   EVT VT = N->getValueType(0);
51411   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
51412         (VT.is256BitVector() && Subtarget.hasInt256())))
51413     return SDValue();
51414 
51415   SDValue X, Y, Mask;
51416   if (!matchLogicBlend(N, X, Y, Mask))
51417     return SDValue();
51418 
51419   // Validate that X, Y, and Mask are bitcasts, and see through them.
51420   Mask = peekThroughBitcasts(Mask);
51421   X = peekThroughBitcasts(X);
51422   Y = peekThroughBitcasts(Y);
51423 
51424   EVT MaskVT = Mask.getValueType();
51425   unsigned EltBits = MaskVT.getScalarSizeInBits();
51426 
51427   // TODO: Attempt to handle floating point cases as well?
51428   if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
51429     return SDValue();
51430 
51431   SDLoc DL(N);
51432 
51433   // Attempt to combine to conditional negate: (sub (xor X, M), M)
51434   if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
51435                                                            DAG, Subtarget))
51436     return Res;
51437 
51438   // PBLENDVB is only available on SSE 4.1.
51439   if (!Subtarget.hasSSE41())
51440     return SDValue();
51441 
51442   // If we have VPTERNLOG we should prefer that since PBLENDVB is multiple uops.
51443   if (Subtarget.hasVLX())
51444     return SDValue();
51445 
51446   MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
51447 
51448   X = DAG.getBitcast(BlendVT, X);
51449   Y = DAG.getBitcast(BlendVT, Y);
51450   Mask = DAG.getBitcast(BlendVT, Mask);
51451   Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
51452   return DAG.getBitcast(VT, Mask);
51453 }
51454 
51455 // Helper function for combineOrCmpEqZeroToCtlzSrl
51456 // Transforms:
51457 //   seteq(cmp x, 0)
51458 //   into:
51459 //   srl(ctlz x), log2(bitsize(x))
51460 // Input pattern is checked by caller.
51461 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) {
51462   SDValue Cmp = Op.getOperand(1);
51463   EVT VT = Cmp.getOperand(0).getValueType();
51464   unsigned Log2b = Log2_32(VT.getSizeInBits());
51465   SDLoc dl(Op);
51466   SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
51467   // The result of the shift is true or false, and on X86, the 32-bit
51468   // encoding of shr and lzcnt is more desirable.
51469   SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
51470   SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
51471                             DAG.getConstant(Log2b, dl, MVT::i8));
51472   return Scc;
51473 }
51474 
51475 // Try to transform:
51476 //   zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
51477 //   into:
51478 //   srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
51479 // Will also attempt to match more generic cases, eg:
51480 //   zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
51481 // Only applies if the target supports the FastLZCNT feature.
51482 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
51483                                            TargetLowering::DAGCombinerInfo &DCI,
51484                                            const X86Subtarget &Subtarget) {
51485   if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
51486     return SDValue();
51487 
51488   auto isORCandidate = [](SDValue N) {
51489     return (N->getOpcode() == ISD::OR && N->hasOneUse());
51490   };
51491 
51492   // Check the zero extend is extending to 32-bit or more. The code generated by
51493   // srl(ctlz) for 16-bit or less variants of the pattern would require extra
51494   // instructions to clear the upper bits.
51495   if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
51496       !isORCandidate(N->getOperand(0)))
51497     return SDValue();
51498 
51499   // Check the node matches: setcc(eq, cmp 0)
51500   auto isSetCCCandidate = [](SDValue N) {
51501     return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
51502            X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
51503            N->getOperand(1).getOpcode() == X86ISD::CMP &&
51504            isNullConstant(N->getOperand(1).getOperand(1)) &&
51505            N->getOperand(1).getValueType().bitsGE(MVT::i32);
51506   };
51507 
51508   SDNode *OR = N->getOperand(0).getNode();
51509   SDValue LHS = OR->getOperand(0);
51510   SDValue RHS = OR->getOperand(1);
51511 
51512   // Save nodes matching or(or, setcc(eq, cmp 0)).
51513   SmallVector<SDNode *, 2> ORNodes;
51514   while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
51515           (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
51516     ORNodes.push_back(OR);
51517     OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
51518     LHS = OR->getOperand(0);
51519     RHS = OR->getOperand(1);
51520   }
51521 
51522   // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
51523   if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
51524       !isORCandidate(SDValue(OR, 0)))
51525     return SDValue();
51526 
51527   // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
51528   // to
51529   // or(srl(ctlz),srl(ctlz)).
51530   // The dag combiner can then fold it into:
51531   // srl(or(ctlz, ctlz)).
51532   SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, DAG);
51533   SDValue Ret, NewRHS;
51534   if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, DAG)))
51535     Ret = DAG.getNode(ISD::OR, SDLoc(OR), MVT::i32, NewLHS, NewRHS);
51536 
51537   if (!Ret)
51538     return SDValue();
51539 
51540   // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
51541   while (!ORNodes.empty()) {
51542     OR = ORNodes.pop_back_val();
51543     LHS = OR->getOperand(0);
51544     RHS = OR->getOperand(1);
51545     // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
51546     if (RHS->getOpcode() == ISD::OR)
51547       std::swap(LHS, RHS);
51548     NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, DAG);
51549     if (!NewRHS)
51550       return SDValue();
51551     Ret = DAG.getNode(ISD::OR, SDLoc(OR), MVT::i32, Ret, NewRHS);
51552   }
51553 
51554   return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
51555 }
51556 
51557 static SDValue foldMaskedMergeImpl(SDValue And0_L, SDValue And0_R,
51558                                    SDValue And1_L, SDValue And1_R,
51559                                    const SDLoc &DL, SelectionDAG &DAG) {
51560   if (!isBitwiseNot(And0_L, true) || !And0_L->hasOneUse())
51561     return SDValue();
51562   SDValue NotOp = And0_L->getOperand(0);
51563   if (NotOp == And1_R)
51564     std::swap(And1_R, And1_L);
51565   if (NotOp != And1_L)
51566     return SDValue();
51567 
51568   // (~(NotOp) & And0_R) | (NotOp & And1_R)
51569   // --> ((And0_R ^ And1_R) & NotOp) ^ And1_R
51570   EVT VT = And1_L->getValueType(0);
51571   SDValue Freeze_And0_R = DAG.getNode(ISD::FREEZE, SDLoc(), VT, And0_R);
51572   SDValue Xor0 = DAG.getNode(ISD::XOR, DL, VT, And1_R, Freeze_And0_R);
51573   SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor0, NotOp);
51574   SDValue Xor1 = DAG.getNode(ISD::XOR, DL, VT, And, Freeze_And0_R);
51575   return Xor1;
51576 }
51577 
51578 /// Fold "masked merge" expressions like `(m & x) | (~m & y)` into the
51579 /// equivalent `((x ^ y) & m) ^ y)` pattern.
51580 /// This is typically a better representation for  targets without a fused
51581 /// "and-not" operation. This function is intended to be called from a
51582 /// `TargetLowering::PerformDAGCombine` callback on `ISD::OR` nodes.
51583 static SDValue foldMaskedMerge(SDNode *Node, SelectionDAG &DAG) {
51584   // Note that masked-merge variants using XOR or ADD expressions are
51585   // normalized to OR by InstCombine so we only check for OR.
51586   assert(Node->getOpcode() == ISD::OR && "Must be called with ISD::OR node");
51587   SDValue N0 = Node->getOperand(0);
51588   if (N0->getOpcode() != ISD::AND || !N0->hasOneUse())
51589     return SDValue();
51590   SDValue N1 = Node->getOperand(1);
51591   if (N1->getOpcode() != ISD::AND || !N1->hasOneUse())
51592     return SDValue();
51593 
51594   SDLoc DL(Node);
51595   SDValue N00 = N0->getOperand(0);
51596   SDValue N01 = N0->getOperand(1);
51597   SDValue N10 = N1->getOperand(0);
51598   SDValue N11 = N1->getOperand(1);
51599   if (SDValue Result = foldMaskedMergeImpl(N00, N01, N10, N11, DL, DAG))
51600     return Result;
51601   if (SDValue Result = foldMaskedMergeImpl(N01, N00, N10, N11, DL, DAG))
51602     return Result;
51603   if (SDValue Result = foldMaskedMergeImpl(N10, N11, N00, N01, DL, DAG))
51604     return Result;
51605   if (SDValue Result = foldMaskedMergeImpl(N11, N10, N00, N01, DL, DAG))
51606     return Result;
51607   return SDValue();
51608 }
51609 
51610 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
51611 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
51612 /// with CMP+{ADC, SBB}.
51613 /// Also try (ADD/SUB)+(AND(SRL,1)) bit extraction pattern with BT+{ADC, SBB}.
51614 static SDValue combineAddOrSubToADCOrSBB(bool IsSub, const SDLoc &DL, EVT VT,
51615                                          SDValue X, SDValue Y,
51616                                          SelectionDAG &DAG,
51617                                          bool ZeroSecondOpOnly = false) {
51618   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
51619     return SDValue();
51620 
51621   // Look through a one-use zext.
51622   if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse())
51623     Y = Y.getOperand(0);
51624 
51625   X86::CondCode CC;
51626   SDValue EFLAGS;
51627   if (Y.getOpcode() == X86ISD::SETCC && Y.hasOneUse()) {
51628     CC = (X86::CondCode)Y.getConstantOperandVal(0);
51629     EFLAGS = Y.getOperand(1);
51630   } else if (Y.getOpcode() == ISD::AND && isOneConstant(Y.getOperand(1)) &&
51631              Y.hasOneUse()) {
51632     EFLAGS = LowerAndToBT(Y, ISD::SETNE, DL, DAG, CC);
51633   }
51634 
51635   if (!EFLAGS)
51636     return SDValue();
51637 
51638   // If X is -1 or 0, then we have an opportunity to avoid constants required in
51639   // the general case below.
51640   auto *ConstantX = dyn_cast<ConstantSDNode>(X);
51641   if (ConstantX && !ZeroSecondOpOnly) {
51642     if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnes()) ||
51643         (IsSub && CC == X86::COND_B && ConstantX->isZero())) {
51644       // This is a complicated way to get -1 or 0 from the carry flag:
51645       // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
51646       //  0 - SETB  -->  0 -  (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
51647       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51648                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51649                          EFLAGS);
51650     }
51651 
51652     if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnes()) ||
51653         (IsSub && CC == X86::COND_A && ConstantX->isZero())) {
51654       if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
51655           EFLAGS.getValueType().isInteger() &&
51656           !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51657         // Swap the operands of a SUB, and we have the same pattern as above.
51658         // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
51659         //  0 - SETA  (SUB A, B) -->  0 - SETB  (SUB B, A) --> SUB + SBB
51660         SDValue NewSub = DAG.getNode(
51661             X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
51662             EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51663         SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
51664         return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51665                            DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51666                            NewEFLAGS);
51667       }
51668     }
51669   }
51670 
51671   if (CC == X86::COND_B) {
51672     // X + SETB Z --> adc X, 0
51673     // X - SETB Z --> sbb X, 0
51674     return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
51675                        DAG.getVTList(VT, MVT::i32), X,
51676                        DAG.getConstant(0, DL, VT), EFLAGS);
51677   }
51678 
51679   if (ZeroSecondOpOnly)
51680     return SDValue();
51681 
51682   if (CC == X86::COND_A) {
51683     // Try to convert COND_A into COND_B in an attempt to facilitate
51684     // materializing "setb reg".
51685     //
51686     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
51687     // cannot take an immediate as its first operand.
51688     //
51689     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
51690         EFLAGS.getValueType().isInteger() &&
51691         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51692       SDValue NewSub =
51693           DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
51694                       EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51695       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
51696       return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
51697                          DAG.getVTList(VT, MVT::i32), X,
51698                          DAG.getConstant(0, DL, VT), NewEFLAGS);
51699     }
51700   }
51701 
51702   if (CC == X86::COND_AE) {
51703     // X + SETAE --> sbb X, -1
51704     // X - SETAE --> adc X, -1
51705     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
51706                        DAG.getVTList(VT, MVT::i32), X,
51707                        DAG.getConstant(-1, DL, VT), EFLAGS);
51708   }
51709 
51710   if (CC == X86::COND_BE) {
51711     // X + SETBE --> sbb X, -1
51712     // X - SETBE --> adc X, -1
51713     // Try to convert COND_BE into COND_AE in an attempt to facilitate
51714     // materializing "setae reg".
51715     //
51716     // Do not flip "e <= c", where "c" is a constant, because Cmp instruction
51717     // cannot take an immediate as its first operand.
51718     //
51719     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
51720         EFLAGS.getValueType().isInteger() &&
51721         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51722       SDValue NewSub =
51723           DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
51724                       EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51725       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
51726       return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
51727                          DAG.getVTList(VT, MVT::i32), X,
51728                          DAG.getConstant(-1, DL, VT), NewEFLAGS);
51729     }
51730   }
51731 
51732   if (CC != X86::COND_E && CC != X86::COND_NE)
51733     return SDValue();
51734 
51735   if (EFLAGS.getOpcode() != X86ISD::CMP || !EFLAGS.hasOneUse() ||
51736       !X86::isZeroNode(EFLAGS.getOperand(1)) ||
51737       !EFLAGS.getOperand(0).getValueType().isInteger())
51738     return SDValue();
51739 
51740   SDValue Z = EFLAGS.getOperand(0);
51741   EVT ZVT = Z.getValueType();
51742 
51743   // If X is -1 or 0, then we have an opportunity to avoid constants required in
51744   // the general case below.
51745   if (ConstantX) {
51746     // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
51747     // fake operands:
51748     //  0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
51749     // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
51750     if ((IsSub && CC == X86::COND_NE && ConstantX->isZero()) ||
51751         (!IsSub && CC == X86::COND_E && ConstantX->isAllOnes())) {
51752       SDValue Zero = DAG.getConstant(0, DL, ZVT);
51753       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51754       SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
51755       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51756                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51757                          SDValue(Neg.getNode(), 1));
51758     }
51759 
51760     // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
51761     // with fake operands:
51762     //  0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
51763     // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
51764     if ((IsSub && CC == X86::COND_E && ConstantX->isZero()) ||
51765         (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnes())) {
51766       SDValue One = DAG.getConstant(1, DL, ZVT);
51767       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51768       SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
51769       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51770                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51771                          Cmp1.getValue(1));
51772     }
51773   }
51774 
51775   // (cmp Z, 1) sets the carry flag if Z is 0.
51776   SDValue One = DAG.getConstant(1, DL, ZVT);
51777   SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51778   SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
51779 
51780   // Add the flags type for ADC/SBB nodes.
51781   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
51782 
51783   // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
51784   // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
51785   if (CC == X86::COND_NE)
51786     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
51787                        DAG.getConstant(-1ULL, DL, VT), Cmp1.getValue(1));
51788 
51789   // X - (Z == 0) --> sub X, (zext(sete  Z, 0)) --> sbb X, 0, (cmp Z, 1)
51790   // X + (Z == 0) --> add X, (zext(sete  Z, 0)) --> adc X, 0, (cmp Z, 1)
51791   return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
51792                      DAG.getConstant(0, DL, VT), Cmp1.getValue(1));
51793 }
51794 
51795 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
51796 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
51797 /// with CMP+{ADC, SBB}.
51798 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
51799   bool IsSub = N->getOpcode() == ISD::SUB;
51800   SDValue X = N->getOperand(0);
51801   SDValue Y = N->getOperand(1);
51802   EVT VT = N->getValueType(0);
51803   SDLoc DL(N);
51804 
51805   if (SDValue ADCOrSBB = combineAddOrSubToADCOrSBB(IsSub, DL, VT, X, Y, DAG))
51806     return ADCOrSBB;
51807 
51808   // Commute and try again (negate the result for subtracts).
51809   if (SDValue ADCOrSBB = combineAddOrSubToADCOrSBB(IsSub, DL, VT, Y, X, DAG)) {
51810     if (IsSub)
51811       ADCOrSBB =
51812           DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), ADCOrSBB);
51813     return ADCOrSBB;
51814   }
51815 
51816   return SDValue();
51817 }
51818 
51819 static SDValue combineOrXorWithSETCC(SDNode *N, SDValue N0, SDValue N1,
51820                                      SelectionDAG &DAG) {
51821   assert((N->getOpcode() == ISD::XOR || N->getOpcode() == ISD::OR) &&
51822          "Unexpected opcode");
51823 
51824   // Delegate to combineAddOrSubToADCOrSBB if we have:
51825   //
51826   //   (xor/or (zero_extend (setcc)) imm)
51827   //
51828   // where imm is odd if and only if we have xor, in which case the XOR/OR are
51829   // equivalent to a SUB/ADD, respectively.
51830   if (N0.getOpcode() == ISD::ZERO_EXTEND &&
51831       N0.getOperand(0).getOpcode() == X86ISD::SETCC && N0.hasOneUse()) {
51832     if (auto *N1C = dyn_cast<ConstantSDNode>(N1)) {
51833       bool IsSub = N->getOpcode() == ISD::XOR;
51834       bool N1COdd = N1C->getZExtValue() & 1;
51835       if (IsSub ? N1COdd : !N1COdd) {
51836         SDLoc DL(N);
51837         EVT VT = N->getValueType(0);
51838         if (SDValue R = combineAddOrSubToADCOrSBB(IsSub, DL, VT, N1, N0, DAG))
51839           return R;
51840       }
51841     }
51842   }
51843 
51844   return SDValue();
51845 }
51846 
51847 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
51848                          TargetLowering::DAGCombinerInfo &DCI,
51849                          const X86Subtarget &Subtarget) {
51850   SDValue N0 = N->getOperand(0);
51851   SDValue N1 = N->getOperand(1);
51852   EVT VT = N->getValueType(0);
51853   SDLoc dl(N);
51854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51855 
51856   // If this is SSE1 only convert to FOR to avoid scalarization.
51857   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
51858     return DAG.getBitcast(MVT::v4i32,
51859                           DAG.getNode(X86ISD::FOR, dl, MVT::v4f32,
51860                                       DAG.getBitcast(MVT::v4f32, N0),
51861                                       DAG.getBitcast(MVT::v4f32, N1)));
51862   }
51863 
51864   // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
51865   // TODO: Support multiple SrcOps.
51866   if (VT == MVT::i1) {
51867     SmallVector<SDValue, 2> SrcOps;
51868     SmallVector<APInt, 2> SrcPartials;
51869     if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps, &SrcPartials) &&
51870         SrcOps.size() == 1) {
51871       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
51872       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
51873       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
51874       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
51875         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
51876       if (Mask) {
51877         assert(SrcPartials[0].getBitWidth() == NumElts &&
51878                "Unexpected partial reduction mask");
51879         SDValue ZeroBits = DAG.getConstant(0, dl, MaskVT);
51880         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
51881         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
51882         return DAG.getSetCC(dl, MVT::i1, Mask, ZeroBits, ISD::SETNE);
51883       }
51884     }
51885   }
51886 
51887   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
51888     return R;
51889 
51890   if (SDValue R = combineBitOpWithShift(N, DAG))
51891     return R;
51892 
51893   if (SDValue R = combineBitOpWithPACK(N, DAG))
51894     return R;
51895 
51896   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
51897     return FPLogic;
51898 
51899   if (DCI.isBeforeLegalizeOps())
51900     return SDValue();
51901 
51902   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
51903     return R;
51904 
51905   if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
51906     return R;
51907 
51908   if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
51909     return R;
51910 
51911   // (0 - SetCC) | C -> (zext (not SetCC)) * (C + 1) - 1 if we can get a LEA out of it.
51912   if ((VT == MVT::i32 || VT == MVT::i64) &&
51913       N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
51914       isNullConstant(N0.getOperand(0))) {
51915     SDValue Cond = N0.getOperand(1);
51916     if (Cond.getOpcode() == ISD::ZERO_EXTEND && Cond.hasOneUse())
51917       Cond = Cond.getOperand(0);
51918 
51919     if (Cond.getOpcode() == X86ISD::SETCC && Cond.hasOneUse()) {
51920       if (auto *CN = dyn_cast<ConstantSDNode>(N1)) {
51921         uint64_t Val = CN->getZExtValue();
51922         if (Val == 1 || Val == 2 || Val == 3 || Val == 4 || Val == 7 || Val == 8) {
51923           X86::CondCode CCode = (X86::CondCode)Cond.getConstantOperandVal(0);
51924           CCode = X86::GetOppositeBranchCondition(CCode);
51925           SDValue NotCond = getSETCC(CCode, Cond.getOperand(1), SDLoc(Cond), DAG);
51926 
51927           SDValue R = DAG.getZExtOrTrunc(NotCond, dl, VT);
51928           R = DAG.getNode(ISD::MUL, dl, VT, R, DAG.getConstant(Val + 1, dl, VT));
51929           R = DAG.getNode(ISD::SUB, dl, VT, R, DAG.getConstant(1, dl, VT));
51930           return R;
51931         }
51932       }
51933     }
51934   }
51935 
51936   // Combine OR(X,KSHIFTL(Y,Elts/2)) -> CONCAT_VECTORS(X,Y) == KUNPCK(X,Y).
51937   // Combine OR(KSHIFTL(X,Elts/2),Y) -> CONCAT_VECTORS(Y,X) == KUNPCK(Y,X).
51938   // iff the upper elements of the non-shifted arg are zero.
51939   // KUNPCK require 16+ bool vector elements.
51940   if (N0.getOpcode() == X86ISD::KSHIFTL || N1.getOpcode() == X86ISD::KSHIFTL) {
51941     unsigned NumElts = VT.getVectorNumElements();
51942     unsigned HalfElts = NumElts / 2;
51943     APInt UpperElts = APInt::getHighBitsSet(NumElts, HalfElts);
51944     if (NumElts >= 16 && N1.getOpcode() == X86ISD::KSHIFTL &&
51945         N1.getConstantOperandAPInt(1) == HalfElts &&
51946         DAG.MaskedVectorIsZero(N0, UpperElts)) {
51947       return DAG.getNode(
51948           ISD::CONCAT_VECTORS, dl, VT,
51949           extractSubVector(N0, 0, DAG, dl, HalfElts),
51950           extractSubVector(N1.getOperand(0), 0, DAG, dl, HalfElts));
51951     }
51952     if (NumElts >= 16 && N0.getOpcode() == X86ISD::KSHIFTL &&
51953         N0.getConstantOperandAPInt(1) == HalfElts &&
51954         DAG.MaskedVectorIsZero(N1, UpperElts)) {
51955       return DAG.getNode(
51956           ISD::CONCAT_VECTORS, dl, VT,
51957           extractSubVector(N1, 0, DAG, dl, HalfElts),
51958           extractSubVector(N0.getOperand(0), 0, DAG, dl, HalfElts));
51959     }
51960   }
51961 
51962   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
51963     // Attempt to recursively combine an OR of shuffles.
51964     SDValue Op(N, 0);
51965     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
51966       return Res;
51967 
51968     // If either operand is a constant mask, then only the elements that aren't
51969     // allones are actually demanded by the other operand.
51970     auto SimplifyUndemandedElts = [&](SDValue Op, SDValue OtherOp) {
51971       APInt UndefElts;
51972       SmallVector<APInt> EltBits;
51973       int NumElts = VT.getVectorNumElements();
51974       int EltSizeInBits = VT.getScalarSizeInBits();
51975       if (!getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts, EltBits))
51976         return false;
51977 
51978       APInt DemandedElts = APInt::getZero(NumElts);
51979       for (int I = 0; I != NumElts; ++I)
51980         if (!EltBits[I].isAllOnes())
51981           DemandedElts.setBit(I);
51982 
51983       return TLI.SimplifyDemandedVectorElts(OtherOp, DemandedElts, DCI);
51984     };
51985     if (SimplifyUndemandedElts(N0, N1) || SimplifyUndemandedElts(N1, N0)) {
51986       if (N->getOpcode() != ISD::DELETED_NODE)
51987         DCI.AddToWorklist(N);
51988       return SDValue(N, 0);
51989     }
51990   }
51991 
51992   // We should fold "masked merge" patterns when `andn` is not available.
51993   if (!Subtarget.hasBMI() && VT.isScalarInteger() && VT != MVT::i1)
51994     if (SDValue R = foldMaskedMerge(N, DAG))
51995       return R;
51996 
51997   if (SDValue R = combineOrXorWithSETCC(N, N0, N1, DAG))
51998     return R;
51999 
52000   return SDValue();
52001 }
52002 
52003 /// Try to turn tests against the signbit in the form of:
52004 ///   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
52005 /// into:
52006 ///   SETGT(X, -1)
52007 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
52008   // This is only worth doing if the output type is i8 or i1.
52009   EVT ResultType = N->getValueType(0);
52010   if (ResultType != MVT::i8 && ResultType != MVT::i1)
52011     return SDValue();
52012 
52013   SDValue N0 = N->getOperand(0);
52014   SDValue N1 = N->getOperand(1);
52015 
52016   // We should be performing an xor against a truncated shift.
52017   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
52018     return SDValue();
52019 
52020   // Make sure we are performing an xor against one.
52021   if (!isOneConstant(N1))
52022     return SDValue();
52023 
52024   // SetCC on x86 zero extends so only act on this if it's a logical shift.
52025   SDValue Shift = N0.getOperand(0);
52026   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
52027     return SDValue();
52028 
52029   // Make sure we are truncating from one of i16, i32 or i64.
52030   EVT ShiftTy = Shift.getValueType();
52031   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
52032     return SDValue();
52033 
52034   // Make sure the shift amount extracts the sign bit.
52035   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
52036       Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
52037     return SDValue();
52038 
52039   // Create a greater-than comparison against -1.
52040   // N.B. Using SETGE against 0 works but we want a canonical looking
52041   // comparison, using SETGT matches up with what TranslateX86CC.
52042   SDLoc DL(N);
52043   SDValue ShiftOp = Shift.getOperand(0);
52044   EVT ShiftOpTy = ShiftOp.getValueType();
52045   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52046   EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
52047                                                *DAG.getContext(), ResultType);
52048   SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
52049                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
52050   if (SetCCResultType != ResultType)
52051     Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
52052   return Cond;
52053 }
52054 
52055 /// Turn vector tests of the signbit in the form of:
52056 ///   xor (sra X, elt_size(X)-1), -1
52057 /// into:
52058 ///   pcmpgt X, -1
52059 ///
52060 /// This should be called before type legalization because the pattern may not
52061 /// persist after that.
52062 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
52063                                          const X86Subtarget &Subtarget) {
52064   EVT VT = N->getValueType(0);
52065   if (!VT.isSimple())
52066     return SDValue();
52067 
52068   switch (VT.getSimpleVT().SimpleTy) {
52069   default: return SDValue();
52070   case MVT::v16i8:
52071   case MVT::v8i16:
52072   case MVT::v4i32:
52073   case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
52074   case MVT::v32i8:
52075   case MVT::v16i16:
52076   case MVT::v8i32:
52077   case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
52078   }
52079 
52080   // There must be a shift right algebraic before the xor, and the xor must be a
52081   // 'not' operation.
52082   SDValue Shift = N->getOperand(0);
52083   SDValue Ones = N->getOperand(1);
52084   if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
52085       !ISD::isBuildVectorAllOnes(Ones.getNode()))
52086     return SDValue();
52087 
52088   // The shift should be smearing the sign bit across each vector element.
52089   auto *ShiftAmt =
52090       isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
52091   if (!ShiftAmt ||
52092       ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
52093     return SDValue();
52094 
52095   // Create a greater-than comparison against -1. We don't use the more obvious
52096   // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
52097   return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
52098 }
52099 
52100 /// Detect patterns of truncation with unsigned saturation:
52101 ///
52102 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
52103 ///   Return the source value x to be truncated or SDValue() if the pattern was
52104 ///   not matched.
52105 ///
52106 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
52107 ///   where C1 >= 0 and C2 is unsigned max of destination type.
52108 ///
52109 ///    (truncate (smax (smin (x, C2), C1)) to dest_type)
52110 ///   where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
52111 ///
52112 ///   These two patterns are equivalent to:
52113 ///   (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
52114 ///   So return the smax(x, C1) value to be truncated or SDValue() if the
52115 ///   pattern was not matched.
52116 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
52117                                  const SDLoc &DL) {
52118   EVT InVT = In.getValueType();
52119 
52120   // Saturation with truncation. We truncate from InVT to VT.
52121   assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
52122          "Unexpected types for truncate operation");
52123 
52124   // Match min/max and return limit value as a parameter.
52125   auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
52126     if (V.getOpcode() == Opcode &&
52127         ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
52128       return V.getOperand(0);
52129     return SDValue();
52130   };
52131 
52132   APInt C1, C2;
52133   if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
52134     // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
52135     // the element size of the destination type.
52136     if (C2.isMask(VT.getScalarSizeInBits()))
52137       return UMin;
52138 
52139   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
52140     if (MatchMinMax(SMin, ISD::SMAX, C1))
52141       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
52142         return SMin;
52143 
52144   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
52145     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
52146       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
52147           C2.uge(C1)) {
52148         return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
52149       }
52150 
52151   return SDValue();
52152 }
52153 
52154 /// Detect patterns of truncation with signed saturation:
52155 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
52156 ///                  signed_max_of_dest_type)) to dest_type)
52157 /// or:
52158 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
52159 ///                  signed_min_of_dest_type)) to dest_type).
52160 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
52161 /// Return the source value to be truncated or SDValue() if the pattern was not
52162 /// matched.
52163 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
52164   unsigned NumDstBits = VT.getScalarSizeInBits();
52165   unsigned NumSrcBits = In.getScalarValueSizeInBits();
52166   assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
52167 
52168   auto MatchMinMax = [](SDValue V, unsigned Opcode,
52169                         const APInt &Limit) -> SDValue {
52170     APInt C;
52171     if (V.getOpcode() == Opcode &&
52172         ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
52173       return V.getOperand(0);
52174     return SDValue();
52175   };
52176 
52177   APInt SignedMax, SignedMin;
52178   if (MatchPackUS) {
52179     SignedMax = APInt::getAllOnes(NumDstBits).zext(NumSrcBits);
52180     SignedMin = APInt(NumSrcBits, 0);
52181   } else {
52182     SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
52183     SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
52184   }
52185 
52186   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
52187     if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
52188       return SMax;
52189 
52190   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
52191     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
52192       return SMin;
52193 
52194   return SDValue();
52195 }
52196 
52197 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
52198                                       SelectionDAG &DAG,
52199                                       const X86Subtarget &Subtarget) {
52200   if (!Subtarget.hasSSE2() || !VT.isVector())
52201     return SDValue();
52202 
52203   EVT SVT = VT.getVectorElementType();
52204   EVT InVT = In.getValueType();
52205   EVT InSVT = InVT.getVectorElementType();
52206 
52207   // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
52208   // split across two registers. We can use a packusdw+perm to clamp to 0-65535
52209   // and concatenate at the same time. Then we can use a final vpmovuswb to
52210   // clip to 0-255.
52211   if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
52212       InVT == MVT::v16i32 && VT == MVT::v16i8) {
52213     if (SDValue USatVal = detectSSatPattern(In, VT, true)) {
52214       // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
52215       SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
52216                                            DL, DAG, Subtarget);
52217       assert(Mid && "Failed to pack!");
52218       return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
52219     }
52220   }
52221 
52222   // vXi32 truncate instructions are available with AVX512F.
52223   // vXi16 truncate instructions are only available with AVX512BW.
52224   // For 256-bit or smaller vectors, we require VLX.
52225   // FIXME: We could widen truncates to 512 to remove the VLX restriction.
52226   // If the result type is 256-bits or larger and we have disable 512-bit
52227   // registers, we should go ahead and use the pack instructions if possible.
52228   bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
52229                        (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
52230                       (InVT.getSizeInBits() > 128) &&
52231                       (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
52232                       !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
52233 
52234   if (isPowerOf2_32(VT.getVectorNumElements()) && !PreferAVX512 &&
52235       VT.getSizeInBits() >= 64 &&
52236       (SVT == MVT::i8 || SVT == MVT::i16) &&
52237       (InSVT == MVT::i16 || InSVT == MVT::i32)) {
52238     if (SDValue USatVal = detectSSatPattern(In, VT, true)) {
52239       // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
52240       // Only do this when the result is at least 64 bits or we'll leaving
52241       // dangling PACKSSDW nodes.
52242       if (SVT == MVT::i8 && InSVT == MVT::i32) {
52243         EVT MidVT = VT.changeVectorElementType(MVT::i16);
52244         SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
52245                                              DAG, Subtarget);
52246         assert(Mid && "Failed to pack!");
52247         SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
52248                                            Subtarget);
52249         assert(V && "Failed to pack!");
52250         return V;
52251       } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
52252         return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
52253                                       Subtarget);
52254     }
52255     if (SDValue SSatVal = detectSSatPattern(In, VT))
52256       return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
52257                                     Subtarget);
52258   }
52259 
52260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52261   if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
52262       Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI()) &&
52263       (SVT == MVT::i32 || SVT == MVT::i16 || SVT == MVT::i8)) {
52264     unsigned TruncOpc = 0;
52265     SDValue SatVal;
52266     if (SDValue SSatVal = detectSSatPattern(In, VT)) {
52267       SatVal = SSatVal;
52268       TruncOpc = X86ISD::VTRUNCS;
52269     } else if (SDValue USatVal = detectUSatPattern(In, VT, DAG, DL)) {
52270       SatVal = USatVal;
52271       TruncOpc = X86ISD::VTRUNCUS;
52272     }
52273     if (SatVal) {
52274       unsigned ResElts = VT.getVectorNumElements();
52275       // If the input type is less than 512 bits and we don't have VLX, we need
52276       // to widen to 512 bits.
52277       if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
52278         unsigned NumConcats = 512 / InVT.getSizeInBits();
52279         ResElts *= NumConcats;
52280         SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
52281         ConcatOps[0] = SatVal;
52282         InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
52283                                 NumConcats * InVT.getVectorNumElements());
52284         SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
52285       }
52286       // Widen the result if its narrower than 128 bits.
52287       if (ResElts * SVT.getSizeInBits() < 128)
52288         ResElts = 128 / SVT.getSizeInBits();
52289       EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
52290       SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
52291       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
52292                          DAG.getIntPtrConstant(0, DL));
52293     }
52294   }
52295 
52296   return SDValue();
52297 }
52298 
52299 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
52300 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
52301 /// ISD::AVGCEILU (AVG) instruction.
52302 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
52303                                 const X86Subtarget &Subtarget,
52304                                 const SDLoc &DL) {
52305   if (!VT.isVector())
52306     return SDValue();
52307   EVT InVT = In.getValueType();
52308   unsigned NumElems = VT.getVectorNumElements();
52309 
52310   EVT ScalarVT = VT.getVectorElementType();
52311   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) && NumElems >= 2))
52312     return SDValue();
52313 
52314   // InScalarVT is the intermediate type in AVG pattern and it should be greater
52315   // than the original input type (i8/i16).
52316   EVT InScalarVT = InVT.getVectorElementType();
52317   if (InScalarVT.getFixedSizeInBits() <= ScalarVT.getFixedSizeInBits())
52318     return SDValue();
52319 
52320   if (!Subtarget.hasSSE2())
52321     return SDValue();
52322 
52323   // Detect the following pattern:
52324   //
52325   //   %1 = zext <N x i8> %a to <N x i32>
52326   //   %2 = zext <N x i8> %b to <N x i32>
52327   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
52328   //   %4 = add nuw nsw <N x i32> %3, %2
52329   //   %5 = lshr <N x i32> %N, <i32 1 x N>
52330   //   %6 = trunc <N x i32> %5 to <N x i8>
52331   //
52332   // In AVX512, the last instruction can also be a trunc store.
52333   if (In.getOpcode() != ISD::SRL)
52334     return SDValue();
52335 
52336   // A lambda checking the given SDValue is a constant vector and each element
52337   // is in the range [Min, Max].
52338   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
52339     return ISD::matchUnaryPredicate(V, [Min, Max](ConstantSDNode *C) {
52340       return !(C->getAPIntValue().ult(Min) || C->getAPIntValue().ugt(Max));
52341     });
52342   };
52343 
52344   auto IsZExtLike = [DAG = &DAG, ScalarVT](SDValue V) {
52345     unsigned MaxActiveBits = DAG->computeKnownBits(V).countMaxActiveBits();
52346     return MaxActiveBits <= ScalarVT.getSizeInBits();
52347   };
52348 
52349   // Check if each element of the vector is right-shifted by one.
52350   SDValue LHS = In.getOperand(0);
52351   SDValue RHS = In.getOperand(1);
52352   if (!IsConstVectorInRange(RHS, 1, 1))
52353     return SDValue();
52354   if (LHS.getOpcode() != ISD::ADD)
52355     return SDValue();
52356 
52357   // Detect a pattern of a + b + 1 where the order doesn't matter.
52358   SDValue Operands[3];
52359   Operands[0] = LHS.getOperand(0);
52360   Operands[1] = LHS.getOperand(1);
52361 
52362   auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
52363                        ArrayRef<SDValue> Ops) {
52364     return DAG.getNode(ISD::AVGCEILU, DL, Ops[0].getValueType(), Ops);
52365   };
52366 
52367   auto AVGSplitter = [&](std::array<SDValue, 2> Ops) {
52368     for (SDValue &Op : Ops)
52369       if (Op.getValueType() != VT)
52370         Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
52371     // Pad to a power-of-2 vector, split+apply and extract the original vector.
52372     unsigned NumElemsPow2 = PowerOf2Ceil(NumElems);
52373     EVT Pow2VT = EVT::getVectorVT(*DAG.getContext(), ScalarVT, NumElemsPow2);
52374     if (NumElemsPow2 != NumElems) {
52375       for (SDValue &Op : Ops) {
52376         SmallVector<SDValue, 32> EltsOfOp(NumElemsPow2, DAG.getUNDEF(ScalarVT));
52377         for (unsigned i = 0; i != NumElems; ++i) {
52378           SDValue Idx = DAG.getIntPtrConstant(i, DL);
52379           EltsOfOp[i] =
52380               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Op, Idx);
52381         }
52382         Op = DAG.getBuildVector(Pow2VT, DL, EltsOfOp);
52383       }
52384     }
52385     SDValue Res = SplitOpsAndApply(DAG, Subtarget, DL, Pow2VT, Ops, AVGBuilder);
52386     if (NumElemsPow2 == NumElems)
52387       return Res;
52388     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
52389                        DAG.getIntPtrConstant(0, DL));
52390   };
52391 
52392   // Take care of the case when one of the operands is a constant vector whose
52393   // element is in the range [1, 256].
52394   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
52395       IsZExtLike(Operands[0])) {
52396     // The pattern is detected. Subtract one from the constant vector, then
52397     // demote it and emit X86ISD::AVG instruction.
52398     SDValue VecOnes = DAG.getConstant(1, DL, InVT);
52399     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
52400     return AVGSplitter({Operands[0], Operands[1]});
52401   }
52402 
52403   // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
52404   // Match the or case only if its 'add-like' - can be replaced by an add.
52405   auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
52406     if (ISD::ADD == V.getOpcode()) {
52407       Op0 = V.getOperand(0);
52408       Op1 = V.getOperand(1);
52409       return true;
52410     }
52411     if (ISD::ZERO_EXTEND != V.getOpcode())
52412       return false;
52413     V = V.getOperand(0);
52414     if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
52415         !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
52416       return false;
52417     Op0 = V.getOperand(0);
52418     Op1 = V.getOperand(1);
52419     return true;
52420   };
52421 
52422   SDValue Op0, Op1;
52423   if (FindAddLike(Operands[0], Op0, Op1))
52424     std::swap(Operands[0], Operands[1]);
52425   else if (!FindAddLike(Operands[1], Op0, Op1))
52426     return SDValue();
52427   Operands[2] = Op0;
52428   Operands[1] = Op1;
52429 
52430   // Now we have three operands of two additions. Check that one of them is a
52431   // constant vector with ones, and the other two can be promoted from i8/i16.
52432   for (SDValue &Op : Operands) {
52433     if (!IsConstVectorInRange(Op, 1, 1))
52434       continue;
52435     std::swap(Op, Operands[2]);
52436 
52437     // Check if Operands[0] and Operands[1] are results of type promotion.
52438     for (int j = 0; j < 2; ++j)
52439       if (Operands[j].getValueType() != VT)
52440         if (!IsZExtLike(Operands[j]))
52441           return SDValue();
52442 
52443     // The pattern is detected, emit X86ISD::AVG instruction(s).
52444     return AVGSplitter({Operands[0], Operands[1]});
52445   }
52446 
52447   return SDValue();
52448 }
52449 
52450 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
52451                            TargetLowering::DAGCombinerInfo &DCI,
52452                            const X86Subtarget &Subtarget) {
52453   LoadSDNode *Ld = cast<LoadSDNode>(N);
52454   EVT RegVT = Ld->getValueType(0);
52455   EVT MemVT = Ld->getMemoryVT();
52456   SDLoc dl(Ld);
52457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52458 
52459   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
52460   // into two 16-byte operations. Also split non-temporal aligned loads on
52461   // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
52462   ISD::LoadExtType Ext = Ld->getExtensionType();
52463   unsigned Fast;
52464   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
52465       Ext == ISD::NON_EXTLOAD &&
52466       ((Ld->isNonTemporal() && !Subtarget.hasInt256() &&
52467         Ld->getAlign() >= Align(16)) ||
52468        (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
52469                                *Ld->getMemOperand(), &Fast) &&
52470         !Fast))) {
52471     unsigned NumElems = RegVT.getVectorNumElements();
52472     if (NumElems < 2)
52473       return SDValue();
52474 
52475     unsigned HalfOffset = 16;
52476     SDValue Ptr1 = Ld->getBasePtr();
52477     SDValue Ptr2 =
52478         DAG.getMemBasePlusOffset(Ptr1, TypeSize::Fixed(HalfOffset), dl);
52479     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
52480                                   NumElems / 2);
52481     SDValue Load1 =
52482         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
52483                     Ld->getOriginalAlign(),
52484                     Ld->getMemOperand()->getFlags());
52485     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
52486                                 Ld->getPointerInfo().getWithOffset(HalfOffset),
52487                                 Ld->getOriginalAlign(),
52488                                 Ld->getMemOperand()->getFlags());
52489     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
52490                              Load1.getValue(1), Load2.getValue(1));
52491 
52492     SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
52493     return DCI.CombineTo(N, NewVec, TF, true);
52494   }
52495 
52496   // Bool vector load - attempt to cast to an integer, as we have good
52497   // (vXiY *ext(vXi1 bitcast(iX))) handling.
52498   if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
52499       RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
52500     unsigned NumElts = RegVT.getVectorNumElements();
52501     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
52502     if (TLI.isTypeLegal(IntVT)) {
52503       SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
52504                                     Ld->getPointerInfo(),
52505                                     Ld->getOriginalAlign(),
52506                                     Ld->getMemOperand()->getFlags());
52507       SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
52508       return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
52509     }
52510   }
52511 
52512   // If we also broadcast this as a subvector to a wider type, then just extract
52513   // the lowest subvector.
52514   if (Ext == ISD::NON_EXTLOAD && Subtarget.hasAVX() && Ld->isSimple() &&
52515       (RegVT.is128BitVector() || RegVT.is256BitVector())) {
52516     SDValue Ptr = Ld->getBasePtr();
52517     SDValue Chain = Ld->getChain();
52518     for (SDNode *User : Ptr->uses()) {
52519       if (User != N && User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
52520           cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
52521           cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
52522           cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
52523               MemVT.getSizeInBits() &&
52524           !User->hasAnyUseOfValue(1) &&
52525           User->getValueSizeInBits(0).getFixedValue() >
52526               RegVT.getFixedSizeInBits()) {
52527         SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
52528                                            RegVT.getSizeInBits());
52529         Extract = DAG.getBitcast(RegVT, Extract);
52530         return DCI.CombineTo(N, Extract, SDValue(User, 1));
52531       }
52532     }
52533   }
52534 
52535   // Cast ptr32 and ptr64 pointers to the default address space before a load.
52536   unsigned AddrSpace = Ld->getAddressSpace();
52537   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
52538       AddrSpace == X86AS::PTR32_UPTR) {
52539     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
52540     if (PtrVT != Ld->getBasePtr().getSimpleValueType()) {
52541       SDValue Cast =
52542           DAG.getAddrSpaceCast(dl, PtrVT, Ld->getBasePtr(), AddrSpace, 0);
52543       return DAG.getLoad(RegVT, dl, Ld->getChain(), Cast, Ld->getPointerInfo(),
52544                          Ld->getOriginalAlign(),
52545                          Ld->getMemOperand()->getFlags());
52546     }
52547   }
52548 
52549   return SDValue();
52550 }
52551 
52552 /// If V is a build vector of boolean constants and exactly one of those
52553 /// constants is true, return the operand index of that true element.
52554 /// Otherwise, return -1.
52555 static int getOneTrueElt(SDValue V) {
52556   // This needs to be a build vector of booleans.
52557   // TODO: Checking for the i1 type matches the IR definition for the mask,
52558   // but the mask check could be loosened to i8 or other types. That might
52559   // also require checking more than 'allOnesValue'; eg, the x86 HW
52560   // instructions only require that the MSB is set for each mask element.
52561   // The ISD::MSTORE comments/definition do not specify how the mask operand
52562   // is formatted.
52563   auto *BV = dyn_cast<BuildVectorSDNode>(V);
52564   if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
52565     return -1;
52566 
52567   int TrueIndex = -1;
52568   unsigned NumElts = BV->getValueType(0).getVectorNumElements();
52569   for (unsigned i = 0; i < NumElts; ++i) {
52570     const SDValue &Op = BV->getOperand(i);
52571     if (Op.isUndef())
52572       continue;
52573     auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
52574     if (!ConstNode)
52575       return -1;
52576     if (ConstNode->getAPIntValue().countr_one() >= 1) {
52577       // If we already found a one, this is too many.
52578       if (TrueIndex >= 0)
52579         return -1;
52580       TrueIndex = i;
52581     }
52582   }
52583   return TrueIndex;
52584 }
52585 
52586 /// Given a masked memory load/store operation, return true if it has one mask
52587 /// bit set. If it has one mask bit set, then also return the memory address of
52588 /// the scalar element to load/store, the vector index to insert/extract that
52589 /// scalar element, and the alignment for the scalar memory access.
52590 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
52591                                          SelectionDAG &DAG, SDValue &Addr,
52592                                          SDValue &Index, Align &Alignment,
52593                                          unsigned &Offset) {
52594   int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
52595   if (TrueMaskElt < 0)
52596     return false;
52597 
52598   // Get the address of the one scalar element that is specified by the mask
52599   // using the appropriate offset from the base pointer.
52600   EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
52601   Offset = 0;
52602   Addr = MaskedOp->getBasePtr();
52603   if (TrueMaskElt != 0) {
52604     Offset = TrueMaskElt * EltVT.getStoreSize();
52605     Addr = DAG.getMemBasePlusOffset(Addr, TypeSize::Fixed(Offset),
52606                                     SDLoc(MaskedOp));
52607   }
52608 
52609   Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
52610   Alignment = commonAlignment(MaskedOp->getOriginalAlign(),
52611                               EltVT.getStoreSize());
52612   return true;
52613 }
52614 
52615 /// If exactly one element of the mask is set for a non-extending masked load,
52616 /// it is a scalar load and vector insert.
52617 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
52618 /// mask have already been optimized in IR, so we don't bother with those here.
52619 static SDValue
52620 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
52621                              TargetLowering::DAGCombinerInfo &DCI,
52622                              const X86Subtarget &Subtarget) {
52623   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
52624   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
52625   // However, some target hooks may need to be added to know when the transform
52626   // is profitable. Endianness would also have to be considered.
52627 
52628   SDValue Addr, VecIndex;
52629   Align Alignment;
52630   unsigned Offset;
52631   if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment, Offset))
52632     return SDValue();
52633 
52634   // Load the one scalar element that is specified by the mask using the
52635   // appropriate offset from the base pointer.
52636   SDLoc DL(ML);
52637   EVT VT = ML->getValueType(0);
52638   EVT EltVT = VT.getVectorElementType();
52639 
52640   EVT CastVT = VT;
52641   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
52642     EltVT = MVT::f64;
52643     CastVT = VT.changeVectorElementType(EltVT);
52644   }
52645 
52646   SDValue Load =
52647       DAG.getLoad(EltVT, DL, ML->getChain(), Addr,
52648                   ML->getPointerInfo().getWithOffset(Offset),
52649                   Alignment, ML->getMemOperand()->getFlags());
52650 
52651   SDValue PassThru = DAG.getBitcast(CastVT, ML->getPassThru());
52652 
52653   // Insert the loaded element into the appropriate place in the vector.
52654   SDValue Insert =
52655       DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, CastVT, PassThru, Load, VecIndex);
52656   Insert = DAG.getBitcast(VT, Insert);
52657   return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
52658 }
52659 
52660 static SDValue
52661 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
52662                               TargetLowering::DAGCombinerInfo &DCI) {
52663   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
52664   if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
52665     return SDValue();
52666 
52667   SDLoc DL(ML);
52668   EVT VT = ML->getValueType(0);
52669 
52670   // If we are loading the first and last elements of a vector, it is safe and
52671   // always faster to load the whole vector. Replace the masked load with a
52672   // vector load and select.
52673   unsigned NumElts = VT.getVectorNumElements();
52674   BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
52675   bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
52676   bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
52677   if (LoadFirstElt && LoadLastElt) {
52678     SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
52679                                 ML->getMemOperand());
52680     SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
52681                                   ML->getPassThru());
52682     return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
52683   }
52684 
52685   // Convert a masked load with a constant mask into a masked load and a select.
52686   // This allows the select operation to use a faster kind of select instruction
52687   // (for example, vblendvps -> vblendps).
52688 
52689   // Don't try this if the pass-through operand is already undefined. That would
52690   // cause an infinite loop because that's what we're about to create.
52691   if (ML->getPassThru().isUndef())
52692     return SDValue();
52693 
52694   if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
52695     return SDValue();
52696 
52697   // The new masked load has an undef pass-through operand. The select uses the
52698   // original pass-through operand.
52699   SDValue NewML = DAG.getMaskedLoad(
52700       VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
52701       DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
52702       ML->getAddressingMode(), ML->getExtensionType());
52703   SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
52704                                 ML->getPassThru());
52705 
52706   return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
52707 }
52708 
52709 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
52710                                  TargetLowering::DAGCombinerInfo &DCI,
52711                                  const X86Subtarget &Subtarget) {
52712   auto *Mld = cast<MaskedLoadSDNode>(N);
52713 
52714   // TODO: Expanding load with constant mask may be optimized as well.
52715   if (Mld->isExpandingLoad())
52716     return SDValue();
52717 
52718   if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
52719     if (SDValue ScalarLoad =
52720             reduceMaskedLoadToScalarLoad(Mld, DAG, DCI, Subtarget))
52721       return ScalarLoad;
52722 
52723     // TODO: Do some AVX512 subsets benefit from this transform?
52724     if (!Subtarget.hasAVX512())
52725       if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
52726         return Blend;
52727   }
52728 
52729   // If the mask value has been legalized to a non-boolean vector, try to
52730   // simplify ops leading up to it. We only demand the MSB of each lane.
52731   SDValue Mask = Mld->getMask();
52732   if (Mask.getScalarValueSizeInBits() != 1) {
52733     EVT VT = Mld->getValueType(0);
52734     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52735     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
52736     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
52737       if (N->getOpcode() != ISD::DELETED_NODE)
52738         DCI.AddToWorklist(N);
52739       return SDValue(N, 0);
52740     }
52741     if (SDValue NewMask =
52742             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
52743       return DAG.getMaskedLoad(
52744           VT, SDLoc(N), Mld->getChain(), Mld->getBasePtr(), Mld->getOffset(),
52745           NewMask, Mld->getPassThru(), Mld->getMemoryVT(), Mld->getMemOperand(),
52746           Mld->getAddressingMode(), Mld->getExtensionType());
52747   }
52748 
52749   return SDValue();
52750 }
52751 
52752 /// If exactly one element of the mask is set for a non-truncating masked store,
52753 /// it is a vector extract and scalar store.
52754 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
52755 /// mask have already been optimized in IR, so we don't bother with those here.
52756 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
52757                                               SelectionDAG &DAG,
52758                                               const X86Subtarget &Subtarget) {
52759   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
52760   // However, some target hooks may need to be added to know when the transform
52761   // is profitable. Endianness would also have to be considered.
52762 
52763   SDValue Addr, VecIndex;
52764   Align Alignment;
52765   unsigned Offset;
52766   if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment, Offset))
52767     return SDValue();
52768 
52769   // Extract the one scalar element that is actually being stored.
52770   SDLoc DL(MS);
52771   SDValue Value = MS->getValue();
52772   EVT VT = Value.getValueType();
52773   EVT EltVT = VT.getVectorElementType();
52774   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
52775     EltVT = MVT::f64;
52776     EVT CastVT = VT.changeVectorElementType(EltVT);
52777     Value = DAG.getBitcast(CastVT, Value);
52778   }
52779   SDValue Extract =
52780       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Value, VecIndex);
52781 
52782   // Store that element at the appropriate offset from the base pointer.
52783   return DAG.getStore(MS->getChain(), DL, Extract, Addr,
52784                       MS->getPointerInfo().getWithOffset(Offset),
52785                       Alignment, MS->getMemOperand()->getFlags());
52786 }
52787 
52788 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
52789                                   TargetLowering::DAGCombinerInfo &DCI,
52790                                   const X86Subtarget &Subtarget) {
52791   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
52792   if (Mst->isCompressingStore())
52793     return SDValue();
52794 
52795   EVT VT = Mst->getValue().getValueType();
52796   SDLoc dl(Mst);
52797   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52798 
52799   if (Mst->isTruncatingStore())
52800     return SDValue();
52801 
52802   if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG, Subtarget))
52803     return ScalarStore;
52804 
52805   // If the mask value has been legalized to a non-boolean vector, try to
52806   // simplify ops leading up to it. We only demand the MSB of each lane.
52807   SDValue Mask = Mst->getMask();
52808   if (Mask.getScalarValueSizeInBits() != 1) {
52809     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
52810     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
52811       if (N->getOpcode() != ISD::DELETED_NODE)
52812         DCI.AddToWorklist(N);
52813       return SDValue(N, 0);
52814     }
52815     if (SDValue NewMask =
52816             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
52817       return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Mst->getValue(),
52818                                 Mst->getBasePtr(), Mst->getOffset(), NewMask,
52819                                 Mst->getMemoryVT(), Mst->getMemOperand(),
52820                                 Mst->getAddressingMode());
52821   }
52822 
52823   SDValue Value = Mst->getValue();
52824   if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
52825       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
52826                             Mst->getMemoryVT())) {
52827     return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
52828                               Mst->getBasePtr(), Mst->getOffset(), Mask,
52829                               Mst->getMemoryVT(), Mst->getMemOperand(),
52830                               Mst->getAddressingMode(), true);
52831   }
52832 
52833   return SDValue();
52834 }
52835 
52836 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
52837                             TargetLowering::DAGCombinerInfo &DCI,
52838                             const X86Subtarget &Subtarget) {
52839   StoreSDNode *St = cast<StoreSDNode>(N);
52840   EVT StVT = St->getMemoryVT();
52841   SDLoc dl(St);
52842   SDValue StoredVal = St->getValue();
52843   EVT VT = StoredVal.getValueType();
52844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52845 
52846   // Convert a store of vXi1 into a store of iX and a bitcast.
52847   if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
52848       VT.getVectorElementType() == MVT::i1) {
52849 
52850     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
52851     StoredVal = DAG.getBitcast(NewVT, StoredVal);
52852 
52853     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
52854                         St->getPointerInfo(), St->getOriginalAlign(),
52855                         St->getMemOperand()->getFlags());
52856   }
52857 
52858   // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
52859   // This will avoid a copy to k-register.
52860   if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
52861       StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
52862       StoredVal.getOperand(0).getValueType() == MVT::i8) {
52863     SDValue Val = StoredVal.getOperand(0);
52864     // We must store zeros to the unused bits.
52865     Val = DAG.getZeroExtendInReg(Val, dl, MVT::i1);
52866     return DAG.getStore(St->getChain(), dl, Val,
52867                         St->getBasePtr(), St->getPointerInfo(),
52868                         St->getOriginalAlign(),
52869                         St->getMemOperand()->getFlags());
52870   }
52871 
52872   // Widen v2i1/v4i1 stores to v8i1.
52873   if ((VT == MVT::v1i1 || VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
52874       Subtarget.hasAVX512()) {
52875     unsigned NumConcats = 8 / VT.getVectorNumElements();
52876     // We must store zeros to the unused bits.
52877     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, VT));
52878     Ops[0] = StoredVal;
52879     StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
52880     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
52881                         St->getPointerInfo(), St->getOriginalAlign(),
52882                         St->getMemOperand()->getFlags());
52883   }
52884 
52885   // Turn vXi1 stores of constants into a scalar store.
52886   if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
52887        VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
52888       ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
52889     // If its a v64i1 store without 64-bit support, we need two stores.
52890     if (!DCI.isBeforeLegalize() && VT == MVT::v64i1 && !Subtarget.is64Bit()) {
52891       SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
52892                                       StoredVal->ops().slice(0, 32));
52893       Lo = combinevXi1ConstantToInteger(Lo, DAG);
52894       SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
52895                                       StoredVal->ops().slice(32, 32));
52896       Hi = combinevXi1ConstantToInteger(Hi, DAG);
52897 
52898       SDValue Ptr0 = St->getBasePtr();
52899       SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(4), dl);
52900 
52901       SDValue Ch0 =
52902           DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
52903                        St->getOriginalAlign(),
52904                        St->getMemOperand()->getFlags());
52905       SDValue Ch1 =
52906           DAG.getStore(St->getChain(), dl, Hi, Ptr1,
52907                        St->getPointerInfo().getWithOffset(4),
52908                        St->getOriginalAlign(),
52909                        St->getMemOperand()->getFlags());
52910       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
52911     }
52912 
52913     StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
52914     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
52915                         St->getPointerInfo(), St->getOriginalAlign(),
52916                         St->getMemOperand()->getFlags());
52917   }
52918 
52919   // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
52920   // Sandy Bridge, perform two 16-byte stores.
52921   unsigned Fast;
52922   if (VT.is256BitVector() && StVT == VT &&
52923       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
52924                              *St->getMemOperand(), &Fast) &&
52925       !Fast) {
52926     unsigned NumElems = VT.getVectorNumElements();
52927     if (NumElems < 2)
52928       return SDValue();
52929 
52930     return splitVectorStore(St, DAG);
52931   }
52932 
52933   // Split under-aligned vector non-temporal stores.
52934   if (St->isNonTemporal() && StVT == VT &&
52935       St->getAlign().value() < VT.getStoreSize()) {
52936     // ZMM/YMM nt-stores - either it can be stored as a series of shorter
52937     // vectors or the legalizer can scalarize it to use MOVNTI.
52938     if (VT.is256BitVector() || VT.is512BitVector()) {
52939       unsigned NumElems = VT.getVectorNumElements();
52940       if (NumElems < 2)
52941         return SDValue();
52942       return splitVectorStore(St, DAG);
52943     }
52944 
52945     // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
52946     // to use MOVNTI.
52947     if (VT.is128BitVector() && Subtarget.hasSSE2()) {
52948       MVT NTVT = Subtarget.hasSSE4A()
52949                      ? MVT::v2f64
52950                      : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
52951       return scalarizeVectorStore(St, NTVT, DAG);
52952     }
52953   }
52954 
52955   // Try to optimize v16i16->v16i8 truncating stores when BWI is not
52956   // supported, but avx512f is by extending to v16i32 and truncating.
52957   if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
52958       St->getValue().getOpcode() == ISD::TRUNCATE &&
52959       St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
52960       TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
52961       St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
52962     SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32,
52963                               St->getValue().getOperand(0));
52964     return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
52965                              MVT::v16i8, St->getMemOperand());
52966   }
52967 
52968   // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
52969   if (!St->isTruncatingStore() &&
52970       (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
52971        StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
52972       StoredVal.hasOneUse() &&
52973       TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
52974     bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
52975     return EmitTruncSStore(IsSigned, St->getChain(),
52976                            dl, StoredVal.getOperand(0), St->getBasePtr(),
52977                            VT, St->getMemOperand(), DAG);
52978   }
52979 
52980   // Try to fold a extract_element(VTRUNC) pattern into a truncating store.
52981   if (!St->isTruncatingStore()) {
52982     auto IsExtractedElement = [](SDValue V) {
52983       if (V.getOpcode() == ISD::TRUNCATE && V.hasOneUse())
52984         V = V.getOperand(0);
52985       unsigned Opc = V.getOpcode();
52986       if ((Opc == ISD::EXTRACT_VECTOR_ELT || Opc == X86ISD::PEXTRW) &&
52987           isNullConstant(V.getOperand(1)) && V.hasOneUse() &&
52988           V.getOperand(0).hasOneUse())
52989         return V.getOperand(0);
52990       return SDValue();
52991     };
52992     if (SDValue Extract = IsExtractedElement(StoredVal)) {
52993       SDValue Trunc = peekThroughOneUseBitcasts(Extract);
52994       if (Trunc.getOpcode() == X86ISD::VTRUNC) {
52995         SDValue Src = Trunc.getOperand(0);
52996         MVT DstVT = Trunc.getSimpleValueType();
52997         MVT SrcVT = Src.getSimpleValueType();
52998         unsigned NumSrcElts = SrcVT.getVectorNumElements();
52999         unsigned NumTruncBits = DstVT.getScalarSizeInBits() * NumSrcElts;
53000         MVT TruncVT = MVT::getVectorVT(DstVT.getScalarType(), NumSrcElts);
53001         if (NumTruncBits == VT.getSizeInBits() &&
53002             TLI.isTruncStoreLegal(SrcVT, TruncVT)) {
53003           return DAG.getTruncStore(St->getChain(), dl, Src, St->getBasePtr(),
53004                                    TruncVT, St->getMemOperand());
53005         }
53006       }
53007     }
53008   }
53009 
53010   // Optimize trunc store (of multiple scalars) to shuffle and store.
53011   // First, pack all of the elements in one place. Next, store to memory
53012   // in fewer chunks.
53013   if (St->isTruncatingStore() && VT.isVector()) {
53014     // Check if we can detect an AVG pattern from the truncation. If yes,
53015     // replace the trunc store by a normal store with the result of X86ISD::AVG
53016     // instruction.
53017     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(St->getMemoryVT()))
53018       if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
53019                                          Subtarget, dl))
53020         return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
53021                             St->getPointerInfo(), St->getOriginalAlign(),
53022                             St->getMemOperand()->getFlags());
53023 
53024     if (TLI.isTruncStoreLegal(VT, StVT)) {
53025       if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
53026         return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
53027                                dl, Val, St->getBasePtr(),
53028                                St->getMemoryVT(), St->getMemOperand(), DAG);
53029       if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
53030                                           DAG, dl))
53031         return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
53032                                dl, Val, St->getBasePtr(),
53033                                St->getMemoryVT(), St->getMemOperand(), DAG);
53034     }
53035 
53036     return SDValue();
53037   }
53038 
53039   // Cast ptr32 and ptr64 pointers to the default address space before a store.
53040   unsigned AddrSpace = St->getAddressSpace();
53041   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
53042       AddrSpace == X86AS::PTR32_UPTR) {
53043     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
53044     if (PtrVT != St->getBasePtr().getSimpleValueType()) {
53045       SDValue Cast =
53046           DAG.getAddrSpaceCast(dl, PtrVT, St->getBasePtr(), AddrSpace, 0);
53047       return DAG.getStore(St->getChain(), dl, StoredVal, Cast,
53048                           St->getPointerInfo(), St->getOriginalAlign(),
53049                           St->getMemOperand()->getFlags(), St->getAAInfo());
53050     }
53051   }
53052 
53053   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
53054   // the FP state in cases where an emms may be missing.
53055   // A preferable solution to the general problem is to figure out the right
53056   // places to insert EMMS.  This qualifies as a quick hack.
53057 
53058   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
53059   if (VT.getSizeInBits() != 64)
53060     return SDValue();
53061 
53062   const Function &F = DAG.getMachineFunction().getFunction();
53063   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
53064   bool F64IsLegal =
53065       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
53066   if ((VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit()) &&
53067       isa<LoadSDNode>(St->getValue()) &&
53068       cast<LoadSDNode>(St->getValue())->isSimple() &&
53069       St->getChain().hasOneUse() && St->isSimple()) {
53070     LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
53071 
53072     if (!ISD::isNormalLoad(Ld))
53073       return SDValue();
53074 
53075     // Avoid the transformation if there are multiple uses of the loaded value.
53076     if (!Ld->hasNUsesOfValue(1, 0))
53077       return SDValue();
53078 
53079     SDLoc LdDL(Ld);
53080     SDLoc StDL(N);
53081     // Lower to a single movq load/store pair.
53082     SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
53083                                 Ld->getBasePtr(), Ld->getMemOperand());
53084 
53085     // Make sure new load is placed in same chain order.
53086     DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
53087     return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
53088                         St->getMemOperand());
53089   }
53090 
53091   // This is similar to the above case, but here we handle a scalar 64-bit
53092   // integer store that is extracted from a vector on a 32-bit target.
53093   // If we have SSE2, then we can treat it like a floating-point double
53094   // to get past legalization. The execution dependencies fixup pass will
53095   // choose the optimal machine instruction for the store if this really is
53096   // an integer or v2f32 rather than an f64.
53097   if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
53098       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
53099     SDValue OldExtract = St->getOperand(1);
53100     SDValue ExtOp0 = OldExtract.getOperand(0);
53101     unsigned VecSize = ExtOp0.getValueSizeInBits();
53102     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
53103     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
53104     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
53105                                      BitCast, OldExtract.getOperand(1));
53106     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
53107                         St->getPointerInfo(), St->getOriginalAlign(),
53108                         St->getMemOperand()->getFlags());
53109   }
53110 
53111   return SDValue();
53112 }
53113 
53114 static SDValue combineVEXTRACT_STORE(SDNode *N, SelectionDAG &DAG,
53115                                      TargetLowering::DAGCombinerInfo &DCI,
53116                                      const X86Subtarget &Subtarget) {
53117   auto *St = cast<MemIntrinsicSDNode>(N);
53118 
53119   SDValue StoredVal = N->getOperand(1);
53120   MVT VT = StoredVal.getSimpleValueType();
53121   EVT MemVT = St->getMemoryVT();
53122 
53123   // Figure out which elements we demand.
53124   unsigned StElts = MemVT.getSizeInBits() / VT.getScalarSizeInBits();
53125   APInt DemandedElts = APInt::getLowBitsSet(VT.getVectorNumElements(), StElts);
53126 
53127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53128   if (TLI.SimplifyDemandedVectorElts(StoredVal, DemandedElts, DCI)) {
53129     if (N->getOpcode() != ISD::DELETED_NODE)
53130       DCI.AddToWorklist(N);
53131     return SDValue(N, 0);
53132   }
53133 
53134   return SDValue();
53135 }
53136 
53137 /// Return 'true' if this vector operation is "horizontal"
53138 /// and return the operands for the horizontal operation in LHS and RHS.  A
53139 /// horizontal operation performs the binary operation on successive elements
53140 /// of its first operand, then on successive elements of its second operand,
53141 /// returning the resulting values in a vector.  For example, if
53142 ///   A = < float a0, float a1, float a2, float a3 >
53143 /// and
53144 ///   B = < float b0, float b1, float b2, float b3 >
53145 /// then the result of doing a horizontal operation on A and B is
53146 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
53147 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
53148 /// A horizontal-op B, for some already available A and B, and if so then LHS is
53149 /// set to A, RHS to B, and the routine returns 'true'.
53150 static bool isHorizontalBinOp(unsigned HOpcode, SDValue &LHS, SDValue &RHS,
53151                               SelectionDAG &DAG, const X86Subtarget &Subtarget,
53152                               bool IsCommutative,
53153                               SmallVectorImpl<int> &PostShuffleMask) {
53154   // If either operand is undef, bail out. The binop should be simplified.
53155   if (LHS.isUndef() || RHS.isUndef())
53156     return false;
53157 
53158   // Look for the following pattern:
53159   //   A = < float a0, float a1, float a2, float a3 >
53160   //   B = < float b0, float b1, float b2, float b3 >
53161   // and
53162   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
53163   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
53164   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
53165   // which is A horizontal-op B.
53166 
53167   MVT VT = LHS.getSimpleValueType();
53168   assert((VT.is128BitVector() || VT.is256BitVector()) &&
53169          "Unsupported vector type for horizontal add/sub");
53170   unsigned NumElts = VT.getVectorNumElements();
53171 
53172   auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
53173                         SmallVectorImpl<int> &ShuffleMask) {
53174     bool UseSubVector = false;
53175     if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
53176         Op.getOperand(0).getValueType().is256BitVector() &&
53177         llvm::isNullConstant(Op.getOperand(1))) {
53178       Op = Op.getOperand(0);
53179       UseSubVector = true;
53180     }
53181     SmallVector<SDValue, 2> SrcOps;
53182     SmallVector<int, 16> SrcMask, ScaledMask;
53183     SDValue BC = peekThroughBitcasts(Op);
53184     if (getTargetShuffleInputs(BC, SrcOps, SrcMask, DAG) &&
53185         !isAnyZero(SrcMask) && all_of(SrcOps, [BC](SDValue Op) {
53186           return Op.getValueSizeInBits() == BC.getValueSizeInBits();
53187         })) {
53188       resolveTargetShuffleInputsAndMask(SrcOps, SrcMask);
53189       if (!UseSubVector && SrcOps.size() <= 2 &&
53190           scaleShuffleElements(SrcMask, NumElts, ScaledMask)) {
53191         N0 = !SrcOps.empty() ? SrcOps[0] : SDValue();
53192         N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
53193         ShuffleMask.assign(ScaledMask.begin(), ScaledMask.end());
53194       }
53195       if (UseSubVector && SrcOps.size() == 1 &&
53196           scaleShuffleElements(SrcMask, 2 * NumElts, ScaledMask)) {
53197         std::tie(N0, N1) = DAG.SplitVector(SrcOps[0], SDLoc(Op));
53198         ArrayRef<int> Mask = ArrayRef<int>(ScaledMask).slice(0, NumElts);
53199         ShuffleMask.assign(Mask.begin(), Mask.end());
53200       }
53201     }
53202   };
53203 
53204   // View LHS in the form
53205   //   LHS = VECTOR_SHUFFLE A, B, LMask
53206   // If LHS is not a shuffle, then pretend it is the identity shuffle:
53207   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
53208   // NOTE: A default initialized SDValue represents an UNDEF of type VT.
53209   SDValue A, B;
53210   SmallVector<int, 16> LMask;
53211   GetShuffle(LHS, A, B, LMask);
53212 
53213   // Likewise, view RHS in the form
53214   //   RHS = VECTOR_SHUFFLE C, D, RMask
53215   SDValue C, D;
53216   SmallVector<int, 16> RMask;
53217   GetShuffle(RHS, C, D, RMask);
53218 
53219   // At least one of the operands should be a vector shuffle.
53220   unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
53221   if (NumShuffles == 0)
53222     return false;
53223 
53224   if (LMask.empty()) {
53225     A = LHS;
53226     for (unsigned i = 0; i != NumElts; ++i)
53227       LMask.push_back(i);
53228   }
53229 
53230   if (RMask.empty()) {
53231     C = RHS;
53232     for (unsigned i = 0; i != NumElts; ++i)
53233       RMask.push_back(i);
53234   }
53235 
53236   // If we have an unary mask, ensure the other op is set to null.
53237   if (isUndefOrInRange(LMask, 0, NumElts))
53238     B = SDValue();
53239   else if (isUndefOrInRange(LMask, NumElts, NumElts * 2))
53240     A = SDValue();
53241 
53242   if (isUndefOrInRange(RMask, 0, NumElts))
53243     D = SDValue();
53244   else if (isUndefOrInRange(RMask, NumElts, NumElts * 2))
53245     C = SDValue();
53246 
53247   // If A and B occur in reverse order in RHS, then canonicalize by commuting
53248   // RHS operands and shuffle mask.
53249   if (A != C) {
53250     std::swap(C, D);
53251     ShuffleVectorSDNode::commuteMask(RMask);
53252   }
53253   // Check that the shuffles are both shuffling the same vectors.
53254   if (!(A == C && B == D))
53255     return false;
53256 
53257   PostShuffleMask.clear();
53258   PostShuffleMask.append(NumElts, SM_SentinelUndef);
53259 
53260   // LHS and RHS are now:
53261   //   LHS = shuffle A, B, LMask
53262   //   RHS = shuffle A, B, RMask
53263   // Check that the masks correspond to performing a horizontal operation.
53264   // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
53265   // so we just repeat the inner loop if this is a 256-bit op.
53266   unsigned Num128BitChunks = VT.getSizeInBits() / 128;
53267   unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
53268   unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
53269   assert((NumEltsPer128BitChunk % 2 == 0) &&
53270          "Vector type should have an even number of elements in each lane");
53271   for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
53272     for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
53273       // Ignore undefined components.
53274       int LIdx = LMask[i + j], RIdx = RMask[i + j];
53275       if (LIdx < 0 || RIdx < 0 ||
53276           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
53277           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
53278         continue;
53279 
53280       // Check that successive odd/even elements are being operated on. If not,
53281       // this is not a horizontal operation.
53282       if (!((RIdx & 1) == 1 && (LIdx + 1) == RIdx) &&
53283           !((LIdx & 1) == 1 && (RIdx + 1) == LIdx && IsCommutative))
53284         return false;
53285 
53286       // Compute the post-shuffle mask index based on where the element
53287       // is stored in the HOP result, and where it needs to be moved to.
53288       int Base = LIdx & ~1u;
53289       int Index = ((Base % NumEltsPer128BitChunk) / 2) +
53290                   ((Base % NumElts) & ~(NumEltsPer128BitChunk - 1));
53291 
53292       // The  low half of the 128-bit result must choose from A.
53293       // The high half of the 128-bit result must choose from B,
53294       // unless B is undef. In that case, we are always choosing from A.
53295       if ((B && Base >= (int)NumElts) || (!B && i >= NumEltsPer64BitChunk))
53296         Index += NumEltsPer64BitChunk;
53297       PostShuffleMask[i + j] = Index;
53298     }
53299   }
53300 
53301   SDValue NewLHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
53302   SDValue NewRHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
53303 
53304   bool IsIdentityPostShuffle =
53305       isSequentialOrUndefInRange(PostShuffleMask, 0, NumElts, 0);
53306   if (IsIdentityPostShuffle)
53307     PostShuffleMask.clear();
53308 
53309   // Avoid 128-bit multi lane shuffles if pre-AVX2 and FP (integer will split).
53310   if (!IsIdentityPostShuffle && !Subtarget.hasAVX2() && VT.isFloatingPoint() &&
53311       isMultiLaneShuffleMask(128, VT.getScalarSizeInBits(), PostShuffleMask))
53312     return false;
53313 
53314   // If the source nodes are already used in HorizOps then always accept this.
53315   // Shuffle folding should merge these back together.
53316   bool FoundHorizLHS = llvm::any_of(NewLHS->uses(), [&](SDNode *User) {
53317     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
53318   });
53319   bool FoundHorizRHS = llvm::any_of(NewRHS->uses(), [&](SDNode *User) {
53320     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
53321   });
53322   bool ForceHorizOp = FoundHorizLHS && FoundHorizRHS;
53323 
53324   // Assume a SingleSource HOP if we only shuffle one input and don't need to
53325   // shuffle the result.
53326   if (!ForceHorizOp &&
53327       !shouldUseHorizontalOp(NewLHS == NewRHS &&
53328                                  (NumShuffles < 2 || !IsIdentityPostShuffle),
53329                              DAG, Subtarget))
53330     return false;
53331 
53332   LHS = DAG.getBitcast(VT, NewLHS);
53333   RHS = DAG.getBitcast(VT, NewRHS);
53334   return true;
53335 }
53336 
53337 // Try to synthesize horizontal (f)hadd/hsub from (f)adds/subs of shuffles.
53338 static SDValue combineToHorizontalAddSub(SDNode *N, SelectionDAG &DAG,
53339                                          const X86Subtarget &Subtarget) {
53340   EVT VT = N->getValueType(0);
53341   unsigned Opcode = N->getOpcode();
53342   bool IsAdd = (Opcode == ISD::FADD) || (Opcode == ISD::ADD);
53343   SmallVector<int, 8> PostShuffleMask;
53344 
53345   switch (Opcode) {
53346   case ISD::FADD:
53347   case ISD::FSUB:
53348     if ((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
53349         (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
53350       SDValue LHS = N->getOperand(0);
53351       SDValue RHS = N->getOperand(1);
53352       auto HorizOpcode = IsAdd ? X86ISD::FHADD : X86ISD::FHSUB;
53353       if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
53354                             PostShuffleMask)) {
53355         SDValue HorizBinOp = DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
53356         if (!PostShuffleMask.empty())
53357           HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
53358                                             DAG.getUNDEF(VT), PostShuffleMask);
53359         return HorizBinOp;
53360       }
53361     }
53362     break;
53363   case ISD::ADD:
53364   case ISD::SUB:
53365     if (Subtarget.hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
53366                                  VT == MVT::v16i16 || VT == MVT::v8i32)) {
53367       SDValue LHS = N->getOperand(0);
53368       SDValue RHS = N->getOperand(1);
53369       auto HorizOpcode = IsAdd ? X86ISD::HADD : X86ISD::HSUB;
53370       if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
53371                             PostShuffleMask)) {
53372         auto HOpBuilder = [HorizOpcode](SelectionDAG &DAG, const SDLoc &DL,
53373                                         ArrayRef<SDValue> Ops) {
53374           return DAG.getNode(HorizOpcode, DL, Ops[0].getValueType(), Ops);
53375         };
53376         SDValue HorizBinOp = SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
53377                                               {LHS, RHS}, HOpBuilder);
53378         if (!PostShuffleMask.empty())
53379           HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
53380                                             DAG.getUNDEF(VT), PostShuffleMask);
53381         return HorizBinOp;
53382       }
53383     }
53384     break;
53385   }
53386 
53387   return SDValue();
53388 }
53389 
53390 //  Try to combine the following nodes
53391 //  t29: i64 = X86ISD::Wrapper TargetConstantPool:i64
53392 //    <i32 -2147483648[float -0.000000e+00]> 0
53393 //  t27: v16i32[v16f32],ch = X86ISD::VBROADCAST_LOAD
53394 //    <(load 4 from constant-pool)> t0, t29
53395 //  [t30: v16i32 = bitcast t27]
53396 //  t6: v16i32 = xor t7, t27[t30]
53397 //  t11: v16f32 = bitcast t6
53398 //  t21: v16f32 = X86ISD::VFMULC[X86ISD::VCFMULC] t11, t8
53399 //  into X86ISD::VFCMULC[X86ISD::VFMULC] if possible:
53400 //  t22: v16f32 = bitcast t7
53401 //  t23: v16f32 = X86ISD::VFCMULC[X86ISD::VFMULC] t8, t22
53402 //  t24: v32f16 = bitcast t23
53403 static SDValue combineFMulcFCMulc(SDNode *N, SelectionDAG &DAG,
53404                                   const X86Subtarget &Subtarget) {
53405   EVT VT = N->getValueType(0);
53406   SDValue LHS = N->getOperand(0);
53407   SDValue RHS = N->getOperand(1);
53408   int CombineOpcode =
53409       N->getOpcode() == X86ISD::VFCMULC ? X86ISD::VFMULC : X86ISD::VFCMULC;
53410   auto isConjugationConstant = [](const Constant *c) {
53411     if (const auto *CI = dyn_cast<ConstantInt>(c)) {
53412       APInt ConjugationInt32 = APInt(32, 0x80000000, true);
53413       APInt ConjugationInt64 = APInt(64, 0x8000000080000000ULL, true);
53414       switch (CI->getBitWidth()) {
53415       case 16:
53416         return false;
53417       case 32:
53418         return CI->getValue() == ConjugationInt32;
53419       case 64:
53420         return CI->getValue() == ConjugationInt64;
53421       default:
53422         llvm_unreachable("Unexpected bit width");
53423       }
53424     }
53425     if (const auto *CF = dyn_cast<ConstantFP>(c))
53426       return CF->getType()->isFloatTy() && CF->isNegativeZeroValue();
53427     return false;
53428   };
53429   auto combineConjugation = [&](SDValue &r) {
53430     if (LHS->getOpcode() == ISD::BITCAST && RHS.hasOneUse()) {
53431       SDValue XOR = LHS.getOperand(0);
53432       if (XOR->getOpcode() == ISD::XOR && XOR.hasOneUse()) {
53433         SDValue XORRHS = XOR.getOperand(1);
53434         if (XORRHS.getOpcode() == ISD::BITCAST && XORRHS.hasOneUse())
53435           XORRHS = XORRHS.getOperand(0);
53436         if (XORRHS.getOpcode() == X86ISD::VBROADCAST_LOAD &&
53437             XORRHS.getOperand(1).getNumOperands()) {
53438           ConstantPoolSDNode *CP =
53439               dyn_cast<ConstantPoolSDNode>(XORRHS.getOperand(1).getOperand(0));
53440           if (CP && isConjugationConstant(CP->getConstVal())) {
53441             SelectionDAG::FlagInserter FlagsInserter(DAG, N);
53442             SDValue I2F = DAG.getBitcast(VT, LHS.getOperand(0).getOperand(0));
53443             SDValue FCMulC = DAG.getNode(CombineOpcode, SDLoc(N), VT, RHS, I2F);
53444             r = DAG.getBitcast(VT, FCMulC);
53445             return true;
53446           }
53447         }
53448       }
53449     }
53450     return false;
53451   };
53452   SDValue Res;
53453   if (combineConjugation(Res))
53454     return Res;
53455   std::swap(LHS, RHS);
53456   if (combineConjugation(Res))
53457     return Res;
53458   return Res;
53459 }
53460 
53461 //  Try to combine the following nodes:
53462 //  FADD(A, FMA(B, C, 0)) and FADD(A, FMUL(B, C)) to FMA(B, C, A)
53463 static SDValue combineFaddCFmul(SDNode *N, SelectionDAG &DAG,
53464                                 const X86Subtarget &Subtarget) {
53465   auto AllowContract = [&DAG](const SDNodeFlags &Flags) {
53466     return DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
53467            Flags.hasAllowContract();
53468   };
53469 
53470   auto HasNoSignedZero = [&DAG](const SDNodeFlags &Flags) {
53471     return DAG.getTarget().Options.NoSignedZerosFPMath ||
53472            Flags.hasNoSignedZeros();
53473   };
53474   auto IsVectorAllNegativeZero = [](const SDNode *N) {
53475     if (N->getOpcode() != X86ISD::VBROADCAST_LOAD)
53476       return false;
53477     assert(N->getSimpleValueType(0).getScalarType() == MVT::f32 &&
53478            "Unexpected vector type!");
53479     if (ConstantPoolSDNode *CP =
53480             dyn_cast<ConstantPoolSDNode>(N->getOperand(1)->getOperand(0))) {
53481       APInt AI = APInt(32, 0x80008000, true);
53482       if (const auto *CI = dyn_cast<ConstantInt>(CP->getConstVal()))
53483         return CI->getValue() == AI;
53484       if (const auto *CF = dyn_cast<ConstantFP>(CP->getConstVal()))
53485         return CF->getValue() == APFloat(APFloat::IEEEsingle(), AI);
53486     }
53487     return false;
53488   };
53489 
53490   if (N->getOpcode() != ISD::FADD || !Subtarget.hasFP16() ||
53491       !AllowContract(N->getFlags()))
53492     return SDValue();
53493 
53494   EVT VT = N->getValueType(0);
53495   if (VT != MVT::v8f16 && VT != MVT::v16f16 && VT != MVT::v32f16)
53496     return SDValue();
53497 
53498   SDValue LHS = N->getOperand(0);
53499   SDValue RHS = N->getOperand(1);
53500   bool IsConj;
53501   SDValue FAddOp1, MulOp0, MulOp1;
53502   auto GetCFmulFrom = [&MulOp0, &MulOp1, &IsConj, &AllowContract,
53503                        &IsVectorAllNegativeZero,
53504                        &HasNoSignedZero](SDValue N) -> bool {
53505     if (!N.hasOneUse() || N.getOpcode() != ISD::BITCAST)
53506       return false;
53507     SDValue Op0 = N.getOperand(0);
53508     unsigned Opcode = Op0.getOpcode();
53509     if (Op0.hasOneUse() && AllowContract(Op0->getFlags())) {
53510       if ((Opcode == X86ISD::VFMULC || Opcode == X86ISD::VFCMULC)) {
53511         MulOp0 = Op0.getOperand(0);
53512         MulOp1 = Op0.getOperand(1);
53513         IsConj = Opcode == X86ISD::VFCMULC;
53514         return true;
53515       }
53516       if ((Opcode == X86ISD::VFMADDC || Opcode == X86ISD::VFCMADDC) &&
53517           ((ISD::isBuildVectorAllZeros(Op0->getOperand(2).getNode()) &&
53518             HasNoSignedZero(Op0->getFlags())) ||
53519            IsVectorAllNegativeZero(Op0->getOperand(2).getNode()))) {
53520         MulOp0 = Op0.getOperand(0);
53521         MulOp1 = Op0.getOperand(1);
53522         IsConj = Opcode == X86ISD::VFCMADDC;
53523         return true;
53524       }
53525     }
53526     return false;
53527   };
53528 
53529   if (GetCFmulFrom(LHS))
53530     FAddOp1 = RHS;
53531   else if (GetCFmulFrom(RHS))
53532     FAddOp1 = LHS;
53533   else
53534     return SDValue();
53535 
53536   MVT CVT = MVT::getVectorVT(MVT::f32, VT.getVectorNumElements() / 2);
53537   FAddOp1 = DAG.getBitcast(CVT, FAddOp1);
53538   unsigned NewOp = IsConj ? X86ISD::VFCMADDC : X86ISD::VFMADDC;
53539   // FIXME: How do we handle when fast math flags of FADD are different from
53540   // CFMUL's?
53541   SDValue CFmul =
53542       DAG.getNode(NewOp, SDLoc(N), CVT, MulOp0, MulOp1, FAddOp1, N->getFlags());
53543   return DAG.getBitcast(VT, CFmul);
53544 }
53545 
53546 /// Do target-specific dag combines on floating-point adds/subs.
53547 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
53548                                const X86Subtarget &Subtarget) {
53549   if (SDValue HOp = combineToHorizontalAddSub(N, DAG, Subtarget))
53550     return HOp;
53551 
53552   if (SDValue COp = combineFaddCFmul(N, DAG, Subtarget))
53553     return COp;
53554 
53555   return SDValue();
53556 }
53557 
53558 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
53559 /// the codegen.
53560 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
53561 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
53562 ///       anything that is guaranteed to be transformed by DAGCombiner.
53563 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
53564                                           const X86Subtarget &Subtarget,
53565                                           const SDLoc &DL) {
53566   assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
53567   SDValue Src = N->getOperand(0);
53568   unsigned SrcOpcode = Src.getOpcode();
53569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53570 
53571   EVT VT = N->getValueType(0);
53572   EVT SrcVT = Src.getValueType();
53573 
53574   auto IsFreeTruncation = [VT](SDValue Op) {
53575     unsigned TruncSizeInBits = VT.getScalarSizeInBits();
53576 
53577     // See if this has been extended from a smaller/equal size to
53578     // the truncation size, allowing a truncation to combine with the extend.
53579     unsigned Opcode = Op.getOpcode();
53580     if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
53581          Opcode == ISD::ZERO_EXTEND) &&
53582         Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
53583       return true;
53584 
53585     // See if this is a single use constant which can be constant folded.
53586     // NOTE: We don't peek throught bitcasts here because there is currently
53587     // no support for constant folding truncate+bitcast+vector_of_constants. So
53588     // we'll just send up with a truncate on both operands which will
53589     // get turned back into (truncate (binop)) causing an infinite loop.
53590     return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
53591   };
53592 
53593   auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
53594     SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
53595     SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
53596     return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
53597   };
53598 
53599   // Don't combine if the operation has other uses.
53600   if (!Src.hasOneUse())
53601     return SDValue();
53602 
53603   // Only support vector truncation for now.
53604   // TODO: i64 scalar math would benefit as well.
53605   if (!VT.isVector())
53606     return SDValue();
53607 
53608   // In most cases its only worth pre-truncating if we're only facing the cost
53609   // of one truncation.
53610   // i.e. if one of the inputs will constant fold or the input is repeated.
53611   switch (SrcOpcode) {
53612   case ISD::MUL:
53613     // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
53614     // better to truncate if we have the chance.
53615     if (SrcVT.getScalarType() == MVT::i64 &&
53616         TLI.isOperationLegal(SrcOpcode, VT) &&
53617         !TLI.isOperationLegal(SrcOpcode, SrcVT))
53618       return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
53619     [[fallthrough]];
53620   case ISD::AND:
53621   case ISD::XOR:
53622   case ISD::OR:
53623   case ISD::ADD:
53624   case ISD::SUB: {
53625     SDValue Op0 = Src.getOperand(0);
53626     SDValue Op1 = Src.getOperand(1);
53627     if (TLI.isOperationLegal(SrcOpcode, VT) &&
53628         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
53629       return TruncateArithmetic(Op0, Op1);
53630     break;
53631   }
53632   }
53633 
53634   return SDValue();
53635 }
53636 
53637 /// This function transforms vector truncation of 'extended sign-bits' or
53638 /// 'extended zero-bits' values.
53639 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
53640 /// TODO: Remove this and just use LowerTruncateVecPackWithSignBits.
53641 static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
53642                                                SelectionDAG &DAG,
53643                                                const X86Subtarget &Subtarget) {
53644   // Requires SSE2.
53645   if (!Subtarget.hasSSE2())
53646     return SDValue();
53647 
53648   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
53649     return SDValue();
53650 
53651   SDValue In = N->getOperand(0);
53652   if (!In.getValueType().isSimple())
53653     return SDValue();
53654 
53655   MVT VT = N->getValueType(0).getSimpleVT();
53656   MVT SVT = VT.getScalarType();
53657 
53658   MVT InVT = In.getValueType().getSimpleVT();
53659   MVT InSVT = InVT.getScalarType();
53660 
53661   // Check we have a truncation suited for PACKSS/PACKUS.
53662   if (!isPowerOf2_32(VT.getVectorNumElements()))
53663     return SDValue();
53664   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
53665     return SDValue();
53666   if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
53667     return SDValue();
53668 
53669   // Truncation to sub-128bit vXi32 can be better handled with shuffles.
53670   if (SVT == MVT::i32 && VT.getSizeInBits() < 128)
53671     return SDValue();
53672 
53673   // AVX512 has fast truncate, but if the input is already going to be split,
53674   // there's no harm in trying pack.
53675   if (Subtarget.hasAVX512() &&
53676       !(!Subtarget.useAVX512Regs() && VT.is256BitVector() &&
53677         InVT.is512BitVector())) {
53678     // PACK should still be worth it for 128-bit vectors if the sources were
53679     // originally concatenated from subvectors.
53680     if (VT.getSizeInBits() > 128 || !isFreeToSplitVector(In.getNode(), DAG))
53681       return SDValue();
53682   }
53683 
53684   unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
53685   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
53686 
53687   // Use PACKUS if the input has zero-bits that extend all the way to the
53688   // packed/truncated value. e.g. masks, zext_in_reg, etc.
53689   KnownBits Known = DAG.computeKnownBits(In);
53690   unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
53691   if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
53692     return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
53693 
53694   // Use PACKSS if the input has sign-bits that extend all the way to the
53695   // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
53696   unsigned NumSignBits = DAG.ComputeNumSignBits(In);
53697 
53698   // Don't use PACKSS for vXi64 -> vXi32 truncations unless we're dealing with
53699   // a sign splat. ComputeNumSignBits struggles to see through BITCASTs later
53700   // on and combines/simplifications can't then use it.
53701   if (SVT == MVT::i32 && NumSignBits != InSVT.getSizeInBits())
53702     return SDValue();
53703 
53704   unsigned MinSignBits = InSVT.getSizeInBits() - NumPackedSignBits;
53705   if (NumSignBits > MinSignBits)
53706     return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
53707 
53708   // If we have a srl that only generates signbits that we will discard in
53709   // the truncation then we can use PACKSS by converting the srl to a sra.
53710   // SimplifyDemandedBits often relaxes sra to srl so we need to reverse it.
53711   if (In.getOpcode() == ISD::SRL && N->isOnlyUserOf(In.getNode()))
53712     if (const APInt *ShAmt = DAG.getValidShiftAmountConstant(
53713             In, APInt::getAllOnes(VT.getVectorNumElements()))) {
53714       if (*ShAmt == MinSignBits) {
53715         SDValue NewIn = DAG.getNode(ISD::SRA, DL, InVT, In->ops());
53716         return truncateVectorWithPACK(X86ISD::PACKSS, VT, NewIn, DL, DAG,
53717                                       Subtarget);
53718       }
53719     }
53720 
53721   return SDValue();
53722 }
53723 
53724 // Try to form a MULHU or MULHS node by looking for
53725 // (trunc (srl (mul ext, ext), 16))
53726 // TODO: This is X86 specific because we want to be able to handle wide types
53727 // before type legalization. But we can only do it if the vector will be
53728 // legalized via widening/splitting. Type legalization can't handle promotion
53729 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
53730 // combiner.
53731 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
53732                             SelectionDAG &DAG, const X86Subtarget &Subtarget) {
53733   // First instruction should be a right shift of a multiply.
53734   if (Src.getOpcode() != ISD::SRL ||
53735       Src.getOperand(0).getOpcode() != ISD::MUL)
53736     return SDValue();
53737 
53738   if (!Subtarget.hasSSE2())
53739     return SDValue();
53740 
53741   // Only handle vXi16 types that are at least 128-bits unless they will be
53742   // widened.
53743   if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
53744     return SDValue();
53745 
53746   // Input type should be at least vXi32.
53747   EVT InVT = Src.getValueType();
53748   if (InVT.getVectorElementType().getSizeInBits() < 32)
53749     return SDValue();
53750 
53751   // Need a shift by 16.
53752   APInt ShiftAmt;
53753   if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
53754       ShiftAmt != 16)
53755     return SDValue();
53756 
53757   SDValue LHS = Src.getOperand(0).getOperand(0);
53758   SDValue RHS = Src.getOperand(0).getOperand(1);
53759 
53760   // Count leading sign/zero bits on both inputs - if there are enough then
53761   // truncation back to vXi16 will be cheap - either as a pack/shuffle
53762   // sequence or using AVX512 truncations. If the inputs are sext/zext then the
53763   // truncations may actually be free by peeking through to the ext source.
53764   auto IsSext = [&DAG](SDValue V) {
53765     return DAG.ComputeMaxSignificantBits(V) <= 16;
53766   };
53767   auto IsZext = [&DAG](SDValue V) {
53768     return DAG.computeKnownBits(V).countMaxActiveBits() <= 16;
53769   };
53770 
53771   bool IsSigned = IsSext(LHS) && IsSext(RHS);
53772   bool IsUnsigned = IsZext(LHS) && IsZext(RHS);
53773   if (!IsSigned && !IsUnsigned)
53774     return SDValue();
53775 
53776   // Check if both inputs are extensions, which will be removed by truncation.
53777   bool IsTruncateFree = (LHS.getOpcode() == ISD::SIGN_EXTEND ||
53778                          LHS.getOpcode() == ISD::ZERO_EXTEND) &&
53779                         (RHS.getOpcode() == ISD::SIGN_EXTEND ||
53780                          RHS.getOpcode() == ISD::ZERO_EXTEND) &&
53781                         LHS.getOperand(0).getScalarValueSizeInBits() <= 16 &&
53782                         RHS.getOperand(0).getScalarValueSizeInBits() <= 16;
53783 
53784   // For AVX2+ targets, with the upper bits known zero, we can perform MULHU on
53785   // the (bitcasted) inputs directly, and then cheaply pack/truncate the result
53786   // (upper elts will be zero). Don't attempt this with just AVX512F as MULHU
53787   // will have to split anyway.
53788   unsigned InSizeInBits = InVT.getSizeInBits();
53789   if (IsUnsigned && !IsTruncateFree && Subtarget.hasInt256() &&
53790       !(Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.is256BitVector()) &&
53791       (InSizeInBits % 16) == 0) {
53792     EVT BCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
53793                                 InVT.getSizeInBits() / 16);
53794     SDValue Res = DAG.getNode(ISD::MULHU, DL, BCVT, DAG.getBitcast(BCVT, LHS),
53795                               DAG.getBitcast(BCVT, RHS));
53796     return DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getBitcast(InVT, Res));
53797   }
53798 
53799   // Truncate back to source type.
53800   LHS = DAG.getNode(ISD::TRUNCATE, DL, VT, LHS);
53801   RHS = DAG.getNode(ISD::TRUNCATE, DL, VT, RHS);
53802 
53803   unsigned Opc = IsSigned ? ISD::MULHS : ISD::MULHU;
53804   return DAG.getNode(Opc, DL, VT, LHS, RHS);
53805 }
53806 
53807 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
53808 // from one vector with signed bytes from another vector, adds together
53809 // adjacent pairs of 16-bit products, and saturates the result before
53810 // truncating to 16-bits.
53811 //
53812 // Which looks something like this:
53813 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
53814 //                 (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
53815 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
53816                                const X86Subtarget &Subtarget,
53817                                const SDLoc &DL) {
53818   if (!VT.isVector() || !Subtarget.hasSSSE3())
53819     return SDValue();
53820 
53821   unsigned NumElems = VT.getVectorNumElements();
53822   EVT ScalarVT = VT.getVectorElementType();
53823   if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
53824     return SDValue();
53825 
53826   SDValue SSatVal = detectSSatPattern(In, VT);
53827   if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
53828     return SDValue();
53829 
53830   // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
53831   // of multiplies from even/odd elements.
53832   SDValue N0 = SSatVal.getOperand(0);
53833   SDValue N1 = SSatVal.getOperand(1);
53834 
53835   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
53836     return SDValue();
53837 
53838   SDValue N00 = N0.getOperand(0);
53839   SDValue N01 = N0.getOperand(1);
53840   SDValue N10 = N1.getOperand(0);
53841   SDValue N11 = N1.getOperand(1);
53842 
53843   // TODO: Handle constant vectors and use knownbits/computenumsignbits?
53844   // Canonicalize zero_extend to LHS.
53845   if (N01.getOpcode() == ISD::ZERO_EXTEND)
53846     std::swap(N00, N01);
53847   if (N11.getOpcode() == ISD::ZERO_EXTEND)
53848     std::swap(N10, N11);
53849 
53850   // Ensure we have a zero_extend and a sign_extend.
53851   if (N00.getOpcode() != ISD::ZERO_EXTEND ||
53852       N01.getOpcode() != ISD::SIGN_EXTEND ||
53853       N10.getOpcode() != ISD::ZERO_EXTEND ||
53854       N11.getOpcode() != ISD::SIGN_EXTEND)
53855     return SDValue();
53856 
53857   // Peek through the extends.
53858   N00 = N00.getOperand(0);
53859   N01 = N01.getOperand(0);
53860   N10 = N10.getOperand(0);
53861   N11 = N11.getOperand(0);
53862 
53863   // Ensure the extend is from vXi8.
53864   if (N00.getValueType().getVectorElementType() != MVT::i8 ||
53865       N01.getValueType().getVectorElementType() != MVT::i8 ||
53866       N10.getValueType().getVectorElementType() != MVT::i8 ||
53867       N11.getValueType().getVectorElementType() != MVT::i8)
53868     return SDValue();
53869 
53870   // All inputs should be build_vectors.
53871   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
53872       N01.getOpcode() != ISD::BUILD_VECTOR ||
53873       N10.getOpcode() != ISD::BUILD_VECTOR ||
53874       N11.getOpcode() != ISD::BUILD_VECTOR)
53875     return SDValue();
53876 
53877   // N00/N10 are zero extended. N01/N11 are sign extended.
53878 
53879   // For each element, we need to ensure we have an odd element from one vector
53880   // multiplied by the odd element of another vector and the even element from
53881   // one of the same vectors being multiplied by the even element from the
53882   // other vector. So we need to make sure for each element i, this operator
53883   // is being performed:
53884   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
53885   SDValue ZExtIn, SExtIn;
53886   for (unsigned i = 0; i != NumElems; ++i) {
53887     SDValue N00Elt = N00.getOperand(i);
53888     SDValue N01Elt = N01.getOperand(i);
53889     SDValue N10Elt = N10.getOperand(i);
53890     SDValue N11Elt = N11.getOperand(i);
53891     // TODO: Be more tolerant to undefs.
53892     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53893         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53894         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53895         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
53896       return SDValue();
53897     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
53898     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
53899     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
53900     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
53901     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
53902       return SDValue();
53903     unsigned IdxN00 = ConstN00Elt->getZExtValue();
53904     unsigned IdxN01 = ConstN01Elt->getZExtValue();
53905     unsigned IdxN10 = ConstN10Elt->getZExtValue();
53906     unsigned IdxN11 = ConstN11Elt->getZExtValue();
53907     // Add is commutative so indices can be reordered.
53908     if (IdxN00 > IdxN10) {
53909       std::swap(IdxN00, IdxN10);
53910       std::swap(IdxN01, IdxN11);
53911     }
53912     // N0 indices be the even element. N1 indices must be the next odd element.
53913     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
53914         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
53915       return SDValue();
53916     SDValue N00In = N00Elt.getOperand(0);
53917     SDValue N01In = N01Elt.getOperand(0);
53918     SDValue N10In = N10Elt.getOperand(0);
53919     SDValue N11In = N11Elt.getOperand(0);
53920     // First time we find an input capture it.
53921     if (!ZExtIn) {
53922       ZExtIn = N00In;
53923       SExtIn = N01In;
53924     }
53925     if (ZExtIn != N00In || SExtIn != N01In ||
53926         ZExtIn != N10In || SExtIn != N11In)
53927       return SDValue();
53928   }
53929 
53930   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
53931                          ArrayRef<SDValue> Ops) {
53932     // Shrink by adding truncate nodes and let DAGCombine fold with the
53933     // sources.
53934     EVT InVT = Ops[0].getValueType();
53935     assert(InVT.getScalarType() == MVT::i8 &&
53936            "Unexpected scalar element type");
53937     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
53938     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
53939                                  InVT.getVectorNumElements() / 2);
53940     return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
53941   };
53942   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
53943                           PMADDBuilder);
53944 }
53945 
53946 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
53947                                const X86Subtarget &Subtarget) {
53948   EVT VT = N->getValueType(0);
53949   SDValue Src = N->getOperand(0);
53950   SDLoc DL(N);
53951 
53952   // Attempt to pre-truncate inputs to arithmetic ops instead.
53953   if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
53954     return V;
53955 
53956   // Try to detect AVG pattern first.
53957   if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
53958     return Avg;
53959 
53960   // Try to detect PMADD
53961   if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
53962     return PMAdd;
53963 
53964   // Try to combine truncation with signed/unsigned saturation.
53965   if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
53966     return Val;
53967 
53968   // Try to combine PMULHUW/PMULHW for vXi16.
53969   if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
53970     return V;
53971 
53972   // The bitcast source is a direct mmx result.
53973   // Detect bitcasts between i32 to x86mmx
53974   if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
53975     SDValue BCSrc = Src.getOperand(0);
53976     if (BCSrc.getValueType() == MVT::x86mmx)
53977       return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
53978   }
53979 
53980   // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
53981   if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
53982     return V;
53983 
53984   return SDValue();
53985 }
53986 
53987 static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG,
53988                              TargetLowering::DAGCombinerInfo &DCI) {
53989   EVT VT = N->getValueType(0);
53990   SDValue In = N->getOperand(0);
53991   SDLoc DL(N);
53992 
53993   if (SDValue SSatVal = detectSSatPattern(In, VT))
53994     return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
53995   if (SDValue USatVal = detectUSatPattern(In, VT, DAG, DL))
53996     return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
53997 
53998   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53999   APInt DemandedMask(APInt::getAllOnes(VT.getScalarSizeInBits()));
54000   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
54001     return SDValue(N, 0);
54002 
54003   return SDValue();
54004 }
54005 
54006 /// Returns the negated value if the node \p N flips sign of FP value.
54007 ///
54008 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
54009 /// or FSUB(0, x)
54010 /// AVX512F does not have FXOR, so FNEG is lowered as
54011 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
54012 /// In this case we go though all bitcasts.
54013 /// This also recognizes splat of a negated value and returns the splat of that
54014 /// value.
54015 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
54016   if (N->getOpcode() == ISD::FNEG)
54017     return N->getOperand(0);
54018 
54019   // Don't recurse exponentially.
54020   if (Depth > SelectionDAG::MaxRecursionDepth)
54021     return SDValue();
54022 
54023   unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
54024 
54025   SDValue Op = peekThroughBitcasts(SDValue(N, 0));
54026   EVT VT = Op->getValueType(0);
54027 
54028   // Make sure the element size doesn't change.
54029   if (VT.getScalarSizeInBits() != ScalarSize)
54030     return SDValue();
54031 
54032   unsigned Opc = Op.getOpcode();
54033   switch (Opc) {
54034   case ISD::VECTOR_SHUFFLE: {
54035     // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
54036     // of this is VECTOR_SHUFFLE(-VEC1, UNDEF).  The mask can be anything here.
54037     if (!Op.getOperand(1).isUndef())
54038       return SDValue();
54039     if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
54040       if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
54041         return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
54042                                     cast<ShuffleVectorSDNode>(Op)->getMask());
54043     break;
54044   }
54045   case ISD::INSERT_VECTOR_ELT: {
54046     // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
54047     // -V, INDEX).
54048     SDValue InsVector = Op.getOperand(0);
54049     SDValue InsVal = Op.getOperand(1);
54050     if (!InsVector.isUndef())
54051       return SDValue();
54052     if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
54053       if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
54054         return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
54055                            NegInsVal, Op.getOperand(2));
54056     break;
54057   }
54058   case ISD::FSUB:
54059   case ISD::XOR:
54060   case X86ISD::FXOR: {
54061     SDValue Op1 = Op.getOperand(1);
54062     SDValue Op0 = Op.getOperand(0);
54063 
54064     // For XOR and FXOR, we want to check if constant
54065     // bits of Op1 are sign bit masks. For FSUB, we
54066     // have to check if constant bits of Op0 are sign
54067     // bit masks and hence we swap the operands.
54068     if (Opc == ISD::FSUB)
54069       std::swap(Op0, Op1);
54070 
54071     APInt UndefElts;
54072     SmallVector<APInt, 16> EltBits;
54073     // Extract constant bits and see if they are all
54074     // sign bit masks. Ignore the undef elements.
54075     if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
54076                                       /* AllowWholeUndefs */ true,
54077                                       /* AllowPartialUndefs */ false)) {
54078       for (unsigned I = 0, E = EltBits.size(); I < E; I++)
54079         if (!UndefElts[I] && !EltBits[I].isSignMask())
54080           return SDValue();
54081 
54082       // Only allow bitcast from correctly-sized constant.
54083       Op0 = peekThroughBitcasts(Op0);
54084       if (Op0.getScalarValueSizeInBits() == ScalarSize)
54085         return Op0;
54086     }
54087     break;
54088   } // case
54089   } // switch
54090 
54091   return SDValue();
54092 }
54093 
54094 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
54095                                 bool NegRes) {
54096   if (NegMul) {
54097     switch (Opcode) {
54098     default: llvm_unreachable("Unexpected opcode");
54099     case ISD::FMA:              Opcode = X86ISD::FNMADD;        break;
54100     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FNMADD; break;
54101     case X86ISD::FMADD_RND:     Opcode = X86ISD::FNMADD_RND;    break;
54102     case X86ISD::FMSUB:         Opcode = X86ISD::FNMSUB;        break;
54103     case X86ISD::STRICT_FMSUB:  Opcode = X86ISD::STRICT_FNMSUB; break;
54104     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FNMSUB_RND;    break;
54105     case X86ISD::FNMADD:        Opcode = ISD::FMA;              break;
54106     case X86ISD::STRICT_FNMADD: Opcode = ISD::STRICT_FMA;       break;
54107     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FMADD_RND;     break;
54108     case X86ISD::FNMSUB:        Opcode = X86ISD::FMSUB;         break;
54109     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FMSUB;  break;
54110     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FMSUB_RND;     break;
54111     }
54112   }
54113 
54114   if (NegAcc) {
54115     switch (Opcode) {
54116     default: llvm_unreachable("Unexpected opcode");
54117     case ISD::FMA:              Opcode = X86ISD::FMSUB;         break;
54118     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FMSUB;  break;
54119     case X86ISD::FMADD_RND:     Opcode = X86ISD::FMSUB_RND;     break;
54120     case X86ISD::FMSUB:         Opcode = ISD::FMA;              break;
54121     case X86ISD::STRICT_FMSUB:  Opcode = ISD::STRICT_FMA;       break;
54122     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FMADD_RND;     break;
54123     case X86ISD::FNMADD:        Opcode = X86ISD::FNMSUB;        break;
54124     case X86ISD::STRICT_FNMADD: Opcode = X86ISD::STRICT_FNMSUB; break;
54125     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FNMSUB_RND;    break;
54126     case X86ISD::FNMSUB:        Opcode = X86ISD::FNMADD;        break;
54127     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FNMADD; break;
54128     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FNMADD_RND;    break;
54129     case X86ISD::FMADDSUB:      Opcode = X86ISD::FMSUBADD;      break;
54130     case X86ISD::FMADDSUB_RND:  Opcode = X86ISD::FMSUBADD_RND;  break;
54131     case X86ISD::FMSUBADD:      Opcode = X86ISD::FMADDSUB;      break;
54132     case X86ISD::FMSUBADD_RND:  Opcode = X86ISD::FMADDSUB_RND;  break;
54133     }
54134   }
54135 
54136   if (NegRes) {
54137     switch (Opcode) {
54138     // For accuracy reason, we never combine fneg and fma under strict FP.
54139     default: llvm_unreachable("Unexpected opcode");
54140     case ISD::FMA:             Opcode = X86ISD::FNMSUB;       break;
54141     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
54142     case X86ISD::FMSUB:        Opcode = X86ISD::FNMADD;       break;
54143     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMADD_RND;   break;
54144     case X86ISD::FNMADD:       Opcode = X86ISD::FMSUB;        break;
54145     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMSUB_RND;    break;
54146     case X86ISD::FNMSUB:       Opcode = ISD::FMA;             break;
54147     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMADD_RND;    break;
54148     }
54149   }
54150 
54151   return Opcode;
54152 }
54153 
54154 /// Do target-specific dag combines on floating point negations.
54155 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
54156                            TargetLowering::DAGCombinerInfo &DCI,
54157                            const X86Subtarget &Subtarget) {
54158   EVT OrigVT = N->getValueType(0);
54159   SDValue Arg = isFNEG(DAG, N);
54160   if (!Arg)
54161     return SDValue();
54162 
54163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54164   EVT VT = Arg.getValueType();
54165   EVT SVT = VT.getScalarType();
54166   SDLoc DL(N);
54167 
54168   // Let legalize expand this if it isn't a legal type yet.
54169   if (!TLI.isTypeLegal(VT))
54170     return SDValue();
54171 
54172   // If we're negating a FMUL node on a target with FMA, then we can avoid the
54173   // use of a constant by performing (-0 - A*B) instead.
54174   // FIXME: Check rounding control flags as well once it becomes available.
54175   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
54176       Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
54177     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
54178     SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
54179                                   Arg.getOperand(1), Zero);
54180     return DAG.getBitcast(OrigVT, NewNode);
54181   }
54182 
54183   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
54184   bool LegalOperations = !DCI.isBeforeLegalizeOps();
54185   if (SDValue NegArg =
54186           TLI.getNegatedExpression(Arg, DAG, LegalOperations, CodeSize))
54187     return DAG.getBitcast(OrigVT, NegArg);
54188 
54189   return SDValue();
54190 }
54191 
54192 SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
54193                                                 bool LegalOperations,
54194                                                 bool ForCodeSize,
54195                                                 NegatibleCost &Cost,
54196                                                 unsigned Depth) const {
54197   // fneg patterns are removable even if they have multiple uses.
54198   if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth)) {
54199     Cost = NegatibleCost::Cheaper;
54200     return DAG.getBitcast(Op.getValueType(), Arg);
54201   }
54202 
54203   EVT VT = Op.getValueType();
54204   EVT SVT = VT.getScalarType();
54205   unsigned Opc = Op.getOpcode();
54206   SDNodeFlags Flags = Op.getNode()->getFlags();
54207   switch (Opc) {
54208   case ISD::FMA:
54209   case X86ISD::FMSUB:
54210   case X86ISD::FNMADD:
54211   case X86ISD::FNMSUB:
54212   case X86ISD::FMADD_RND:
54213   case X86ISD::FMSUB_RND:
54214   case X86ISD::FNMADD_RND:
54215   case X86ISD::FNMSUB_RND: {
54216     if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
54217         !(SVT == MVT::f32 || SVT == MVT::f64) ||
54218         !isOperationLegal(ISD::FMA, VT))
54219       break;
54220 
54221     // Don't fold (fneg (fma (fneg x), y, (fneg z))) to (fma x, y, z)
54222     // if it may have signed zeros.
54223     if (!Flags.hasNoSignedZeros())
54224       break;
54225 
54226     // This is always negatible for free but we might be able to remove some
54227     // extra operand negations as well.
54228     SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
54229     for (int i = 0; i != 3; ++i)
54230       NewOps[i] = getCheaperNegatedExpression(
54231           Op.getOperand(i), DAG, LegalOperations, ForCodeSize, Depth + 1);
54232 
54233     bool NegA = !!NewOps[0];
54234     bool NegB = !!NewOps[1];
54235     bool NegC = !!NewOps[2];
54236     unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
54237 
54238     Cost = (NegA || NegB || NegC) ? NegatibleCost::Cheaper
54239                                   : NegatibleCost::Neutral;
54240 
54241     // Fill in the non-negated ops with the original values.
54242     for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
54243       if (!NewOps[i])
54244         NewOps[i] = Op.getOperand(i);
54245     return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
54246   }
54247   case X86ISD::FRCP:
54248     if (SDValue NegOp0 =
54249             getNegatedExpression(Op.getOperand(0), DAG, LegalOperations,
54250                                  ForCodeSize, Cost, Depth + 1))
54251       return DAG.getNode(Opc, SDLoc(Op), VT, NegOp0);
54252     break;
54253   }
54254 
54255   return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
54256                                               ForCodeSize, Cost, Depth);
54257 }
54258 
54259 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
54260                                  const X86Subtarget &Subtarget) {
54261   MVT VT = N->getSimpleValueType(0);
54262   // If we have integer vector types available, use the integer opcodes.
54263   if (!VT.isVector() || !Subtarget.hasSSE2())
54264     return SDValue();
54265 
54266   SDLoc dl(N);
54267 
54268   unsigned IntBits = VT.getScalarSizeInBits();
54269   MVT IntSVT = MVT::getIntegerVT(IntBits);
54270   MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
54271 
54272   SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
54273   SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
54274   unsigned IntOpcode;
54275   switch (N->getOpcode()) {
54276   default: llvm_unreachable("Unexpected FP logic op");
54277   case X86ISD::FOR:   IntOpcode = ISD::OR; break;
54278   case X86ISD::FXOR:  IntOpcode = ISD::XOR; break;
54279   case X86ISD::FAND:  IntOpcode = ISD::AND; break;
54280   case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
54281   }
54282   SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
54283   return DAG.getBitcast(VT, IntOp);
54284 }
54285 
54286 
54287 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
54288 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
54289   if (N->getOpcode() != ISD::XOR)
54290     return SDValue();
54291 
54292   SDValue LHS = N->getOperand(0);
54293   if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
54294     return SDValue();
54295 
54296   X86::CondCode NewCC = X86::GetOppositeBranchCondition(
54297       X86::CondCode(LHS->getConstantOperandVal(0)));
54298   SDLoc DL(N);
54299   return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
54300 }
54301 
54302 static SDValue combineXorSubCTLZ(SDNode *N, SelectionDAG &DAG,
54303                                  const X86Subtarget &Subtarget) {
54304   assert((N->getOpcode() == ISD::XOR || N->getOpcode() == ISD::SUB) &&
54305          "Invalid opcode for combing with CTLZ");
54306   if (Subtarget.hasFastLZCNT())
54307     return SDValue();
54308 
54309   EVT VT = N->getValueType(0);
54310   if (VT != MVT::i8 && VT != MVT::i16 && VT != MVT::i32 &&
54311       (VT != MVT::i64 || !Subtarget.is64Bit()))
54312     return SDValue();
54313 
54314   SDValue N0 = N->getOperand(0);
54315   SDValue N1 = N->getOperand(1);
54316 
54317   if (N0.getOpcode() != ISD::CTLZ_ZERO_UNDEF &&
54318       N1.getOpcode() != ISD::CTLZ_ZERO_UNDEF)
54319     return SDValue();
54320 
54321   SDValue OpCTLZ;
54322   SDValue OpSizeTM1;
54323 
54324   if (N1.getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
54325     OpCTLZ = N1;
54326     OpSizeTM1 = N0;
54327   } else if (N->getOpcode() == ISD::SUB) {
54328     return SDValue();
54329   } else {
54330     OpCTLZ = N0;
54331     OpSizeTM1 = N1;
54332   }
54333 
54334   if (!OpCTLZ.hasOneUse())
54335     return SDValue();
54336   auto *C = dyn_cast<ConstantSDNode>(OpSizeTM1);
54337   if (!C)
54338     return SDValue();
54339 
54340   if (C->getZExtValue() != uint64_t(OpCTLZ.getValueSizeInBits() - 1))
54341     return SDValue();
54342   SDLoc DL(N);
54343   EVT OpVT = VT;
54344   SDValue Op = OpCTLZ.getOperand(0);
54345   if (VT == MVT::i8) {
54346     // Zero extend to i32 since there is not an i8 bsr.
54347     OpVT = MVT::i32;
54348     Op = DAG.getNode(ISD::ZERO_EXTEND, DL, OpVT, Op);
54349   }
54350 
54351   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
54352   Op = DAG.getNode(X86ISD::BSR, DL, VTs, Op);
54353   if (VT == MVT::i8)
54354     Op = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Op);
54355 
54356   return Op;
54357 }
54358 
54359 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
54360                           TargetLowering::DAGCombinerInfo &DCI,
54361                           const X86Subtarget &Subtarget) {
54362   SDValue N0 = N->getOperand(0);
54363   SDValue N1 = N->getOperand(1);
54364   EVT VT = N->getValueType(0);
54365 
54366   // If this is SSE1 only convert to FXOR to avoid scalarization.
54367   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
54368     return DAG.getBitcast(MVT::v4i32,
54369                           DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
54370                                       DAG.getBitcast(MVT::v4f32, N0),
54371                                       DAG.getBitcast(MVT::v4f32, N1)));
54372   }
54373 
54374   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
54375     return Cmp;
54376 
54377   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
54378     return R;
54379 
54380   if (SDValue R = combineBitOpWithShift(N, DAG))
54381     return R;
54382 
54383   if (SDValue R = combineBitOpWithPACK(N, DAG))
54384     return R;
54385 
54386   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
54387     return FPLogic;
54388 
54389   if (SDValue R = combineXorSubCTLZ(N, DAG, Subtarget))
54390     return R;
54391 
54392   if (DCI.isBeforeLegalizeOps())
54393     return SDValue();
54394 
54395   if (SDValue SetCC = foldXor1SetCC(N, DAG))
54396     return SetCC;
54397 
54398   if (SDValue R = combineOrXorWithSETCC(N, N0, N1, DAG))
54399     return R;
54400 
54401   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
54402     return RV;
54403 
54404   // Fold not(iX bitcast(vXi1)) -> (iX bitcast(not(vec))) for legal boolvecs.
54405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54406   if (llvm::isAllOnesConstant(N1) && N0.getOpcode() == ISD::BITCAST &&
54407       N0.getOperand(0).getValueType().isVector() &&
54408       N0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
54409       TLI.isTypeLegal(N0.getOperand(0).getValueType()) && N0.hasOneUse()) {
54410     return DAG.getBitcast(VT, DAG.getNOT(SDLoc(N), N0.getOperand(0),
54411                                          N0.getOperand(0).getValueType()));
54412   }
54413 
54414   // Handle AVX512 mask widening.
54415   // Fold not(insert_subvector(undef,sub)) -> insert_subvector(undef,not(sub))
54416   if (ISD::isBuildVectorAllOnes(N1.getNode()) && VT.isVector() &&
54417       VT.getVectorElementType() == MVT::i1 &&
54418       N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.getOperand(0).isUndef() &&
54419       TLI.isTypeLegal(N0.getOperand(1).getValueType())) {
54420     return DAG.getNode(
54421         ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
54422         DAG.getNOT(SDLoc(N), N0.getOperand(1), N0.getOperand(1).getValueType()),
54423         N0.getOperand(2));
54424   }
54425 
54426   // Fold xor(zext(xor(x,c1)),c2) -> xor(zext(x),xor(zext(c1),c2))
54427   // Fold xor(truncate(xor(x,c1)),c2) -> xor(truncate(x),xor(truncate(c1),c2))
54428   // TODO: Under what circumstances could this be performed in DAGCombine?
54429   if ((N0.getOpcode() == ISD::TRUNCATE || N0.getOpcode() == ISD::ZERO_EXTEND) &&
54430       N0.getOperand(0).getOpcode() == N->getOpcode()) {
54431     SDValue TruncExtSrc = N0.getOperand(0);
54432     auto *N1C = dyn_cast<ConstantSDNode>(N1);
54433     auto *N001C = dyn_cast<ConstantSDNode>(TruncExtSrc.getOperand(1));
54434     if (N1C && !N1C->isOpaque() && N001C && !N001C->isOpaque()) {
54435       SDLoc DL(N);
54436       SDValue LHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(0), DL, VT);
54437       SDValue RHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(1), DL, VT);
54438       return DAG.getNode(ISD::XOR, DL, VT, LHS,
54439                          DAG.getNode(ISD::XOR, DL, VT, RHS, N1));
54440     }
54441   }
54442 
54443   if (SDValue R = combineBMILogicOp(N, DAG, Subtarget))
54444     return R;
54445 
54446   return combineFneg(N, DAG, DCI, Subtarget);
54447 }
54448 
54449 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
54450                             TargetLowering::DAGCombinerInfo &DCI,
54451                             const X86Subtarget &Subtarget) {
54452   EVT VT = N->getValueType(0);
54453   unsigned NumBits = VT.getSizeInBits();
54454 
54455   // TODO - Constant Folding.
54456 
54457   // Simplify the inputs.
54458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54459   APInt DemandedMask(APInt::getAllOnes(NumBits));
54460   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
54461     return SDValue(N, 0);
54462 
54463   return SDValue();
54464 }
54465 
54466 static bool isNullFPScalarOrVectorConst(SDValue V) {
54467   return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
54468 }
54469 
54470 /// If a value is a scalar FP zero or a vector FP zero (potentially including
54471 /// undefined elements), return a zero constant that may be used to fold away
54472 /// that value. In the case of a vector, the returned constant will not contain
54473 /// undefined elements even if the input parameter does. This makes it suitable
54474 /// to be used as a replacement operand with operations (eg, bitwise-and) where
54475 /// an undef should not propagate.
54476 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
54477                                         const X86Subtarget &Subtarget) {
54478   if (!isNullFPScalarOrVectorConst(V))
54479     return SDValue();
54480 
54481   if (V.getValueType().isVector())
54482     return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
54483 
54484   return V;
54485 }
54486 
54487 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
54488                                       const X86Subtarget &Subtarget) {
54489   SDValue N0 = N->getOperand(0);
54490   SDValue N1 = N->getOperand(1);
54491   EVT VT = N->getValueType(0);
54492   SDLoc DL(N);
54493 
54494   // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
54495   if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
54496         (VT == MVT::f64 && Subtarget.hasSSE2()) ||
54497         (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
54498     return SDValue();
54499 
54500   auto isAllOnesConstantFP = [](SDValue V) {
54501     if (V.getSimpleValueType().isVector())
54502       return ISD::isBuildVectorAllOnes(V.getNode());
54503     auto *C = dyn_cast<ConstantFPSDNode>(V);
54504     return C && C->getConstantFPValue()->isAllOnesValue();
54505   };
54506 
54507   // fand (fxor X, -1), Y --> fandn X, Y
54508   if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
54509     return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
54510 
54511   // fand X, (fxor Y, -1) --> fandn Y, X
54512   if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
54513     return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
54514 
54515   return SDValue();
54516 }
54517 
54518 /// Do target-specific dag combines on X86ISD::FAND nodes.
54519 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
54520                            const X86Subtarget &Subtarget) {
54521   // FAND(0.0, x) -> 0.0
54522   if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
54523     return V;
54524 
54525   // FAND(x, 0.0) -> 0.0
54526   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
54527     return V;
54528 
54529   if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
54530     return V;
54531 
54532   return lowerX86FPLogicOp(N, DAG, Subtarget);
54533 }
54534 
54535 /// Do target-specific dag combines on X86ISD::FANDN nodes.
54536 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
54537                             const X86Subtarget &Subtarget) {
54538   // FANDN(0.0, x) -> x
54539   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
54540     return N->getOperand(1);
54541 
54542   // FANDN(x, 0.0) -> 0.0
54543   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
54544     return V;
54545 
54546   return lowerX86FPLogicOp(N, DAG, Subtarget);
54547 }
54548 
54549 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
54550 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
54551                           TargetLowering::DAGCombinerInfo &DCI,
54552                           const X86Subtarget &Subtarget) {
54553   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
54554 
54555   // F[X]OR(0.0, x) -> x
54556   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
54557     return N->getOperand(1);
54558 
54559   // F[X]OR(x, 0.0) -> x
54560   if (isNullFPScalarOrVectorConst(N->getOperand(1)))
54561     return N->getOperand(0);
54562 
54563   if (SDValue NewVal = combineFneg(N, DAG, DCI, Subtarget))
54564     return NewVal;
54565 
54566   return lowerX86FPLogicOp(N, DAG, Subtarget);
54567 }
54568 
54569 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
54570 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
54571   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
54572 
54573   // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
54574   if (!DAG.getTarget().Options.NoNaNsFPMath ||
54575       !DAG.getTarget().Options.NoSignedZerosFPMath)
54576     return SDValue();
54577 
54578   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
54579   // into FMINC and FMAXC, which are Commutative operations.
54580   unsigned NewOp = 0;
54581   switch (N->getOpcode()) {
54582     default: llvm_unreachable("unknown opcode");
54583     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
54584     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
54585   }
54586 
54587   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
54588                      N->getOperand(0), N->getOperand(1));
54589 }
54590 
54591 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
54592                                      const X86Subtarget &Subtarget) {
54593   EVT VT = N->getValueType(0);
54594   if (Subtarget.useSoftFloat() || isSoftF16(VT, Subtarget))
54595     return SDValue();
54596 
54597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54598 
54599   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
54600         (Subtarget.hasSSE2() && VT == MVT::f64) ||
54601         (Subtarget.hasFP16() && VT == MVT::f16) ||
54602         (VT.isVector() && TLI.isTypeLegal(VT))))
54603     return SDValue();
54604 
54605   SDValue Op0 = N->getOperand(0);
54606   SDValue Op1 = N->getOperand(1);
54607   SDLoc DL(N);
54608   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
54609 
54610   // If we don't have to respect NaN inputs, this is a direct translation to x86
54611   // min/max instructions.
54612   if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
54613     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
54614 
54615   // If one of the operands is known non-NaN use the native min/max instructions
54616   // with the non-NaN input as second operand.
54617   if (DAG.isKnownNeverNaN(Op1))
54618     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
54619   if (DAG.isKnownNeverNaN(Op0))
54620     return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
54621 
54622   // If we have to respect NaN inputs, this takes at least 3 instructions.
54623   // Favor a library call when operating on a scalar and minimizing code size.
54624   if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
54625     return SDValue();
54626 
54627   EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
54628                                          VT);
54629 
54630   // There are 4 possibilities involving NaN inputs, and these are the required
54631   // outputs:
54632   //                   Op1
54633   //               Num     NaN
54634   //            ----------------
54635   //       Num  |  Max  |  Op0 |
54636   // Op0        ----------------
54637   //       NaN  |  Op1  |  NaN |
54638   //            ----------------
54639   //
54640   // The SSE FP max/min instructions were not designed for this case, but rather
54641   // to implement:
54642   //   Min = Op1 < Op0 ? Op1 : Op0
54643   //   Max = Op1 > Op0 ? Op1 : Op0
54644   //
54645   // So they always return Op0 if either input is a NaN. However, we can still
54646   // use those instructions for fmaxnum by selecting away a NaN input.
54647 
54648   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
54649   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
54650   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
54651 
54652   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
54653   // are NaN, the NaN value of Op1 is the result.
54654   return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
54655 }
54656 
54657 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
54658                                    TargetLowering::DAGCombinerInfo &DCI) {
54659   EVT VT = N->getValueType(0);
54660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54661 
54662   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
54663   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
54664     return SDValue(N, 0);
54665 
54666   // Convert a full vector load into vzload when not all bits are needed.
54667   SDValue In = N->getOperand(0);
54668   MVT InVT = In.getSimpleValueType();
54669   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
54670       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
54671     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
54672     LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
54673     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
54674     MVT MemVT = MVT::getIntegerVT(NumBits);
54675     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
54676     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
54677       SDLoc dl(N);
54678       SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
54679                                     DAG.getBitcast(InVT, VZLoad));
54680       DCI.CombineTo(N, Convert);
54681       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
54682       DCI.recursivelyDeleteUnusedNodes(LN);
54683       return SDValue(N, 0);
54684     }
54685   }
54686 
54687   return SDValue();
54688 }
54689 
54690 static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
54691                                      TargetLowering::DAGCombinerInfo &DCI) {
54692   bool IsStrict = N->isTargetStrictFPOpcode();
54693   EVT VT = N->getValueType(0);
54694 
54695   // Convert a full vector load into vzload when not all bits are needed.
54696   SDValue In = N->getOperand(IsStrict ? 1 : 0);
54697   MVT InVT = In.getSimpleValueType();
54698   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
54699       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
54700     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
54701     LoadSDNode *LN = cast<LoadSDNode>(In);
54702     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
54703     MVT MemVT = MVT::getFloatingPointVT(NumBits);
54704     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
54705     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
54706       SDLoc dl(N);
54707       if (IsStrict) {
54708         SDValue Convert =
54709             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
54710                         {N->getOperand(0), DAG.getBitcast(InVT, VZLoad)});
54711         DCI.CombineTo(N, Convert, Convert.getValue(1));
54712       } else {
54713         SDValue Convert =
54714             DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(InVT, VZLoad));
54715         DCI.CombineTo(N, Convert);
54716       }
54717       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
54718       DCI.recursivelyDeleteUnusedNodes(LN);
54719       return SDValue(N, 0);
54720     }
54721   }
54722 
54723   return SDValue();
54724 }
54725 
54726 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
54727 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
54728                             TargetLowering::DAGCombinerInfo &DCI,
54729                             const X86Subtarget &Subtarget) {
54730   SDValue N0 = N->getOperand(0);
54731   SDValue N1 = N->getOperand(1);
54732   MVT VT = N->getSimpleValueType(0);
54733   int NumElts = VT.getVectorNumElements();
54734   unsigned EltSizeInBits = VT.getScalarSizeInBits();
54735   SDLoc DL(N);
54736 
54737   // ANDNP(undef, x) -> 0
54738   // ANDNP(x, undef) -> 0
54739   if (N0.isUndef() || N1.isUndef())
54740     return DAG.getConstant(0, DL, VT);
54741 
54742   // ANDNP(0, x) -> x
54743   if (ISD::isBuildVectorAllZeros(N0.getNode()))
54744     return N1;
54745 
54746   // ANDNP(x, 0) -> 0
54747   if (ISD::isBuildVectorAllZeros(N1.getNode()))
54748     return DAG.getConstant(0, DL, VT);
54749 
54750   // ANDNP(x, -1) -> NOT(x) -> XOR(x, -1)
54751   if (ISD::isBuildVectorAllOnes(N1.getNode()))
54752     return DAG.getNOT(DL, N0, VT);
54753 
54754   // Turn ANDNP back to AND if input is inverted.
54755   if (SDValue Not = IsNOT(N0, DAG))
54756     return DAG.getNode(ISD::AND, DL, VT, DAG.getBitcast(VT, Not), N1);
54757 
54758   // Fold for better commutatvity:
54759   // ANDNP(x,NOT(y)) -> AND(NOT(x),NOT(y)) -> NOT(OR(X,Y)).
54760   if (N1->hasOneUse())
54761     if (SDValue Not = IsNOT(N1, DAG))
54762       return DAG.getNOT(
54763           DL, DAG.getNode(ISD::OR, DL, VT, N0, DAG.getBitcast(VT, Not)), VT);
54764 
54765   // Constant Folding
54766   APInt Undefs0, Undefs1;
54767   SmallVector<APInt> EltBits0, EltBits1;
54768   if (getTargetConstantBitsFromNode(N0, EltSizeInBits, Undefs0, EltBits0)) {
54769     if (getTargetConstantBitsFromNode(N1, EltSizeInBits, Undefs1, EltBits1)) {
54770       SmallVector<APInt> ResultBits;
54771       for (int I = 0; I != NumElts; ++I)
54772         ResultBits.push_back(~EltBits0[I] & EltBits1[I]);
54773       return getConstVector(ResultBits, VT, DAG, DL);
54774     }
54775 
54776     // Constant fold NOT(N0) to allow us to use AND.
54777     // Ensure this is only performed if we can confirm that the bitcasted source
54778     // has oneuse to prevent an infinite loop with canonicalizeBitSelect.
54779     if (N0->hasOneUse()) {
54780       SDValue BC0 = peekThroughOneUseBitcasts(N0);
54781       if (BC0.getOpcode() != ISD::BITCAST) {
54782         for (APInt &Elt : EltBits0)
54783           Elt = ~Elt;
54784         SDValue Not = getConstVector(EltBits0, VT, DAG, DL);
54785         return DAG.getNode(ISD::AND, DL, VT, Not, N1);
54786       }
54787     }
54788   }
54789 
54790   // Attempt to recursively combine a bitmask ANDNP with shuffles.
54791   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
54792     SDValue Op(N, 0);
54793     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
54794       return Res;
54795 
54796     // If either operand is a constant mask, then only the elements that aren't
54797     // zero are actually demanded by the other operand.
54798     auto GetDemandedMasks = [&](SDValue Op, bool Invert = false) {
54799       APInt UndefElts;
54800       SmallVector<APInt> EltBits;
54801       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
54802       APInt DemandedElts = APInt::getAllOnes(NumElts);
54803       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
54804                                         EltBits)) {
54805         DemandedBits.clearAllBits();
54806         DemandedElts.clearAllBits();
54807         for (int I = 0; I != NumElts; ++I) {
54808           if (UndefElts[I]) {
54809             // We can't assume an undef src element gives an undef dst - the
54810             // other src might be zero.
54811             DemandedBits.setAllBits();
54812             DemandedElts.setBit(I);
54813           } else if ((Invert && !EltBits[I].isAllOnes()) ||
54814                      (!Invert && !EltBits[I].isZero())) {
54815             DemandedBits |= Invert ? ~EltBits[I] : EltBits[I];
54816             DemandedElts.setBit(I);
54817           }
54818         }
54819       }
54820       return std::make_pair(DemandedBits, DemandedElts);
54821     };
54822     APInt Bits0, Elts0;
54823     APInt Bits1, Elts1;
54824     std::tie(Bits0, Elts0) = GetDemandedMasks(N1);
54825     std::tie(Bits1, Elts1) = GetDemandedMasks(N0, true);
54826 
54827     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54828     if (TLI.SimplifyDemandedVectorElts(N0, Elts0, DCI) ||
54829         TLI.SimplifyDemandedVectorElts(N1, Elts1, DCI) ||
54830         TLI.SimplifyDemandedBits(N0, Bits0, Elts0, DCI) ||
54831         TLI.SimplifyDemandedBits(N1, Bits1, Elts1, DCI)) {
54832       if (N->getOpcode() != ISD::DELETED_NODE)
54833         DCI.AddToWorklist(N);
54834       return SDValue(N, 0);
54835     }
54836   }
54837 
54838   return SDValue();
54839 }
54840 
54841 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
54842                          TargetLowering::DAGCombinerInfo &DCI) {
54843   SDValue N1 = N->getOperand(1);
54844 
54845   // BT ignores high bits in the bit index operand.
54846   unsigned BitWidth = N1.getValueSizeInBits();
54847   APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
54848   if (DAG.getTargetLoweringInfo().SimplifyDemandedBits(N1, DemandedMask, DCI)) {
54849     if (N->getOpcode() != ISD::DELETED_NODE)
54850       DCI.AddToWorklist(N);
54851     return SDValue(N, 0);
54852   }
54853 
54854   return SDValue();
54855 }
54856 
54857 static SDValue combineCVTPH2PS(SDNode *N, SelectionDAG &DAG,
54858                                TargetLowering::DAGCombinerInfo &DCI) {
54859   bool IsStrict = N->getOpcode() == X86ISD::STRICT_CVTPH2PS;
54860   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
54861 
54862   if (N->getValueType(0) == MVT::v4f32 && Src.getValueType() == MVT::v8i16) {
54863     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54864     APInt DemandedElts = APInt::getLowBitsSet(8, 4);
54865     if (TLI.SimplifyDemandedVectorElts(Src, DemandedElts, DCI)) {
54866       if (N->getOpcode() != ISD::DELETED_NODE)
54867         DCI.AddToWorklist(N);
54868       return SDValue(N, 0);
54869     }
54870 
54871     // Convert a full vector load into vzload when not all bits are needed.
54872     if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
54873       LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(IsStrict ? 1 : 0));
54874       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::i64, MVT::v2i64, DAG)) {
54875         SDLoc dl(N);
54876         if (IsStrict) {
54877           SDValue Convert = DAG.getNode(
54878               N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
54879               {N->getOperand(0), DAG.getBitcast(MVT::v8i16, VZLoad)});
54880           DCI.CombineTo(N, Convert, Convert.getValue(1));
54881         } else {
54882           SDValue Convert = DAG.getNode(N->getOpcode(), dl, MVT::v4f32,
54883                                         DAG.getBitcast(MVT::v8i16, VZLoad));
54884           DCI.CombineTo(N, Convert);
54885         }
54886 
54887         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
54888         DCI.recursivelyDeleteUnusedNodes(LN);
54889         return SDValue(N, 0);
54890       }
54891     }
54892   }
54893 
54894   return SDValue();
54895 }
54896 
54897 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
54898 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
54899   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
54900 
54901   EVT DstVT = N->getValueType(0);
54902 
54903   SDValue N0 = N->getOperand(0);
54904   SDValue N1 = N->getOperand(1);
54905   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
54906 
54907   if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
54908     return SDValue();
54909 
54910   // Look through single use any_extends / truncs.
54911   SDValue IntermediateBitwidthOp;
54912   if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
54913       N0.hasOneUse()) {
54914     IntermediateBitwidthOp = N0;
54915     N0 = N0.getOperand(0);
54916   }
54917 
54918   // See if we have a single use cmov.
54919   if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
54920     return SDValue();
54921 
54922   SDValue CMovOp0 = N0.getOperand(0);
54923   SDValue CMovOp1 = N0.getOperand(1);
54924 
54925   // Make sure both operands are constants.
54926   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
54927       !isa<ConstantSDNode>(CMovOp1.getNode()))
54928     return SDValue();
54929 
54930   SDLoc DL(N);
54931 
54932   // If we looked through an any_extend/trunc above, add one to the constants.
54933   if (IntermediateBitwidthOp) {
54934     unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
54935     CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
54936     CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
54937   }
54938 
54939   CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
54940   CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
54941 
54942   EVT CMovVT = DstVT;
54943   // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
54944   if (DstVT == MVT::i16) {
54945     CMovVT = MVT::i32;
54946     CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
54947     CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
54948   }
54949 
54950   SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
54951                              N0.getOperand(2), N0.getOperand(3));
54952 
54953   if (CMovVT != DstVT)
54954     CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
54955 
54956   return CMov;
54957 }
54958 
54959 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
54960                                       const X86Subtarget &Subtarget) {
54961   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
54962 
54963   if (SDValue V = combineSextInRegCmov(N, DAG))
54964     return V;
54965 
54966   EVT VT = N->getValueType(0);
54967   SDValue N0 = N->getOperand(0);
54968   SDValue N1 = N->getOperand(1);
54969   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
54970   SDLoc dl(N);
54971 
54972   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
54973   // both SSE and AVX2 since there is no sign-extended shift right
54974   // operation on a vector with 64-bit elements.
54975   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
54976   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
54977   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
54978                            N0.getOpcode() == ISD::SIGN_EXTEND)) {
54979     SDValue N00 = N0.getOperand(0);
54980 
54981     // EXTLOAD has a better solution on AVX2,
54982     // it may be replaced with X86ISD::VSEXT node.
54983     if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
54984       if (!ISD::isNormalLoad(N00.getNode()))
54985         return SDValue();
54986 
54987     // Attempt to promote any comparison mask ops before moving the
54988     // SIGN_EXTEND_INREG in the way.
54989     if (SDValue Promote = PromoteMaskArithmetic(N0.getNode(), DAG, Subtarget))
54990       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Promote, N1);
54991 
54992     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
54993       SDValue Tmp =
54994           DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, N00, N1);
54995       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
54996     }
54997   }
54998   return SDValue();
54999 }
55000 
55001 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
55002 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
55003 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
55004 /// opportunities to combine math ops, use an LEA, or use a complex addressing
55005 /// mode. This can eliminate extend, add, and shift instructions.
55006 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
55007                                    const X86Subtarget &Subtarget) {
55008   if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
55009       Ext->getOpcode() != ISD::ZERO_EXTEND)
55010     return SDValue();
55011 
55012   // TODO: This should be valid for other integer types.
55013   EVT VT = Ext->getValueType(0);
55014   if (VT != MVT::i64)
55015     return SDValue();
55016 
55017   SDValue Add = Ext->getOperand(0);
55018   if (Add.getOpcode() != ISD::ADD)
55019     return SDValue();
55020 
55021   bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
55022   bool NSW = Add->getFlags().hasNoSignedWrap();
55023   bool NUW = Add->getFlags().hasNoUnsignedWrap();
55024 
55025   // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
55026   // into the 'zext'
55027   if ((Sext && !NSW) || (!Sext && !NUW))
55028     return SDValue();
55029 
55030   // Having a constant operand to the 'add' ensures that we are not increasing
55031   // the instruction count because the constant is extended for free below.
55032   // A constant operand can also become the displacement field of an LEA.
55033   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
55034   if (!AddOp1)
55035     return SDValue();
55036 
55037   // Don't make the 'add' bigger if there's no hope of combining it with some
55038   // other 'add' or 'shl' instruction.
55039   // TODO: It may be profitable to generate simpler LEA instructions in place
55040   // of single 'add' instructions, but the cost model for selecting an LEA
55041   // currently has a high threshold.
55042   bool HasLEAPotential = false;
55043   for (auto *User : Ext->uses()) {
55044     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
55045       HasLEAPotential = true;
55046       break;
55047     }
55048   }
55049   if (!HasLEAPotential)
55050     return SDValue();
55051 
55052   // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
55053   int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
55054   SDValue AddOp0 = Add.getOperand(0);
55055   SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
55056   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
55057 
55058   // The wider add is guaranteed to not wrap because both operands are
55059   // sign-extended.
55060   SDNodeFlags Flags;
55061   Flags.setNoSignedWrap(NSW);
55062   Flags.setNoUnsignedWrap(NUW);
55063   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
55064 }
55065 
55066 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
55067 // operands and the result of CMOV is not used anywhere else - promote CMOV
55068 // itself instead of promoting its result. This could be beneficial, because:
55069 //     1) X86TargetLowering::EmitLoweredSelect later can do merging of two
55070 //        (or more) pseudo-CMOVs only when they go one-after-another and
55071 //        getting rid of result extension code after CMOV will help that.
55072 //     2) Promotion of constant CMOV arguments is free, hence the
55073 //        {ANY,SIGN,ZERO}_EXTEND will just be deleted.
55074 //     3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
55075 //        promotion is also good in terms of code-size.
55076 //        (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
55077 //         promotion).
55078 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
55079   SDValue CMovN = Extend->getOperand(0);
55080   if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
55081     return SDValue();
55082 
55083   EVT TargetVT = Extend->getValueType(0);
55084   unsigned ExtendOpcode = Extend->getOpcode();
55085   SDLoc DL(Extend);
55086 
55087   EVT VT = CMovN.getValueType();
55088   SDValue CMovOp0 = CMovN.getOperand(0);
55089   SDValue CMovOp1 = CMovN.getOperand(1);
55090 
55091   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
55092       !isa<ConstantSDNode>(CMovOp1.getNode()))
55093     return SDValue();
55094 
55095   // Only extend to i32 or i64.
55096   if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
55097     return SDValue();
55098 
55099   // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
55100   // are free.
55101   if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
55102     return SDValue();
55103 
55104   // If this a zero extend to i64, we should only extend to i32 and use a free
55105   // zero extend to finish.
55106   EVT ExtendVT = TargetVT;
55107   if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
55108     ExtendVT = MVT::i32;
55109 
55110   CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
55111   CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
55112 
55113   SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
55114                             CMovN.getOperand(2), CMovN.getOperand(3));
55115 
55116   // Finish extending if needed.
55117   if (ExtendVT != TargetVT)
55118     Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
55119 
55120   return Res;
55121 }
55122 
55123 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
55124 // result type.
55125 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
55126                                const X86Subtarget &Subtarget) {
55127   SDValue N0 = N->getOperand(0);
55128   EVT VT = N->getValueType(0);
55129   SDLoc dl(N);
55130 
55131   // Only do this combine with AVX512 for vector extends.
55132   if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
55133     return SDValue();
55134 
55135   // Only combine legal element types.
55136   EVT SVT = VT.getVectorElementType();
55137   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
55138       SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
55139     return SDValue();
55140 
55141   // We don't have CMPP Instruction for vxf16
55142   if (N0.getOperand(0).getValueType().getVectorElementType() == MVT::f16)
55143     return SDValue();
55144   // We can only do this if the vector size in 256 bits or less.
55145   unsigned Size = VT.getSizeInBits();
55146   if (Size > 256 && Subtarget.useAVX512Regs())
55147     return SDValue();
55148 
55149   // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
55150   // that's the only integer compares with we have.
55151   ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
55152   if (ISD::isUnsignedIntSetCC(CC))
55153     return SDValue();
55154 
55155   // Only do this combine if the extension will be fully consumed by the setcc.
55156   EVT N00VT = N0.getOperand(0).getValueType();
55157   EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
55158   if (Size != MatchingVecType.getSizeInBits())
55159     return SDValue();
55160 
55161   SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
55162 
55163   if (N->getOpcode() == ISD::ZERO_EXTEND)
55164     Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType());
55165 
55166   return Res;
55167 }
55168 
55169 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
55170                            TargetLowering::DAGCombinerInfo &DCI,
55171                            const X86Subtarget &Subtarget) {
55172   SDValue N0 = N->getOperand(0);
55173   EVT VT = N->getValueType(0);
55174   SDLoc DL(N);
55175 
55176   // (i32 (sext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
55177   if (!DCI.isBeforeLegalizeOps() &&
55178       N0.getOpcode() == X86ISD::SETCC_CARRY) {
55179     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, N0->getOperand(0),
55180                                  N0->getOperand(1));
55181     bool ReplaceOtherUses = !N0.hasOneUse();
55182     DCI.CombineTo(N, Setcc);
55183     // Replace other uses with a truncate of the widened setcc_carry.
55184     if (ReplaceOtherUses) {
55185       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
55186                                   N0.getValueType(), Setcc);
55187       DCI.CombineTo(N0.getNode(), Trunc);
55188     }
55189 
55190     return SDValue(N, 0);
55191   }
55192 
55193   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
55194     return NewCMov;
55195 
55196   if (!DCI.isBeforeLegalizeOps())
55197     return SDValue();
55198 
55199   if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
55200     return V;
55201 
55202   if (SDValue V = combineToExtendBoolVectorInReg(N->getOpcode(), DL, VT, N0,
55203                                                  DAG, DCI, Subtarget))
55204     return V;
55205 
55206   if (VT.isVector()) {
55207     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
55208       return R;
55209 
55210     if (N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG)
55211       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
55212   }
55213 
55214   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
55215     return NewAdd;
55216 
55217   return SDValue();
55218 }
55219 
55220 // Inverting a constant vector is profitable if it can be eliminated and the
55221 // inverted vector is already present in DAG. Otherwise, it will be loaded
55222 // anyway.
55223 //
55224 // We determine which of the values can be completely eliminated and invert it.
55225 // If both are eliminable, select a vector with the first negative element.
55226 static SDValue getInvertedVectorForFMA(SDValue V, SelectionDAG &DAG) {
55227   assert(ISD::isBuildVectorOfConstantFPSDNodes(V.getNode()) &&
55228          "ConstantFP build vector expected");
55229   // Check if we can eliminate V. We assume if a value is only used in FMAs, we
55230   // can eliminate it. Since this function is invoked for each FMA with this
55231   // vector.
55232   auto IsNotFMA = [](SDNode *Use) {
55233     return Use->getOpcode() != ISD::FMA && Use->getOpcode() != ISD::STRICT_FMA;
55234   };
55235   if (llvm::any_of(V->uses(), IsNotFMA))
55236     return SDValue();
55237 
55238   SmallVector<SDValue, 8> Ops;
55239   EVT VT = V.getValueType();
55240   EVT EltVT = VT.getVectorElementType();
55241   for (auto Op : V->op_values()) {
55242     if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
55243       Ops.push_back(DAG.getConstantFP(-Cst->getValueAPF(), SDLoc(Op), EltVT));
55244     } else {
55245       assert(Op.isUndef());
55246       Ops.push_back(DAG.getUNDEF(EltVT));
55247     }
55248   }
55249 
55250   SDNode *NV = DAG.getNodeIfExists(ISD::BUILD_VECTOR, DAG.getVTList(VT), Ops);
55251   if (!NV)
55252     return SDValue();
55253 
55254   // If an inverted version cannot be eliminated, choose it instead of the
55255   // original version.
55256   if (llvm::any_of(NV->uses(), IsNotFMA))
55257     return SDValue(NV, 0);
55258 
55259   // If the inverted version also can be eliminated, we have to consistently
55260   // prefer one of the values. We prefer a constant with a negative value on
55261   // the first place.
55262   // N.B. We need to skip undefs that may precede a value.
55263   for (auto op : V->op_values()) {
55264     if (auto *Cst = dyn_cast<ConstantFPSDNode>(op)) {
55265       if (Cst->isNegative())
55266         return SDValue();
55267       break;
55268     }
55269   }
55270   return SDValue(NV, 0);
55271 }
55272 
55273 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
55274                           TargetLowering::DAGCombinerInfo &DCI,
55275                           const X86Subtarget &Subtarget) {
55276   SDLoc dl(N);
55277   EVT VT = N->getValueType(0);
55278   bool IsStrict = N->isStrictFPOpcode() || N->isTargetStrictFPOpcode();
55279 
55280   // Let legalize expand this if it isn't a legal type yet.
55281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55282   if (!TLI.isTypeLegal(VT))
55283     return SDValue();
55284 
55285   SDValue A = N->getOperand(IsStrict ? 1 : 0);
55286   SDValue B = N->getOperand(IsStrict ? 2 : 1);
55287   SDValue C = N->getOperand(IsStrict ? 3 : 2);
55288 
55289   // If the operation allows fast-math and the target does not support FMA,
55290   // split this into mul+add to avoid libcall(s).
55291   SDNodeFlags Flags = N->getFlags();
55292   if (!IsStrict && Flags.hasAllowReassociation() &&
55293       TLI.isOperationExpand(ISD::FMA, VT)) {
55294     SDValue Fmul = DAG.getNode(ISD::FMUL, dl, VT, A, B, Flags);
55295     return DAG.getNode(ISD::FADD, dl, VT, Fmul, C, Flags);
55296   }
55297 
55298   EVT ScalarVT = VT.getScalarType();
55299   if (((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
55300        !Subtarget.hasAnyFMA()) &&
55301       !(ScalarVT == MVT::f16 && Subtarget.hasFP16()))
55302     return SDValue();
55303 
55304   auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
55305     bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
55306     bool LegalOperations = !DCI.isBeforeLegalizeOps();
55307     if (SDValue NegV = TLI.getCheaperNegatedExpression(V, DAG, LegalOperations,
55308                                                        CodeSize)) {
55309       V = NegV;
55310       return true;
55311     }
55312     // Look through extract_vector_elts. If it comes from an FNEG, create a
55313     // new extract from the FNEG input.
55314     if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
55315         isNullConstant(V.getOperand(1))) {
55316       SDValue Vec = V.getOperand(0);
55317       if (SDValue NegV = TLI.getCheaperNegatedExpression(
55318               Vec, DAG, LegalOperations, CodeSize)) {
55319         V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
55320                         NegV, V.getOperand(1));
55321         return true;
55322       }
55323     }
55324     // Lookup if there is an inverted version of constant vector V in DAG.
55325     if (ISD::isBuildVectorOfConstantFPSDNodes(V.getNode())) {
55326       if (SDValue NegV = getInvertedVectorForFMA(V, DAG)) {
55327         V = NegV;
55328         return true;
55329       }
55330     }
55331     return false;
55332   };
55333 
55334   // Do not convert the passthru input of scalar intrinsics.
55335   // FIXME: We could allow negations of the lower element only.
55336   bool NegA = invertIfNegative(A);
55337   bool NegB = invertIfNegative(B);
55338   bool NegC = invertIfNegative(C);
55339 
55340   if (!NegA && !NegB && !NegC)
55341     return SDValue();
55342 
55343   unsigned NewOpcode =
55344       negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
55345 
55346   // Propagate fast-math-flags to new FMA node.
55347   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
55348   if (IsStrict) {
55349     assert(N->getNumOperands() == 4 && "Shouldn't be greater than 4");
55350     return DAG.getNode(NewOpcode, dl, {VT, MVT::Other},
55351                        {N->getOperand(0), A, B, C});
55352   } else {
55353     if (N->getNumOperands() == 4)
55354       return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
55355     return DAG.getNode(NewOpcode, dl, VT, A, B, C);
55356   }
55357 }
55358 
55359 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
55360 // Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
55361 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
55362                                TargetLowering::DAGCombinerInfo &DCI) {
55363   SDLoc dl(N);
55364   EVT VT = N->getValueType(0);
55365   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55366   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
55367   bool LegalOperations = !DCI.isBeforeLegalizeOps();
55368 
55369   SDValue N2 = N->getOperand(2);
55370 
55371   SDValue NegN2 =
55372       TLI.getCheaperNegatedExpression(N2, DAG, LegalOperations, CodeSize);
55373   if (!NegN2)
55374     return SDValue();
55375   unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
55376 
55377   if (N->getNumOperands() == 4)
55378     return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
55379                        NegN2, N->getOperand(3));
55380   return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
55381                      NegN2);
55382 }
55383 
55384 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
55385                            TargetLowering::DAGCombinerInfo &DCI,
55386                            const X86Subtarget &Subtarget) {
55387   SDLoc dl(N);
55388   SDValue N0 = N->getOperand(0);
55389   EVT VT = N->getValueType(0);
55390 
55391   // (i32 (aext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
55392   // FIXME: Is this needed? We don't seem to have any tests for it.
55393   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ANY_EXTEND &&
55394       N0.getOpcode() == X86ISD::SETCC_CARRY) {
55395     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, N0->getOperand(0),
55396                                  N0->getOperand(1));
55397     bool ReplaceOtherUses = !N0.hasOneUse();
55398     DCI.CombineTo(N, Setcc);
55399     // Replace other uses with a truncate of the widened setcc_carry.
55400     if (ReplaceOtherUses) {
55401       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
55402                                   N0.getValueType(), Setcc);
55403       DCI.CombineTo(N0.getNode(), Trunc);
55404     }
55405 
55406     return SDValue(N, 0);
55407   }
55408 
55409   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
55410     return NewCMov;
55411 
55412   if (DCI.isBeforeLegalizeOps())
55413     if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
55414       return V;
55415 
55416   if (SDValue V = combineToExtendBoolVectorInReg(N->getOpcode(), dl, VT, N0,
55417                                                  DAG, DCI, Subtarget))
55418     return V;
55419 
55420   if (VT.isVector())
55421     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
55422       return R;
55423 
55424   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
55425     return NewAdd;
55426 
55427   if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
55428     return R;
55429 
55430   // TODO: Combine with any target/faux shuffle.
55431   if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
55432       VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
55433     SDValue N00 = N0.getOperand(0);
55434     SDValue N01 = N0.getOperand(1);
55435     unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
55436     APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
55437     if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
55438         (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
55439       return concatSubVectors(N00, N01, DAG, dl);
55440     }
55441   }
55442 
55443   return SDValue();
55444 }
55445 
55446 /// If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
55447 /// pre-promote its result type since vXi1 vectors don't get promoted
55448 /// during type legalization.
55449 static SDValue truncateAVX512SetCCNoBWI(EVT VT, EVT OpVT, SDValue LHS,
55450                                         SDValue RHS, ISD::CondCode CC,
55451                                         const SDLoc &DL, SelectionDAG &DAG,
55452                                         const X86Subtarget &Subtarget) {
55453   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
55454       VT.getVectorElementType() == MVT::i1 &&
55455       (OpVT.getVectorElementType() == MVT::i8 ||
55456        OpVT.getVectorElementType() == MVT::i16)) {
55457     SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
55458     return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
55459   }
55460   return SDValue();
55461 }
55462 
55463 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
55464                             TargetLowering::DAGCombinerInfo &DCI,
55465                             const X86Subtarget &Subtarget) {
55466   const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
55467   const SDValue LHS = N->getOperand(0);
55468   const SDValue RHS = N->getOperand(1);
55469   EVT VT = N->getValueType(0);
55470   EVT OpVT = LHS.getValueType();
55471   SDLoc DL(N);
55472 
55473   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
55474     if (SDValue V = combineVectorSizedSetCCEquality(VT, LHS, RHS, CC, DL, DAG,
55475                                                     Subtarget))
55476       return V;
55477 
55478     if (VT == MVT::i1) {
55479       X86::CondCode X86CC;
55480       if (SDValue V =
55481               MatchVectorAllEqualTest(LHS, RHS, CC, DL, Subtarget, DAG, X86CC))
55482         return DAG.getNode(ISD::TRUNCATE, DL, VT, getSETCC(X86CC, V, DL, DAG));
55483     }
55484 
55485     if (OpVT.isScalarInteger()) {
55486       // cmpeq(or(X,Y),X) --> cmpeq(and(~X,Y),0)
55487       // cmpne(or(X,Y),X) --> cmpne(and(~X,Y),0)
55488       auto MatchOrCmpEq = [&](SDValue N0, SDValue N1) {
55489         if (N0.getOpcode() == ISD::OR && N0->hasOneUse()) {
55490           if (N0.getOperand(0) == N1)
55491             return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
55492                                N0.getOperand(1));
55493           if (N0.getOperand(1) == N1)
55494             return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
55495                                N0.getOperand(0));
55496         }
55497         return SDValue();
55498       };
55499       if (SDValue AndN = MatchOrCmpEq(LHS, RHS))
55500         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
55501       if (SDValue AndN = MatchOrCmpEq(RHS, LHS))
55502         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
55503 
55504       // cmpeq(and(X,Y),Y) --> cmpeq(and(~X,Y),0)
55505       // cmpne(and(X,Y),Y) --> cmpne(and(~X,Y),0)
55506       auto MatchAndCmpEq = [&](SDValue N0, SDValue N1) {
55507         if (N0.getOpcode() == ISD::AND && N0->hasOneUse()) {
55508           if (N0.getOperand(0) == N1)
55509             return DAG.getNode(ISD::AND, DL, OpVT, N1,
55510                                DAG.getNOT(DL, N0.getOperand(1), OpVT));
55511           if (N0.getOperand(1) == N1)
55512             return DAG.getNode(ISD::AND, DL, OpVT, N1,
55513                                DAG.getNOT(DL, N0.getOperand(0), OpVT));
55514         }
55515         return SDValue();
55516       };
55517       if (SDValue AndN = MatchAndCmpEq(LHS, RHS))
55518         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
55519       if (SDValue AndN = MatchAndCmpEq(RHS, LHS))
55520         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
55521 
55522       // cmpeq(trunc(x),C) --> cmpeq(x,C)
55523       // cmpne(trunc(x),C) --> cmpne(x,C)
55524       // iff x upper bits are zero.
55525       if (LHS.getOpcode() == ISD::TRUNCATE &&
55526           LHS.getOperand(0).getScalarValueSizeInBits() >= 32 &&
55527           isa<ConstantSDNode>(RHS) && !DCI.isBeforeLegalize()) {
55528         EVT SrcVT = LHS.getOperand(0).getValueType();
55529         APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
55530                                                 OpVT.getScalarSizeInBits());
55531         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55532         auto *C = cast<ConstantSDNode>(RHS);
55533         if (DAG.MaskedValueIsZero(LHS.getOperand(0), UpperBits) &&
55534             TLI.isTypeLegal(LHS.getOperand(0).getValueType()))
55535           return DAG.getSetCC(DL, VT, LHS.getOperand(0),
55536                               DAG.getConstant(C->getAPIntValue().zextOrTrunc(
55537                                                   SrcVT.getScalarSizeInBits()),
55538                                               DL, SrcVT),
55539                               CC);
55540       }
55541 
55542       // With C as a power of 2 and C != 0 and C != INT_MIN:
55543       //    icmp eq Abs(X) C ->
55544       //        (icmp eq A, C) | (icmp eq A, -C)
55545       //    icmp ne Abs(X) C ->
55546       //        (icmp ne A, C) & (icmp ne A, -C)
55547       // Both of these patterns can be better optimized in
55548       // DAGCombiner::foldAndOrOfSETCC. Note this only applies for scalar
55549       // integers which is checked above.
55550       if (LHS.getOpcode() == ISD::ABS && LHS.hasOneUse()) {
55551         if (auto *C = dyn_cast<ConstantSDNode>(RHS)) {
55552           const APInt &CInt = C->getAPIntValue();
55553           // We can better optimize this case in DAGCombiner::foldAndOrOfSETCC.
55554           if (CInt.isPowerOf2() && !CInt.isMinSignedValue()) {
55555             SDValue BaseOp = LHS.getOperand(0);
55556             SDValue SETCC0 = DAG.getSetCC(DL, VT, BaseOp, RHS, CC);
55557             SDValue SETCC1 = DAG.getSetCC(
55558                 DL, VT, BaseOp, DAG.getConstant(-CInt, DL, OpVT), CC);
55559             return DAG.getNode(CC == ISD::SETEQ ? ISD::OR : ISD::AND, DL, VT,
55560                                SETCC0, SETCC1);
55561           }
55562         }
55563       }
55564     }
55565   }
55566 
55567   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
55568       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
55569     // Using temporaries to avoid messing up operand ordering for later
55570     // transformations if this doesn't work.
55571     SDValue Op0 = LHS;
55572     SDValue Op1 = RHS;
55573     ISD::CondCode TmpCC = CC;
55574     // Put build_vector on the right.
55575     if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
55576       std::swap(Op0, Op1);
55577       TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
55578     }
55579 
55580     bool IsSEXT0 =
55581         (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
55582         (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
55583     bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
55584 
55585     if (IsSEXT0 && IsVZero1) {
55586       assert(VT == Op0.getOperand(0).getValueType() &&
55587              "Unexpected operand type");
55588       if (TmpCC == ISD::SETGT)
55589         return DAG.getConstant(0, DL, VT);
55590       if (TmpCC == ISD::SETLE)
55591         return DAG.getConstant(1, DL, VT);
55592       if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
55593         return DAG.getNOT(DL, Op0.getOperand(0), VT);
55594 
55595       assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&
55596              "Unexpected condition code!");
55597       return Op0.getOperand(0);
55598     }
55599   }
55600 
55601   // Try and make unsigned vector comparison signed. On pre AVX512 targets there
55602   // only are unsigned comparisons (`PCMPGT`) and on AVX512 its often better to
55603   // use `PCMPGT` if the result is mean to stay in a vector (and if its going to
55604   // a mask, there are signed AVX512 comparisons).
55605   if (VT.isVector() && OpVT.isVector() && OpVT.isInteger()) {
55606     bool CanMakeSigned = false;
55607     if (ISD::isUnsignedIntSetCC(CC)) {
55608       KnownBits CmpKnown =
55609           DAG.computeKnownBits(LHS).intersectWith(DAG.computeKnownBits(RHS));
55610       // If we know LHS/RHS share the same sign bit at each element we can
55611       // make this signed.
55612       // NOTE: `computeKnownBits` on a vector type aggregates common bits
55613       // across all lanes. So a pattern where the sign varies from lane to
55614       // lane, but at each lane Sign(LHS) is known to equal Sign(RHS), will be
55615       // missed. We could get around this by demanding each lane
55616       // independently, but this isn't the most important optimization and
55617       // that may eat into compile time.
55618       CanMakeSigned =
55619           CmpKnown.Zero.isSignBitSet() || CmpKnown.One.isSignBitSet();
55620     }
55621     if (CanMakeSigned || ISD::isSignedIntSetCC(CC)) {
55622       SDValue LHSOut = LHS;
55623       SDValue RHSOut = RHS;
55624       ISD::CondCode NewCC = CC;
55625       switch (CC) {
55626       case ISD::SETGE:
55627       case ISD::SETUGE:
55628         if (SDValue NewLHS = incDecVectorConstant(LHS, DAG, /*IsInc*/ true,
55629                                                   /*NSW*/ true))
55630           LHSOut = NewLHS;
55631         else if (SDValue NewRHS = incDecVectorConstant(
55632                      RHS, DAG, /*IsInc*/ false, /*NSW*/ true))
55633           RHSOut = NewRHS;
55634         else
55635           break;
55636 
55637         [[fallthrough]];
55638       case ISD::SETUGT:
55639         NewCC = ISD::SETGT;
55640         break;
55641 
55642       case ISD::SETLE:
55643       case ISD::SETULE:
55644         if (SDValue NewLHS = incDecVectorConstant(LHS, DAG, /*IsInc*/ false,
55645                                                   /*NSW*/ true))
55646           LHSOut = NewLHS;
55647         else if (SDValue NewRHS = incDecVectorConstant(RHS, DAG, /*IsInc*/ true,
55648                                                        /*NSW*/ true))
55649           RHSOut = NewRHS;
55650         else
55651           break;
55652 
55653         [[fallthrough]];
55654       case ISD::SETULT:
55655         // Will be swapped to SETGT in LowerVSETCC*.
55656         NewCC = ISD::SETLT;
55657         break;
55658       default:
55659         break;
55660       }
55661       if (NewCC != CC) {
55662         if (SDValue R = truncateAVX512SetCCNoBWI(VT, OpVT, LHSOut, RHSOut,
55663                                                  NewCC, DL, DAG, Subtarget))
55664           return R;
55665         return DAG.getSetCC(DL, VT, LHSOut, RHSOut, NewCC);
55666       }
55667     }
55668   }
55669 
55670   if (SDValue R =
55671           truncateAVX512SetCCNoBWI(VT, OpVT, LHS, RHS, CC, DL, DAG, Subtarget))
55672     return R;
55673 
55674   // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
55675   // to avoid scalarization via legalization because v4i32 is not a legal type.
55676   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
55677       LHS.getValueType() == MVT::v4f32)
55678     return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
55679 
55680   // X pred 0.0 --> X pred -X
55681   // If the negation of X already exists, use it in the comparison. This removes
55682   // the need to materialize 0.0 and allows matching to SSE's MIN/MAX
55683   // instructions in patterns with a 'select' node.
55684   if (isNullFPScalarOrVectorConst(RHS)) {
55685     SDVTList FNegVT = DAG.getVTList(OpVT);
55686     if (SDNode *FNeg = DAG.getNodeIfExists(ISD::FNEG, FNegVT, {LHS}))
55687       return DAG.getSetCC(DL, VT, LHS, SDValue(FNeg, 0), CC);
55688   }
55689 
55690   return SDValue();
55691 }
55692 
55693 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
55694                              TargetLowering::DAGCombinerInfo &DCI,
55695                              const X86Subtarget &Subtarget) {
55696   SDValue Src = N->getOperand(0);
55697   MVT SrcVT = Src.getSimpleValueType();
55698   MVT VT = N->getSimpleValueType(0);
55699   unsigned NumBits = VT.getScalarSizeInBits();
55700   unsigned NumElts = SrcVT.getVectorNumElements();
55701   unsigned NumBitsPerElt = SrcVT.getScalarSizeInBits();
55702   assert(VT == MVT::i32 && NumElts <= NumBits && "Unexpected MOVMSK types");
55703 
55704   // Perform constant folding.
55705   APInt UndefElts;
55706   SmallVector<APInt, 32> EltBits;
55707   if (getTargetConstantBitsFromNode(Src, NumBitsPerElt, UndefElts, EltBits)) {
55708     APInt Imm(32, 0);
55709     for (unsigned Idx = 0; Idx != NumElts; ++Idx)
55710       if (!UndefElts[Idx] && EltBits[Idx].isNegative())
55711         Imm.setBit(Idx);
55712 
55713     return DAG.getConstant(Imm, SDLoc(N), VT);
55714   }
55715 
55716   // Look through int->fp bitcasts that don't change the element width.
55717   unsigned EltWidth = SrcVT.getScalarSizeInBits();
55718   if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
55719       Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
55720     return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
55721 
55722   // Fold movmsk(not(x)) -> not(movmsk(x)) to improve folding of movmsk results
55723   // with scalar comparisons.
55724   if (SDValue NotSrc = IsNOT(Src, DAG)) {
55725     SDLoc DL(N);
55726     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
55727     NotSrc = DAG.getBitcast(SrcVT, NotSrc);
55728     return DAG.getNode(ISD::XOR, DL, VT,
55729                        DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
55730                        DAG.getConstant(NotMask, DL, VT));
55731   }
55732 
55733   // Fold movmsk(icmp_sgt(x,-1)) -> not(movmsk(x)) to improve folding of movmsk
55734   // results with scalar comparisons.
55735   if (Src.getOpcode() == X86ISD::PCMPGT &&
55736       ISD::isBuildVectorAllOnes(Src.getOperand(1).getNode())) {
55737     SDLoc DL(N);
55738     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
55739     return DAG.getNode(ISD::XOR, DL, VT,
55740                        DAG.getNode(X86ISD::MOVMSK, DL, VT, Src.getOperand(0)),
55741                        DAG.getConstant(NotMask, DL, VT));
55742   }
55743 
55744   // Fold movmsk(icmp_eq(and(x,c1),c1)) -> movmsk(shl(x,c2))
55745   // Fold movmsk(icmp_eq(and(x,c1),0)) -> movmsk(not(shl(x,c2)))
55746   // iff pow2splat(c1).
55747   // Use KnownBits to determine if only a single bit is non-zero
55748   // in each element (pow2 or zero), and shift that bit to the msb.
55749   if (Src.getOpcode() == X86ISD::PCMPEQ) {
55750     KnownBits KnownLHS = DAG.computeKnownBits(Src.getOperand(0));
55751     KnownBits KnownRHS = DAG.computeKnownBits(Src.getOperand(1));
55752     unsigned ShiftAmt = KnownLHS.countMinLeadingZeros();
55753     if (KnownLHS.countMaxPopulation() == 1 &&
55754         (KnownRHS.isZero() || (KnownRHS.countMaxPopulation() == 1 &&
55755                                ShiftAmt == KnownRHS.countMinLeadingZeros()))) {
55756       SDLoc DL(N);
55757       MVT ShiftVT = SrcVT;
55758       SDValue ShiftLHS = Src.getOperand(0);
55759       SDValue ShiftRHS = Src.getOperand(1);
55760       if (ShiftVT.getScalarType() == MVT::i8) {
55761         // vXi8 shifts - we only care about the signbit so can use PSLLW.
55762         ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
55763         ShiftLHS = DAG.getBitcast(ShiftVT, ShiftLHS);
55764         ShiftRHS = DAG.getBitcast(ShiftVT, ShiftRHS);
55765       }
55766       ShiftLHS = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, ShiftVT,
55767                                             ShiftLHS, ShiftAmt, DAG);
55768       ShiftRHS = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, ShiftVT,
55769                                             ShiftRHS, ShiftAmt, DAG);
55770       ShiftLHS = DAG.getBitcast(SrcVT, ShiftLHS);
55771       ShiftRHS = DAG.getBitcast(SrcVT, ShiftRHS);
55772       SDValue Res = DAG.getNode(ISD::XOR, DL, SrcVT, ShiftLHS, ShiftRHS);
55773       return DAG.getNode(X86ISD::MOVMSK, DL, VT, DAG.getNOT(DL, Res, SrcVT));
55774     }
55775   }
55776 
55777   // Fold movmsk(logic(X,C)) -> logic(movmsk(X),C)
55778   if (N->isOnlyUserOf(Src.getNode())) {
55779     SDValue SrcBC = peekThroughOneUseBitcasts(Src);
55780     if (ISD::isBitwiseLogicOp(SrcBC.getOpcode())) {
55781       APInt UndefElts;
55782       SmallVector<APInt, 32> EltBits;
55783       if (getTargetConstantBitsFromNode(SrcBC.getOperand(1), NumBitsPerElt,
55784                                         UndefElts, EltBits)) {
55785         APInt Mask = APInt::getZero(NumBits);
55786         for (unsigned Idx = 0; Idx != NumElts; ++Idx) {
55787           if (!UndefElts[Idx] && EltBits[Idx].isNegative())
55788             Mask.setBit(Idx);
55789         }
55790         SDLoc DL(N);
55791         SDValue NewSrc = DAG.getBitcast(SrcVT, SrcBC.getOperand(0));
55792         SDValue NewMovMsk = DAG.getNode(X86ISD::MOVMSK, DL, VT, NewSrc);
55793         return DAG.getNode(SrcBC.getOpcode(), DL, VT, NewMovMsk,
55794                            DAG.getConstant(Mask, DL, VT));
55795       }
55796     }
55797   }
55798 
55799   // Simplify the inputs.
55800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55801   APInt DemandedMask(APInt::getAllOnes(NumBits));
55802   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
55803     return SDValue(N, 0);
55804 
55805   return SDValue();
55806 }
55807 
55808 static SDValue combineTESTP(SDNode *N, SelectionDAG &DAG,
55809                             TargetLowering::DAGCombinerInfo &DCI,
55810                             const X86Subtarget &Subtarget) {
55811   MVT VT = N->getSimpleValueType(0);
55812   unsigned NumBits = VT.getScalarSizeInBits();
55813 
55814   // Simplify the inputs.
55815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55816   APInt DemandedMask(APInt::getAllOnes(NumBits));
55817   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
55818     return SDValue(N, 0);
55819 
55820   return SDValue();
55821 }
55822 
55823 static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
55824                                        TargetLowering::DAGCombinerInfo &DCI,
55825                                        const X86Subtarget &Subtarget) {
55826   auto *MemOp = cast<X86MaskedGatherScatterSDNode>(N);
55827   SDValue BasePtr = MemOp->getBasePtr();
55828   SDValue Index = MemOp->getIndex();
55829   SDValue Scale = MemOp->getScale();
55830   SDValue Mask = MemOp->getMask();
55831 
55832   // Attempt to fold an index scale into the scale value directly.
55833   // For smaller indices, implicit sext is performed BEFORE scale, preventing
55834   // this fold under most circumstances.
55835   // TODO: Move this into X86DAGToDAGISel::matchVectorAddressRecursively?
55836   if ((Index.getOpcode() == X86ISD::VSHLI ||
55837        (Index.getOpcode() == ISD::ADD &&
55838         Index.getOperand(0) == Index.getOperand(1))) &&
55839       isa<ConstantSDNode>(Scale) &&
55840       BasePtr.getScalarValueSizeInBits() == Index.getScalarValueSizeInBits()) {
55841     unsigned ShiftAmt =
55842         Index.getOpcode() == ISD::ADD ? 1 : Index.getConstantOperandVal(1);
55843     uint64_t ScaleAmt = cast<ConstantSDNode>(Scale)->getZExtValue();
55844     uint64_t NewScaleAmt = ScaleAmt * (1ULL << ShiftAmt);
55845     if (isPowerOf2_64(NewScaleAmt) && NewScaleAmt <= 8) {
55846       SDValue NewIndex = Index.getOperand(0);
55847       SDValue NewScale =
55848           DAG.getTargetConstant(NewScaleAmt, SDLoc(N), Scale.getValueType());
55849       if (N->getOpcode() == X86ISD::MGATHER)
55850         return getAVX2GatherNode(N->getOpcode(), SDValue(N, 0), DAG,
55851                                  MemOp->getOperand(1), Mask,
55852                                  MemOp->getBasePtr(), NewIndex, NewScale,
55853                                  MemOp->getChain(), Subtarget);
55854       if (N->getOpcode() == X86ISD::MSCATTER)
55855         return getScatterNode(N->getOpcode(), SDValue(N, 0), DAG,
55856                               MemOp->getOperand(1), Mask, MemOp->getBasePtr(),
55857                               NewIndex, NewScale, MemOp->getChain(), Subtarget);
55858     }
55859   }
55860 
55861   // With vector masks we only demand the upper bit of the mask.
55862   if (Mask.getScalarValueSizeInBits() != 1) {
55863     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55864     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
55865     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
55866       if (N->getOpcode() != ISD::DELETED_NODE)
55867         DCI.AddToWorklist(N);
55868       return SDValue(N, 0);
55869     }
55870   }
55871 
55872   return SDValue();
55873 }
55874 
55875 static SDValue rebuildGatherScatter(MaskedGatherScatterSDNode *GorS,
55876                                     SDValue Index, SDValue Base, SDValue Scale,
55877                                     SelectionDAG &DAG) {
55878   SDLoc DL(GorS);
55879 
55880   if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
55881     SDValue Ops[] = { Gather->getChain(), Gather->getPassThru(),
55882                       Gather->getMask(), Base, Index, Scale } ;
55883     return DAG.getMaskedGather(Gather->getVTList(),
55884                                Gather->getMemoryVT(), DL, Ops,
55885                                Gather->getMemOperand(),
55886                                Gather->getIndexType(),
55887                                Gather->getExtensionType());
55888   }
55889   auto *Scatter = cast<MaskedScatterSDNode>(GorS);
55890   SDValue Ops[] = { Scatter->getChain(), Scatter->getValue(),
55891                     Scatter->getMask(), Base, Index, Scale };
55892   return DAG.getMaskedScatter(Scatter->getVTList(),
55893                               Scatter->getMemoryVT(), DL,
55894                               Ops, Scatter->getMemOperand(),
55895                               Scatter->getIndexType(),
55896                               Scatter->isTruncatingStore());
55897 }
55898 
55899 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
55900                                     TargetLowering::DAGCombinerInfo &DCI) {
55901   SDLoc DL(N);
55902   auto *GorS = cast<MaskedGatherScatterSDNode>(N);
55903   SDValue Index = GorS->getIndex();
55904   SDValue Base = GorS->getBasePtr();
55905   SDValue Scale = GorS->getScale();
55906 
55907   if (DCI.isBeforeLegalize()) {
55908     unsigned IndexWidth = Index.getScalarValueSizeInBits();
55909 
55910     // Shrink constant indices if they are larger than 32-bits.
55911     // Only do this before legalize types since v2i64 could become v2i32.
55912     // FIXME: We could check that the type is legal if we're after legalize
55913     // types, but then we would need to construct test cases where that happens.
55914     // FIXME: We could support more than just constant vectors, but we need to
55915     // careful with costing. A truncate that can be optimized out would be fine.
55916     // Otherwise we might only want to create a truncate if it avoids a split.
55917     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
55918       if (BV->isConstant() && IndexWidth > 32 &&
55919           DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
55920         EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
55921         Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
55922         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55923       }
55924     }
55925 
55926     // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
55927     // there are sufficient sign bits. Only do this before legalize types to
55928     // avoid creating illegal types in truncate.
55929     if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
55930          Index.getOpcode() == ISD::ZERO_EXTEND) &&
55931         IndexWidth > 32 &&
55932         Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
55933         DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
55934       EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
55935       Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
55936       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55937     }
55938   }
55939 
55940   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55941   EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
55942   // Try to move splat constant adders from the index operand to the base
55943   // pointer operand. Taking care to multiply by the scale. We can only do
55944   // this when index element type is the same as the pointer type.
55945   // Otherwise we need to be sure the math doesn't wrap before the scale.
55946   if (Index.getOpcode() == ISD::ADD &&
55947       Index.getValueType().getVectorElementType() == PtrVT &&
55948       isa<ConstantSDNode>(Scale)) {
55949     uint64_t ScaleAmt = cast<ConstantSDNode>(Scale)->getZExtValue();
55950     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index.getOperand(1))) {
55951       BitVector UndefElts;
55952       if (ConstantSDNode *C = BV->getConstantSplatNode(&UndefElts)) {
55953         // FIXME: Allow non-constant?
55954         if (UndefElts.none()) {
55955           // Apply the scale.
55956           APInt Adder = C->getAPIntValue() * ScaleAmt;
55957           // Add it to the existing base.
55958           Base = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
55959                              DAG.getConstant(Adder, DL, PtrVT));
55960           Index = Index.getOperand(0);
55961           return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55962         }
55963       }
55964 
55965       // It's also possible base is just a constant. In that case, just
55966       // replace it with 0 and move the displacement into the index.
55967       if (BV->isConstant() && isa<ConstantSDNode>(Base) &&
55968           isOneConstant(Scale)) {
55969         SDValue Splat = DAG.getSplatBuildVector(Index.getValueType(), DL, Base);
55970         // Combine the constant build_vector and the constant base.
55971         Splat = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
55972                             Index.getOperand(1), Splat);
55973         // Add to the LHS of the original Index add.
55974         Index = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
55975                             Index.getOperand(0), Splat);
55976         Base = DAG.getConstant(0, DL, Base.getValueType());
55977         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55978       }
55979     }
55980   }
55981 
55982   if (DCI.isBeforeLegalizeOps()) {
55983     unsigned IndexWidth = Index.getScalarValueSizeInBits();
55984 
55985     // Make sure the index is either i32 or i64
55986     if (IndexWidth != 32 && IndexWidth != 64) {
55987       MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
55988       EVT IndexVT = Index.getValueType().changeVectorElementType(EltVT);
55989       Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
55990       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55991     }
55992   }
55993 
55994   // With vector masks we only demand the upper bit of the mask.
55995   SDValue Mask = GorS->getMask();
55996   if (Mask.getScalarValueSizeInBits() != 1) {
55997     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55998     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
55999     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
56000       if (N->getOpcode() != ISD::DELETED_NODE)
56001         DCI.AddToWorklist(N);
56002       return SDValue(N, 0);
56003     }
56004   }
56005 
56006   return SDValue();
56007 }
56008 
56009 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
56010 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
56011                                const X86Subtarget &Subtarget) {
56012   SDLoc DL(N);
56013   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
56014   SDValue EFLAGS = N->getOperand(1);
56015 
56016   // Try to simplify the EFLAGS and condition code operands.
56017   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
56018     return getSETCC(CC, Flags, DL, DAG);
56019 
56020   return SDValue();
56021 }
56022 
56023 /// Optimize branch condition evaluation.
56024 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
56025                              const X86Subtarget &Subtarget) {
56026   SDLoc DL(N);
56027   SDValue EFLAGS = N->getOperand(3);
56028   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
56029 
56030   // Try to simplify the EFLAGS and condition code operands.
56031   // Make sure to not keep references to operands, as combineSetCCEFLAGS can
56032   // RAUW them under us.
56033   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
56034     SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
56035     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
56036                        N->getOperand(1), Cond, Flags);
56037   }
56038 
56039   return SDValue();
56040 }
56041 
56042 // TODO: Could we move this to DAGCombine?
56043 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
56044                                                   SelectionDAG &DAG) {
56045   // Take advantage of vector comparisons (etc.) producing 0 or -1 in each lane
56046   // to optimize away operation when it's from a constant.
56047   //
56048   // The general transformation is:
56049   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
56050   //       AND(VECTOR_CMP(x,y), constant2)
56051   //    constant2 = UNARYOP(constant)
56052 
56053   // Early exit if this isn't a vector operation, the operand of the
56054   // unary operation isn't a bitwise AND, or if the sizes of the operations
56055   // aren't the same.
56056   EVT VT = N->getValueType(0);
56057   bool IsStrict = N->isStrictFPOpcode();
56058   unsigned NumEltBits = VT.getScalarSizeInBits();
56059   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
56060   if (!VT.isVector() || Op0.getOpcode() != ISD::AND ||
56061       DAG.ComputeNumSignBits(Op0.getOperand(0)) != NumEltBits ||
56062       VT.getSizeInBits() != Op0.getValueSizeInBits())
56063     return SDValue();
56064 
56065   // Now check that the other operand of the AND is a constant. We could
56066   // make the transformation for non-constant splats as well, but it's unclear
56067   // that would be a benefit as it would not eliminate any operations, just
56068   // perform one more step in scalar code before moving to the vector unit.
56069   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
56070     // Bail out if the vector isn't a constant.
56071     if (!BV->isConstant())
56072       return SDValue();
56073 
56074     // Everything checks out. Build up the new and improved node.
56075     SDLoc DL(N);
56076     EVT IntVT = BV->getValueType(0);
56077     // Create a new constant of the appropriate type for the transformed
56078     // DAG.
56079     SDValue SourceConst;
56080     if (IsStrict)
56081       SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
56082                                 {N->getOperand(0), SDValue(BV, 0)});
56083     else
56084       SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
56085     // The AND node needs bitcasts to/from an integer vector type around it.
56086     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
56087     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
56088                                  MaskConst);
56089     SDValue Res = DAG.getBitcast(VT, NewAnd);
56090     if (IsStrict)
56091       return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
56092     return Res;
56093   }
56094 
56095   return SDValue();
56096 }
56097 
56098 /// If we are converting a value to floating-point, try to replace scalar
56099 /// truncate of an extracted vector element with a bitcast. This tries to keep
56100 /// the sequence on XMM registers rather than moving between vector and GPRs.
56101 static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
56102   // TODO: This is currently only used by combineSIntToFP, but it is generalized
56103   //       to allow being called by any similar cast opcode.
56104   // TODO: Consider merging this into lowering: vectorizeExtractedCast().
56105   SDValue Trunc = N->getOperand(0);
56106   if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
56107     return SDValue();
56108 
56109   SDValue ExtElt = Trunc.getOperand(0);
56110   if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56111       !isNullConstant(ExtElt.getOperand(1)))
56112     return SDValue();
56113 
56114   EVT TruncVT = Trunc.getValueType();
56115   EVT SrcVT = ExtElt.getValueType();
56116   unsigned DestWidth = TruncVT.getSizeInBits();
56117   unsigned SrcWidth = SrcVT.getSizeInBits();
56118   if (SrcWidth % DestWidth != 0)
56119     return SDValue();
56120 
56121   // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
56122   EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
56123   unsigned VecWidth = SrcVecVT.getSizeInBits();
56124   unsigned NumElts = VecWidth / DestWidth;
56125   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
56126   SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
56127   SDLoc DL(N);
56128   SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
56129                                   BitcastVec, ExtElt.getOperand(1));
56130   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
56131 }
56132 
56133 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
56134                                const X86Subtarget &Subtarget) {
56135   bool IsStrict = N->isStrictFPOpcode();
56136   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
56137   EVT VT = N->getValueType(0);
56138   EVT InVT = Op0.getValueType();
56139 
56140   // UINT_TO_FP(vXi1~15)  -> UINT_TO_FP(ZEXT(vXi1~15  to vXi16))
56141   // UINT_TO_FP(vXi17~31) -> UINT_TO_FP(ZEXT(vXi17~31 to vXi32))
56142   // UINT_TO_FP(vXi33~63) -> UINT_TO_FP(ZEXT(vXi33~63 to vXi64))
56143   if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
56144     unsigned ScalarSize = InVT.getScalarSizeInBits();
56145     if (ScalarSize == 16 || ScalarSize == 32 || ScalarSize >= 64)
56146       return SDValue();
56147     SDLoc dl(N);
56148     EVT DstVT = EVT::getVectorVT(*DAG.getContext(),
56149                                  ScalarSize < 16   ? MVT::i16
56150                                  : ScalarSize < 32 ? MVT::i32
56151                                                    : MVT::i64,
56152                                  InVT.getVectorNumElements());
56153     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
56154     if (IsStrict)
56155       return DAG.getNode(ISD::STRICT_UINT_TO_FP, dl, {VT, MVT::Other},
56156                          {N->getOperand(0), P});
56157     return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
56158   }
56159 
56160   // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
56161   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
56162   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
56163   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
56164       VT.getScalarType() != MVT::f16) {
56165     SDLoc dl(N);
56166     EVT DstVT = InVT.changeVectorElementType(MVT::i32);
56167     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
56168 
56169     // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
56170     if (IsStrict)
56171       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
56172                          {N->getOperand(0), P});
56173     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
56174   }
56175 
56176   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
56177   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
56178   // the optimization here.
56179   if (DAG.SignBitIsZero(Op0)) {
56180     if (IsStrict)
56181       return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
56182                          {N->getOperand(0), Op0});
56183     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
56184   }
56185 
56186   return SDValue();
56187 }
56188 
56189 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
56190                                TargetLowering::DAGCombinerInfo &DCI,
56191                                const X86Subtarget &Subtarget) {
56192   // First try to optimize away the conversion entirely when it's
56193   // conditionally from a constant. Vectors only.
56194   bool IsStrict = N->isStrictFPOpcode();
56195   if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
56196     return Res;
56197 
56198   // Now move on to more general possibilities.
56199   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
56200   EVT VT = N->getValueType(0);
56201   EVT InVT = Op0.getValueType();
56202 
56203   // SINT_TO_FP(vXi1~15)  -> SINT_TO_FP(SEXT(vXi1~15  to vXi16))
56204   // SINT_TO_FP(vXi17~31) -> SINT_TO_FP(SEXT(vXi17~31 to vXi32))
56205   // SINT_TO_FP(vXi33~63) -> SINT_TO_FP(SEXT(vXi33~63 to vXi64))
56206   if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
56207     unsigned ScalarSize = InVT.getScalarSizeInBits();
56208     if (ScalarSize == 16 || ScalarSize == 32 || ScalarSize >= 64)
56209       return SDValue();
56210     SDLoc dl(N);
56211     EVT DstVT = EVT::getVectorVT(*DAG.getContext(),
56212                                  ScalarSize < 16   ? MVT::i16
56213                                  : ScalarSize < 32 ? MVT::i32
56214                                                    : MVT::i64,
56215                                  InVT.getVectorNumElements());
56216     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
56217     if (IsStrict)
56218       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
56219                          {N->getOperand(0), P});
56220     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
56221   }
56222 
56223   // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
56224   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
56225   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
56226   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
56227       VT.getScalarType() != MVT::f16) {
56228     SDLoc dl(N);
56229     EVT DstVT = InVT.changeVectorElementType(MVT::i32);
56230     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
56231     if (IsStrict)
56232       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
56233                          {N->getOperand(0), P});
56234     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
56235   }
56236 
56237   // Without AVX512DQ we only support i64 to float scalar conversion. For both
56238   // vectors and scalars, see if we know that the upper bits are all the sign
56239   // bit, in which case we can truncate the input to i32 and convert from that.
56240   if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
56241     unsigned BitWidth = InVT.getScalarSizeInBits();
56242     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
56243     if (NumSignBits >= (BitWidth - 31)) {
56244       EVT TruncVT = MVT::i32;
56245       if (InVT.isVector())
56246         TruncVT = InVT.changeVectorElementType(TruncVT);
56247       SDLoc dl(N);
56248       if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
56249         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
56250         if (IsStrict)
56251           return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
56252                              {N->getOperand(0), Trunc});
56253         return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
56254       }
56255       // If we're after legalize and the type is v2i32 we need to shuffle and
56256       // use CVTSI2P.
56257       assert(InVT == MVT::v2i64 && "Unexpected VT!");
56258       SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
56259       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
56260                                           { 0, 2, -1, -1 });
56261       if (IsStrict)
56262         return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
56263                            {N->getOperand(0), Shuf});
56264       return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
56265     }
56266   }
56267 
56268   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
56269   // a 32-bit target where SSE doesn't support i64->FP operations.
56270   if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
56271       Op0.getOpcode() == ISD::LOAD) {
56272     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
56273 
56274     // This transformation is not supported if the result type is f16 or f128.
56275     if (VT == MVT::f16 || VT == MVT::f128)
56276       return SDValue();
56277 
56278     // If we have AVX512DQ we can use packed conversion instructions unless
56279     // the VT is f80.
56280     if (Subtarget.hasDQI() && VT != MVT::f80)
56281       return SDValue();
56282 
56283     if (Ld->isSimple() && !VT.isVector() && ISD::isNormalLoad(Op0.getNode()) &&
56284         Op0.hasOneUse() && !Subtarget.is64Bit() && InVT == MVT::i64) {
56285       std::pair<SDValue, SDValue> Tmp =
56286           Subtarget.getTargetLowering()->BuildFILD(
56287               VT, InVT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(),
56288               Ld->getPointerInfo(), Ld->getOriginalAlign(), DAG);
56289       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
56290       return Tmp.first;
56291     }
56292   }
56293 
56294   if (IsStrict)
56295     return SDValue();
56296 
56297   if (SDValue V = combineToFPTruncExtElt(N, DAG))
56298     return V;
56299 
56300   return SDValue();
56301 }
56302 
56303 static bool needCarryOrOverflowFlag(SDValue Flags) {
56304   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
56305 
56306   for (const SDNode *User : Flags->uses()) {
56307     X86::CondCode CC;
56308     switch (User->getOpcode()) {
56309     default:
56310       // Be conservative.
56311       return true;
56312     case X86ISD::SETCC:
56313     case X86ISD::SETCC_CARRY:
56314       CC = (X86::CondCode)User->getConstantOperandVal(0);
56315       break;
56316     case X86ISD::BRCOND:
56317     case X86ISD::CMOV:
56318       CC = (X86::CondCode)User->getConstantOperandVal(2);
56319       break;
56320     }
56321 
56322     switch (CC) {
56323     default: break;
56324     case X86::COND_A: case X86::COND_AE:
56325     case X86::COND_B: case X86::COND_BE:
56326     case X86::COND_O: case X86::COND_NO:
56327     case X86::COND_G: case X86::COND_GE:
56328     case X86::COND_L: case X86::COND_LE:
56329       return true;
56330     }
56331   }
56332 
56333   return false;
56334 }
56335 
56336 static bool onlyZeroFlagUsed(SDValue Flags) {
56337   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
56338 
56339   for (const SDNode *User : Flags->uses()) {
56340     unsigned CCOpNo;
56341     switch (User->getOpcode()) {
56342     default:
56343       // Be conservative.
56344       return false;
56345     case X86ISD::SETCC:
56346     case X86ISD::SETCC_CARRY:
56347       CCOpNo = 0;
56348       break;
56349     case X86ISD::BRCOND:
56350     case X86ISD::CMOV:
56351       CCOpNo = 2;
56352       break;
56353     }
56354 
56355     X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
56356     if (CC != X86::COND_E && CC != X86::COND_NE)
56357       return false;
56358   }
56359 
56360   return true;
56361 }
56362 
56363 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
56364   // Only handle test patterns.
56365   if (!isNullConstant(N->getOperand(1)))
56366     return SDValue();
56367 
56368   // If we have a CMP of a truncated binop, see if we can make a smaller binop
56369   // and use its flags directly.
56370   // TODO: Maybe we should try promoting compares that only use the zero flag
56371   // first if we can prove the upper bits with computeKnownBits?
56372   SDLoc dl(N);
56373   SDValue Op = N->getOperand(0);
56374   EVT VT = Op.getValueType();
56375 
56376   // If we have a constant logical shift that's only used in a comparison
56377   // against zero turn it into an equivalent AND. This allows turning it into
56378   // a TEST instruction later.
56379   if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
56380       Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
56381       onlyZeroFlagUsed(SDValue(N, 0))) {
56382     unsigned BitWidth = VT.getSizeInBits();
56383     const APInt &ShAmt = Op.getConstantOperandAPInt(1);
56384     if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
56385       unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
56386       APInt Mask = Op.getOpcode() == ISD::SRL
56387                        ? APInt::getHighBitsSet(BitWidth, MaskBits)
56388                        : APInt::getLowBitsSet(BitWidth, MaskBits);
56389       if (Mask.isSignedIntN(32)) {
56390         Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
56391                          DAG.getConstant(Mask, dl, VT));
56392         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
56393                            DAG.getConstant(0, dl, VT));
56394       }
56395     }
56396   }
56397 
56398   // Peek through any zero-extend if we're only testing for a zero result.
56399   if (Op.getOpcode() == ISD::ZERO_EXTEND && onlyZeroFlagUsed(SDValue(N, 0))) {
56400     SDValue Src = Op.getOperand(0);
56401     EVT SrcVT = Src.getValueType();
56402     if (SrcVT.getScalarSizeInBits() >= 8 &&
56403         DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
56404       return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Src,
56405                          DAG.getConstant(0, dl, SrcVT));
56406   }
56407 
56408   // Look for a truncate.
56409   if (Op.getOpcode() != ISD::TRUNCATE)
56410     return SDValue();
56411 
56412   SDValue Trunc = Op;
56413   Op = Op.getOperand(0);
56414 
56415   // See if we can compare with zero against the truncation source,
56416   // which should help using the Z flag from many ops. Only do this for
56417   // i32 truncated op to prevent partial-reg compares of promoted ops.
56418   EVT OpVT = Op.getValueType();
56419   APInt UpperBits =
56420       APInt::getBitsSetFrom(OpVT.getSizeInBits(), VT.getSizeInBits());
56421   if (OpVT == MVT::i32 && DAG.MaskedValueIsZero(Op, UpperBits) &&
56422       onlyZeroFlagUsed(SDValue(N, 0))) {
56423     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
56424                        DAG.getConstant(0, dl, OpVT));
56425   }
56426 
56427   // After this the truncate and arithmetic op must have a single use.
56428   if (!Trunc.hasOneUse() || !Op.hasOneUse())
56429       return SDValue();
56430 
56431   unsigned NewOpc;
56432   switch (Op.getOpcode()) {
56433   default: return SDValue();
56434   case ISD::AND:
56435     // Skip and with constant. We have special handling for and with immediate
56436     // during isel to generate test instructions.
56437     if (isa<ConstantSDNode>(Op.getOperand(1)))
56438       return SDValue();
56439     NewOpc = X86ISD::AND;
56440     break;
56441   case ISD::OR:  NewOpc = X86ISD::OR;  break;
56442   case ISD::XOR: NewOpc = X86ISD::XOR; break;
56443   case ISD::ADD:
56444     // If the carry or overflow flag is used, we can't truncate.
56445     if (needCarryOrOverflowFlag(SDValue(N, 0)))
56446       return SDValue();
56447     NewOpc = X86ISD::ADD;
56448     break;
56449   case ISD::SUB:
56450     // If the carry or overflow flag is used, we can't truncate.
56451     if (needCarryOrOverflowFlag(SDValue(N, 0)))
56452       return SDValue();
56453     NewOpc = X86ISD::SUB;
56454     break;
56455   }
56456 
56457   // We found an op we can narrow. Truncate its inputs.
56458   SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
56459   SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
56460 
56461   // Use a X86 specific opcode to avoid DAG combine messing with it.
56462   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
56463   Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
56464 
56465   // For AND, keep a CMP so that we can match the test pattern.
56466   if (NewOpc == X86ISD::AND)
56467     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
56468                        DAG.getConstant(0, dl, VT));
56469 
56470   // Return the flags.
56471   return Op.getValue(1);
56472 }
56473 
56474 static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
56475                                 TargetLowering::DAGCombinerInfo &DCI) {
56476   assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&
56477          "Expected X86ISD::ADD or X86ISD::SUB");
56478 
56479   SDLoc DL(N);
56480   SDValue LHS = N->getOperand(0);
56481   SDValue RHS = N->getOperand(1);
56482   MVT VT = LHS.getSimpleValueType();
56483   bool IsSub = X86ISD::SUB == N->getOpcode();
56484   unsigned GenericOpc = IsSub ? ISD::SUB : ISD::ADD;
56485 
56486   // If we don't use the flag result, simplify back to a generic ADD/SUB.
56487   if (!N->hasAnyUseOfValue(1)) {
56488     SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
56489     return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
56490   }
56491 
56492   // Fold any similar generic ADD/SUB opcodes to reuse this node.
56493   auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
56494     SDValue Ops[] = {N0, N1};
56495     SDVTList VTs = DAG.getVTList(N->getValueType(0));
56496     if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
56497       SDValue Op(N, 0);
56498       if (Negate)
56499         Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
56500       DCI.CombineTo(GenericAddSub, Op);
56501     }
56502   };
56503   MatchGeneric(LHS, RHS, false);
56504   MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
56505 
56506   // TODO: Can we drop the ZeroSecondOpOnly limit? This is to guarantee that the
56507   // EFLAGS result doesn't change.
56508   return combineAddOrSubToADCOrSBB(IsSub, DL, VT, LHS, RHS, DAG,
56509                                    /*ZeroSecondOpOnly*/ true);
56510 }
56511 
56512 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
56513   SDValue LHS = N->getOperand(0);
56514   SDValue RHS = N->getOperand(1);
56515   SDValue BorrowIn = N->getOperand(2);
56516 
56517   if (SDValue Flags = combineCarryThroughADD(BorrowIn, DAG)) {
56518     MVT VT = N->getSimpleValueType(0);
56519     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
56520     return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs, LHS, RHS, Flags);
56521   }
56522 
56523   // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
56524   // iff the flag result is dead.
56525   if (LHS.getOpcode() == ISD::SUB && isNullConstant(RHS) &&
56526       !N->hasAnyUseOfValue(1))
56527     return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), LHS.getOperand(0),
56528                        LHS.getOperand(1), BorrowIn);
56529 
56530   return SDValue();
56531 }
56532 
56533 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
56534 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
56535                           TargetLowering::DAGCombinerInfo &DCI) {
56536   SDValue LHS = N->getOperand(0);
56537   SDValue RHS = N->getOperand(1);
56538   SDValue CarryIn = N->getOperand(2);
56539   auto *LHSC = dyn_cast<ConstantSDNode>(LHS);
56540   auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
56541 
56542   // Canonicalize constant to RHS.
56543   if (LHSC && !RHSC)
56544     return DAG.getNode(X86ISD::ADC, SDLoc(N), N->getVTList(), RHS, LHS,
56545                        CarryIn);
56546 
56547   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
56548   // the result is either zero or one (depending on the input carry bit).
56549   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
56550   if (LHSC && RHSC && LHSC->isZero() && RHSC->isZero() &&
56551       // We don't have a good way to replace an EFLAGS use, so only do this when
56552       // dead right now.
56553       SDValue(N, 1).use_empty()) {
56554     SDLoc DL(N);
56555     EVT VT = N->getValueType(0);
56556     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
56557     SDValue Res1 = DAG.getNode(
56558         ISD::AND, DL, VT,
56559         DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
56560                     DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), CarryIn),
56561         DAG.getConstant(1, DL, VT));
56562     return DCI.CombineTo(N, Res1, CarryOut);
56563   }
56564 
56565   // Fold ADC(C1,C2,Carry) -> ADC(0,C1+C2,Carry)
56566   // iff the flag result is dead.
56567   // TODO: Allow flag result if C1+C2 doesn't signed/unsigned overflow.
56568   if (LHSC && RHSC && !LHSC->isZero() && !N->hasAnyUseOfValue(1)) {
56569     SDLoc DL(N);
56570     APInt Sum = LHSC->getAPIntValue() + RHSC->getAPIntValue();
56571     return DAG.getNode(X86ISD::ADC, DL, N->getVTList(),
56572                        DAG.getConstant(0, DL, LHS.getValueType()),
56573                        DAG.getConstant(Sum, DL, LHS.getValueType()), CarryIn);
56574   }
56575 
56576   if (SDValue Flags = combineCarryThroughADD(CarryIn, DAG)) {
56577     MVT VT = N->getSimpleValueType(0);
56578     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
56579     return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs, LHS, RHS, Flags);
56580   }
56581 
56582   // Fold ADC(ADD(X,Y),0,Carry) -> ADC(X,Y,Carry)
56583   // iff the flag result is dead.
56584   if (LHS.getOpcode() == ISD::ADD && RHSC && RHSC->isZero() &&
56585       !N->hasAnyUseOfValue(1))
56586     return DAG.getNode(X86ISD::ADC, SDLoc(N), N->getVTList(), LHS.getOperand(0),
56587                        LHS.getOperand(1), CarryIn);
56588 
56589   return SDValue();
56590 }
56591 
56592 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
56593                             const SDLoc &DL, EVT VT,
56594                             const X86Subtarget &Subtarget) {
56595   // Example of pattern we try to detect:
56596   // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
56597   //(add (build_vector (extract_elt t, 0),
56598   //                   (extract_elt t, 2),
56599   //                   (extract_elt t, 4),
56600   //                   (extract_elt t, 6)),
56601   //     (build_vector (extract_elt t, 1),
56602   //                   (extract_elt t, 3),
56603   //                   (extract_elt t, 5),
56604   //                   (extract_elt t, 7)))
56605 
56606   if (!Subtarget.hasSSE2())
56607     return SDValue();
56608 
56609   if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
56610       Op1.getOpcode() != ISD::BUILD_VECTOR)
56611     return SDValue();
56612 
56613   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
56614       VT.getVectorNumElements() < 4 ||
56615       !isPowerOf2_32(VT.getVectorNumElements()))
56616     return SDValue();
56617 
56618   // Check if one of Op0,Op1 is of the form:
56619   // (build_vector (extract_elt Mul, 0),
56620   //               (extract_elt Mul, 2),
56621   //               (extract_elt Mul, 4),
56622   //                   ...
56623   // the other is of the form:
56624   // (build_vector (extract_elt Mul, 1),
56625   //               (extract_elt Mul, 3),
56626   //               (extract_elt Mul, 5),
56627   //                   ...
56628   // and identify Mul.
56629   SDValue Mul;
56630   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
56631     SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
56632             Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
56633     // TODO: Be more tolerant to undefs.
56634     if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56635         Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56636         Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56637         Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
56638       return SDValue();
56639     auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
56640     auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
56641     auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
56642     auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
56643     if (!Const0L || !Const1L || !Const0H || !Const1H)
56644       return SDValue();
56645     unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
56646              Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
56647     // Commutativity of mul allows factors of a product to reorder.
56648     if (Idx0L > Idx1L)
56649       std::swap(Idx0L, Idx1L);
56650     if (Idx0H > Idx1H)
56651       std::swap(Idx0H, Idx1H);
56652     // Commutativity of add allows pairs of factors to reorder.
56653     if (Idx0L > Idx0H) {
56654       std::swap(Idx0L, Idx0H);
56655       std::swap(Idx1L, Idx1H);
56656     }
56657     if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
56658         Idx1H != 2 * i + 3)
56659       return SDValue();
56660     if (!Mul) {
56661       // First time an extract_elt's source vector is visited. Must be a MUL
56662       // with 2X number of vector elements than the BUILD_VECTOR.
56663       // Both extracts must be from same MUL.
56664       Mul = Op0L->getOperand(0);
56665       if (Mul->getOpcode() != ISD::MUL ||
56666           Mul.getValueType().getVectorNumElements() != 2 * e)
56667         return SDValue();
56668     }
56669     // Check that the extract is from the same MUL previously seen.
56670     if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
56671         Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
56672       return SDValue();
56673   }
56674 
56675   // Check if the Mul source can be safely shrunk.
56676   ShrinkMode Mode;
56677   if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
56678       Mode == ShrinkMode::MULU16)
56679     return SDValue();
56680 
56681   EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
56682                                  VT.getVectorNumElements() * 2);
56683   SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(0));
56684   SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(1));
56685 
56686   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
56687                          ArrayRef<SDValue> Ops) {
56688     EVT InVT = Ops[0].getValueType();
56689     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
56690     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
56691                                  InVT.getVectorNumElements() / 2);
56692     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
56693   };
56694   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { N0, N1 }, PMADDBuilder);
56695 }
56696 
56697 // Attempt to turn this pattern into PMADDWD.
56698 // (add (mul (sext (build_vector)), (sext (build_vector))),
56699 //      (mul (sext (build_vector)), (sext (build_vector)))
56700 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
56701                               const SDLoc &DL, EVT VT,
56702                               const X86Subtarget &Subtarget) {
56703   if (!Subtarget.hasSSE2())
56704     return SDValue();
56705 
56706   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
56707     return SDValue();
56708 
56709   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
56710       VT.getVectorNumElements() < 4 ||
56711       !isPowerOf2_32(VT.getVectorNumElements()))
56712     return SDValue();
56713 
56714   SDValue N00 = N0.getOperand(0);
56715   SDValue N01 = N0.getOperand(1);
56716   SDValue N10 = N1.getOperand(0);
56717   SDValue N11 = N1.getOperand(1);
56718 
56719   // All inputs need to be sign extends.
56720   // TODO: Support ZERO_EXTEND from known positive?
56721   if (N00.getOpcode() != ISD::SIGN_EXTEND ||
56722       N01.getOpcode() != ISD::SIGN_EXTEND ||
56723       N10.getOpcode() != ISD::SIGN_EXTEND ||
56724       N11.getOpcode() != ISD::SIGN_EXTEND)
56725     return SDValue();
56726 
56727   // Peek through the extends.
56728   N00 = N00.getOperand(0);
56729   N01 = N01.getOperand(0);
56730   N10 = N10.getOperand(0);
56731   N11 = N11.getOperand(0);
56732 
56733   // Must be extending from vXi16.
56734   EVT InVT = N00.getValueType();
56735   if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
56736       N10.getValueType() != InVT || N11.getValueType() != InVT)
56737     return SDValue();
56738 
56739   // All inputs should be build_vectors.
56740   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
56741       N01.getOpcode() != ISD::BUILD_VECTOR ||
56742       N10.getOpcode() != ISD::BUILD_VECTOR ||
56743       N11.getOpcode() != ISD::BUILD_VECTOR)
56744     return SDValue();
56745 
56746   // For each element, we need to ensure we have an odd element from one vector
56747   // multiplied by the odd element of another vector and the even element from
56748   // one of the same vectors being multiplied by the even element from the
56749   // other vector. So we need to make sure for each element i, this operator
56750   // is being performed:
56751   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
56752   SDValue In0, In1;
56753   for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
56754     SDValue N00Elt = N00.getOperand(i);
56755     SDValue N01Elt = N01.getOperand(i);
56756     SDValue N10Elt = N10.getOperand(i);
56757     SDValue N11Elt = N11.getOperand(i);
56758     // TODO: Be more tolerant to undefs.
56759     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56760         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56761         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56762         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
56763       return SDValue();
56764     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
56765     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
56766     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
56767     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
56768     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
56769       return SDValue();
56770     unsigned IdxN00 = ConstN00Elt->getZExtValue();
56771     unsigned IdxN01 = ConstN01Elt->getZExtValue();
56772     unsigned IdxN10 = ConstN10Elt->getZExtValue();
56773     unsigned IdxN11 = ConstN11Elt->getZExtValue();
56774     // Add is commutative so indices can be reordered.
56775     if (IdxN00 > IdxN10) {
56776       std::swap(IdxN00, IdxN10);
56777       std::swap(IdxN01, IdxN11);
56778     }
56779     // N0 indices be the even element. N1 indices must be the next odd element.
56780     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
56781         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
56782       return SDValue();
56783     SDValue N00In = N00Elt.getOperand(0);
56784     SDValue N01In = N01Elt.getOperand(0);
56785     SDValue N10In = N10Elt.getOperand(0);
56786     SDValue N11In = N11Elt.getOperand(0);
56787 
56788     // First time we find an input capture it.
56789     if (!In0) {
56790       In0 = N00In;
56791       In1 = N01In;
56792 
56793       // The input vectors must be at least as wide as the output.
56794       // If they are larger than the output, we extract subvector below.
56795       if (In0.getValueSizeInBits() < VT.getSizeInBits() ||
56796           In1.getValueSizeInBits() < VT.getSizeInBits())
56797         return SDValue();
56798     }
56799     // Mul is commutative so the input vectors can be in any order.
56800     // Canonicalize to make the compares easier.
56801     if (In0 != N00In)
56802       std::swap(N00In, N01In);
56803     if (In0 != N10In)
56804       std::swap(N10In, N11In);
56805     if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
56806       return SDValue();
56807   }
56808 
56809   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
56810                          ArrayRef<SDValue> Ops) {
56811     EVT OpVT = Ops[0].getValueType();
56812     assert(OpVT.getScalarType() == MVT::i16 &&
56813            "Unexpected scalar element type");
56814     assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch");
56815     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
56816                                  OpVT.getVectorNumElements() / 2);
56817     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
56818   };
56819 
56820   // If the output is narrower than an input, extract the low part of the input
56821   // vector.
56822   EVT OutVT16 = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
56823                                VT.getVectorNumElements() * 2);
56824   if (OutVT16.bitsLT(In0.getValueType())) {
56825     In0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In0,
56826                       DAG.getIntPtrConstant(0, DL));
56827   }
56828   if (OutVT16.bitsLT(In1.getValueType())) {
56829     In1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In1,
56830                       DAG.getIntPtrConstant(0, DL));
56831   }
56832   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
56833                           PMADDBuilder);
56834 }
56835 
56836 // ADD(VPMADDWD(X,Y),VPMADDWD(Z,W)) -> VPMADDWD(SHUFFLE(X,Z), SHUFFLE(Y,W))
56837 // If upper element in each pair of both VPMADDWD are zero then we can merge
56838 // the operand elements and use the implicit add of VPMADDWD.
56839 // TODO: Add support for VPMADDUBSW (which isn't commutable).
56840 static SDValue combineAddOfPMADDWD(SelectionDAG &DAG, SDValue N0, SDValue N1,
56841                                    const SDLoc &DL, EVT VT) {
56842   if (N0.getOpcode() != N1.getOpcode() || N0.getOpcode() != X86ISD::VPMADDWD)
56843     return SDValue();
56844 
56845   // TODO: Add 256/512-bit support once VPMADDWD combines with shuffles.
56846   if (VT.getSizeInBits() > 128)
56847     return SDValue();
56848 
56849   unsigned NumElts = VT.getVectorNumElements();
56850   MVT OpVT = N0.getOperand(0).getSimpleValueType();
56851   APInt DemandedBits = APInt::getAllOnes(OpVT.getScalarSizeInBits());
56852   APInt DemandedHiElts = APInt::getSplat(2 * NumElts, APInt(2, 2));
56853 
56854   bool Op0HiZero =
56855       DAG.MaskedValueIsZero(N0.getOperand(0), DemandedBits, DemandedHiElts) ||
56856       DAG.MaskedValueIsZero(N0.getOperand(1), DemandedBits, DemandedHiElts);
56857   bool Op1HiZero =
56858       DAG.MaskedValueIsZero(N1.getOperand(0), DemandedBits, DemandedHiElts) ||
56859       DAG.MaskedValueIsZero(N1.getOperand(1), DemandedBits, DemandedHiElts);
56860 
56861   // TODO: Check for zero lower elements once we have actual codegen that
56862   // creates them.
56863   if (!Op0HiZero || !Op1HiZero)
56864     return SDValue();
56865 
56866   // Create a shuffle mask packing the lower elements from each VPMADDWD.
56867   SmallVector<int> Mask;
56868   for (int i = 0; i != (int)NumElts; ++i) {
56869     Mask.push_back(2 * i);
56870     Mask.push_back(2 * (i + NumElts));
56871   }
56872 
56873   SDValue LHS =
56874       DAG.getVectorShuffle(OpVT, DL, N0.getOperand(0), N1.getOperand(0), Mask);
56875   SDValue RHS =
56876       DAG.getVectorShuffle(OpVT, DL, N0.getOperand(1), N1.getOperand(1), Mask);
56877   return DAG.getNode(X86ISD::VPMADDWD, DL, VT, LHS, RHS);
56878 }
56879 
56880 /// CMOV of constants requires materializing constant operands in registers.
56881 /// Try to fold those constants into an 'add' instruction to reduce instruction
56882 /// count. We do this with CMOV rather the generic 'select' because there are
56883 /// earlier folds that may be used to turn select-of-constants into logic hacks.
56884 static SDValue pushAddIntoCmovOfConsts(SDNode *N, SelectionDAG &DAG,
56885                                        const X86Subtarget &Subtarget) {
56886   // If an operand is zero, add-of-0 gets simplified away, so that's clearly
56887   // better because we eliminate 1-2 instructions. This transform is still
56888   // an improvement without zero operands because we trade 2 move constants and
56889   // 1 add for 2 adds (LEA) as long as the constants can be represented as
56890   // immediate asm operands (fit in 32-bits).
56891   auto isSuitableCmov = [](SDValue V) {
56892     if (V.getOpcode() != X86ISD::CMOV || !V.hasOneUse())
56893       return false;
56894     if (!isa<ConstantSDNode>(V.getOperand(0)) ||
56895         !isa<ConstantSDNode>(V.getOperand(1)))
56896       return false;
56897     return isNullConstant(V.getOperand(0)) || isNullConstant(V.getOperand(1)) ||
56898            (V.getConstantOperandAPInt(0).isSignedIntN(32) &&
56899             V.getConstantOperandAPInt(1).isSignedIntN(32));
56900   };
56901 
56902   // Match an appropriate CMOV as the first operand of the add.
56903   SDValue Cmov = N->getOperand(0);
56904   SDValue OtherOp = N->getOperand(1);
56905   if (!isSuitableCmov(Cmov))
56906     std::swap(Cmov, OtherOp);
56907   if (!isSuitableCmov(Cmov))
56908     return SDValue();
56909 
56910   // Don't remove a load folding opportunity for the add. That would neutralize
56911   // any improvements from removing constant materializations.
56912   if (X86::mayFoldLoad(OtherOp, Subtarget))
56913     return SDValue();
56914 
56915   EVT VT = N->getValueType(0);
56916   SDLoc DL(N);
56917   SDValue FalseOp = Cmov.getOperand(0);
56918   SDValue TrueOp = Cmov.getOperand(1);
56919 
56920   // We will push the add through the select, but we can potentially do better
56921   // if we know there is another add in the sequence and this is pointer math.
56922   // In that case, we can absorb an add into the trailing memory op and avoid
56923   // a 3-operand LEA which is likely slower than a 2-operand LEA.
56924   // TODO: If target has "slow3OpsLEA", do this even without the trailing memop?
56925   if (OtherOp.getOpcode() == ISD::ADD && OtherOp.hasOneUse() &&
56926       !isa<ConstantSDNode>(OtherOp.getOperand(0)) &&
56927       all_of(N->uses(), [&](SDNode *Use) {
56928         auto *MemNode = dyn_cast<MemSDNode>(Use);
56929         return MemNode && MemNode->getBasePtr().getNode() == N;
56930       })) {
56931     // add (cmov C1, C2), add (X, Y) --> add (cmov (add X, C1), (add X, C2)), Y
56932     // TODO: We are arbitrarily choosing op0 as the 1st piece of the sum, but
56933     //       it is possible that choosing op1 might be better.
56934     SDValue X = OtherOp.getOperand(0), Y = OtherOp.getOperand(1);
56935     FalseOp = DAG.getNode(ISD::ADD, DL, VT, X, FalseOp);
56936     TrueOp = DAG.getNode(ISD::ADD, DL, VT, X, TrueOp);
56937     Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp,
56938                        Cmov.getOperand(2), Cmov.getOperand(3));
56939     return DAG.getNode(ISD::ADD, DL, VT, Cmov, Y);
56940   }
56941 
56942   // add (cmov C1, C2), OtherOp --> cmov (add OtherOp, C1), (add OtherOp, C2)
56943   FalseOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, FalseOp);
56944   TrueOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, TrueOp);
56945   return DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp, Cmov.getOperand(2),
56946                      Cmov.getOperand(3));
56947 }
56948 
56949 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
56950                           TargetLowering::DAGCombinerInfo &DCI,
56951                           const X86Subtarget &Subtarget) {
56952   EVT VT = N->getValueType(0);
56953   SDValue Op0 = N->getOperand(0);
56954   SDValue Op1 = N->getOperand(1);
56955   SDLoc DL(N);
56956 
56957   if (SDValue Select = pushAddIntoCmovOfConsts(N, DAG, Subtarget))
56958     return Select;
56959 
56960   if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, DL, VT, Subtarget))
56961     return MAdd;
56962   if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, DL, VT, Subtarget))
56963     return MAdd;
56964   if (SDValue MAdd = combineAddOfPMADDWD(DAG, Op0, Op1, DL, VT))
56965     return MAdd;
56966 
56967   // Try to synthesize horizontal adds from adds of shuffles.
56968   if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
56969     return V;
56970 
56971   // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
56972   // (sub Y, (sext (vXi1 X))).
56973   // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
56974   // generic DAG combine without a legal type check, but adding this there
56975   // caused regressions.
56976   if (VT.isVector()) {
56977     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
56978     if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
56979         Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
56980         TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
56981       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
56982       return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
56983     }
56984 
56985     if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
56986         Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
56987         TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
56988       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
56989       return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
56990     }
56991   }
56992 
56993   // Fold ADD(ADC(Y,0,W),X) -> ADC(X,Y,W)
56994   if (Op0.getOpcode() == X86ISD::ADC && Op0->hasOneUse() &&
56995       X86::isZeroNode(Op0.getOperand(1))) {
56996     assert(!Op0->hasAnyUseOfValue(1) && "Overflow bit in use");
56997     return DAG.getNode(X86ISD::ADC, SDLoc(Op0), Op0->getVTList(), Op1,
56998                        Op0.getOperand(0), Op0.getOperand(2));
56999   }
57000 
57001   return combineAddOrSubToADCOrSBB(N, DAG);
57002 }
57003 
57004 // Try to fold (sub Y, cmovns X, -X) -> (add Y, cmovns -X, X) if the cmov
57005 // condition comes from the subtract node that produced -X. This matches the
57006 // cmov expansion for absolute value. By swapping the operands we convert abs
57007 // to nabs.
57008 static SDValue combineSubABS(SDNode *N, SelectionDAG &DAG) {
57009   SDValue N0 = N->getOperand(0);
57010   SDValue N1 = N->getOperand(1);
57011 
57012   if (N1.getOpcode() != X86ISD::CMOV || !N1.hasOneUse())
57013     return SDValue();
57014 
57015   X86::CondCode CC = (X86::CondCode)N1.getConstantOperandVal(2);
57016   if (CC != X86::COND_S && CC != X86::COND_NS)
57017     return SDValue();
57018 
57019   // Condition should come from a negate operation.
57020   SDValue Cond = N1.getOperand(3);
57021   if (Cond.getOpcode() != X86ISD::SUB || !isNullConstant(Cond.getOperand(0)))
57022     return SDValue();
57023   assert(Cond.getResNo() == 1 && "Unexpected result number");
57024 
57025   // Get the X and -X from the negate.
57026   SDValue NegX = Cond.getValue(0);
57027   SDValue X = Cond.getOperand(1);
57028 
57029   SDValue FalseOp = N1.getOperand(0);
57030   SDValue TrueOp = N1.getOperand(1);
57031 
57032   // Cmov operands should be X and NegX. Order doesn't matter.
57033   if (!(TrueOp == X && FalseOp == NegX) && !(TrueOp == NegX && FalseOp == X))
57034     return SDValue();
57035 
57036   // Build a new CMOV with the operands swapped.
57037   SDLoc DL(N);
57038   MVT VT = N->getSimpleValueType(0);
57039   SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, TrueOp, FalseOp,
57040                              N1.getOperand(2), Cond);
57041   // Convert sub to add.
57042   return DAG.getNode(ISD::ADD, DL, VT, N0, Cmov);
57043 }
57044 
57045 static SDValue combineSubSetcc(SDNode *N, SelectionDAG &DAG) {
57046   SDValue Op0 = N->getOperand(0);
57047   SDValue Op1 = N->getOperand(1);
57048 
57049   // (sub C (zero_extend (setcc)))
57050   // =>
57051   // (add (zero_extend (setcc inverted) C-1))   if C is a nonzero immediate
57052   // Don't disturb (sub 0 setcc), which is easily done with neg.
57053   EVT VT = N->getValueType(0);
57054   auto *Op0C = dyn_cast<ConstantSDNode>(Op0);
57055   if (Op1.getOpcode() == ISD::ZERO_EXTEND && Op1.hasOneUse() && Op0C &&
57056       !Op0C->isZero() && Op1.getOperand(0).getOpcode() == X86ISD::SETCC &&
57057       Op1.getOperand(0).hasOneUse()) {
57058     SDValue SetCC = Op1.getOperand(0);
57059     X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
57060     X86::CondCode NewCC = X86::GetOppositeBranchCondition(CC);
57061     uint64_t NewImm = Op0C->getZExtValue() - 1;
57062     SDLoc DL(Op1);
57063     SDValue NewSetCC = getSETCC(NewCC, SetCC.getOperand(1), DL, DAG);
57064     NewSetCC = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NewSetCC);
57065     return DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(VT, VT), NewSetCC,
57066                        DAG.getConstant(NewImm, DL, VT));
57067   }
57068 
57069   return SDValue();
57070 }
57071 
57072 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
57073                           TargetLowering::DAGCombinerInfo &DCI,
57074                           const X86Subtarget &Subtarget) {
57075   SDValue Op0 = N->getOperand(0);
57076   SDValue Op1 = N->getOperand(1);
57077 
57078   // TODO: Add NoOpaque handling to isConstantIntBuildVectorOrConstantInt.
57079   auto IsNonOpaqueConstant = [&](SDValue Op) {
57080     if (SDNode *C = DAG.isConstantIntBuildVectorOrConstantInt(Op)) {
57081       if (auto *Cst = dyn_cast<ConstantSDNode>(C))
57082         return !Cst->isOpaque();
57083       return true;
57084     }
57085     return false;
57086   };
57087 
57088   // X86 can't encode an immediate LHS of a sub. See if we can push the
57089   // negation into a preceding instruction. If the RHS of the sub is a XOR with
57090   // one use and a constant, invert the immediate, saving one register.
57091   // However, ignore cases where C1 is 0, as those will become a NEG.
57092   // sub(C1, xor(X, C2)) -> add(xor(X, ~C2), C1+1)
57093   if (Op1.getOpcode() == ISD::XOR && IsNonOpaqueConstant(Op0) &&
57094       !isNullConstant(Op0) && IsNonOpaqueConstant(Op1.getOperand(1)) &&
57095       Op1->hasOneUse()) {
57096     SDLoc DL(N);
57097     EVT VT = Op0.getValueType();
57098     SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT, Op1.getOperand(0),
57099                                  DAG.getNOT(SDLoc(Op1), Op1.getOperand(1), VT));
57100     SDValue NewAdd =
57101         DAG.getNode(ISD::ADD, DL, VT, Op0, DAG.getConstant(1, DL, VT));
57102     return DAG.getNode(ISD::ADD, DL, VT, NewXor, NewAdd);
57103   }
57104 
57105   if (SDValue V = combineSubABS(N, DAG))
57106     return V;
57107 
57108   // Try to synthesize horizontal subs from subs of shuffles.
57109   if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
57110     return V;
57111 
57112   // Fold SUB(X,ADC(Y,0,W)) -> SBB(X,Y,W)
57113   if (Op1.getOpcode() == X86ISD::ADC && Op1->hasOneUse() &&
57114       X86::isZeroNode(Op1.getOperand(1))) {
57115     assert(!Op1->hasAnyUseOfValue(1) && "Overflow bit in use");
57116     return DAG.getNode(X86ISD::SBB, SDLoc(Op1), Op1->getVTList(), Op0,
57117                        Op1.getOperand(0), Op1.getOperand(2));
57118   }
57119 
57120   // Fold SUB(X,SBB(Y,Z,W)) -> SUB(ADC(X,Z,W),Y)
57121   // Don't fold to ADC(0,0,W)/SETCC_CARRY pattern which will prevent more folds.
57122   if (Op1.getOpcode() == X86ISD::SBB && Op1->hasOneUse() &&
57123       !(X86::isZeroNode(Op0) && X86::isZeroNode(Op1.getOperand(1)))) {
57124     assert(!Op1->hasAnyUseOfValue(1) && "Overflow bit in use");
57125     SDValue ADC = DAG.getNode(X86ISD::ADC, SDLoc(Op1), Op1->getVTList(), Op0,
57126                               Op1.getOperand(1), Op1.getOperand(2));
57127     return DAG.getNode(ISD::SUB, SDLoc(N), Op0.getValueType(), ADC.getValue(0),
57128                        Op1.getOperand(0));
57129   }
57130 
57131   if (SDValue V = combineXorSubCTLZ(N, DAG, Subtarget))
57132     return V;
57133 
57134   if (SDValue V = combineAddOrSubToADCOrSBB(N, DAG))
57135     return V;
57136 
57137   return combineSubSetcc(N, DAG);
57138 }
57139 
57140 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
57141                                     const X86Subtarget &Subtarget) {
57142   MVT VT = N->getSimpleValueType(0);
57143   SDLoc DL(N);
57144 
57145   if (N->getOperand(0) == N->getOperand(1)) {
57146     if (N->getOpcode() == X86ISD::PCMPEQ)
57147       return DAG.getConstant(-1, DL, VT);
57148     if (N->getOpcode() == X86ISD::PCMPGT)
57149       return DAG.getConstant(0, DL, VT);
57150   }
57151 
57152   return SDValue();
57153 }
57154 
57155 /// Helper that combines an array of subvector ops as if they were the operands
57156 /// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
57157 /// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
57158 static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
57159                                       ArrayRef<SDValue> Ops, SelectionDAG &DAG,
57160                                       TargetLowering::DAGCombinerInfo &DCI,
57161                                       const X86Subtarget &Subtarget) {
57162   assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors");
57163   unsigned EltSizeInBits = VT.getScalarSizeInBits();
57164 
57165   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
57166     return DAG.getUNDEF(VT);
57167 
57168   if (llvm::all_of(Ops, [](SDValue Op) {
57169         return ISD::isBuildVectorAllZeros(Op.getNode());
57170       }))
57171     return getZeroVector(VT, Subtarget, DAG, DL);
57172 
57173   SDValue Op0 = Ops[0];
57174   bool IsSplat = llvm::all_equal(Ops);
57175 
57176   // Repeated subvectors.
57177   if (IsSplat &&
57178       (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
57179     // If this broadcast is inserted into both halves, use a larger broadcast.
57180     if (Op0.getOpcode() == X86ISD::VBROADCAST)
57181       return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
57182 
57183     // If this simple subvector or scalar/subvector broadcast_load is inserted
57184     // into both halves, use a larger broadcast_load. Update other uses to use
57185     // an extracted subvector.
57186     if (ISD::isNormalLoad(Op0.getNode()) ||
57187         Op0.getOpcode() == X86ISD::VBROADCAST_LOAD ||
57188         Op0.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
57189       auto *Mem = cast<MemSDNode>(Op0);
57190       unsigned Opc = Op0.getOpcode() == X86ISD::VBROADCAST_LOAD
57191                          ? X86ISD::VBROADCAST_LOAD
57192                          : X86ISD::SUBV_BROADCAST_LOAD;
57193       if (SDValue BcastLd =
57194               getBROADCAST_LOAD(Opc, DL, VT, Mem->getMemoryVT(), Mem, 0, DAG)) {
57195         SDValue BcastSrc =
57196             extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits());
57197         DAG.ReplaceAllUsesOfValueWith(Op0, BcastSrc);
57198         return BcastLd;
57199       }
57200     }
57201 
57202     // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
57203     if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
57204         (Subtarget.hasAVX2() ||
57205          X86::mayFoldLoadIntoBroadcastFromMem(Op0.getOperand(0),
57206                                               VT.getScalarType(), Subtarget)))
57207       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
57208                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
57209                                      Op0.getOperand(0),
57210                                      DAG.getIntPtrConstant(0, DL)));
57211 
57212     // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
57213     if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
57214         (Subtarget.hasAVX2() ||
57215          (EltSizeInBits >= 32 &&
57216           X86::mayFoldLoad(Op0.getOperand(0), Subtarget))) &&
57217         Op0.getOperand(0).getValueType() == VT.getScalarType())
57218       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
57219 
57220     // concat_vectors(extract_subvector(broadcast(x)),
57221     //                extract_subvector(broadcast(x))) -> broadcast(x)
57222     if (Op0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
57223         Op0.getOperand(0).getValueType() == VT) {
57224       if (Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST ||
57225           Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST_LOAD)
57226         return Op0.getOperand(0);
57227     }
57228   }
57229 
57230   // concat(extract_subvector(v0,c0), extract_subvector(v1,c1)) -> vperm2x128.
57231   // Only concat of subvector high halves which vperm2x128 is best at.
57232   // TODO: This should go in combineX86ShufflesRecursively eventually.
57233   if (VT.is256BitVector() && Ops.size() == 2) {
57234     SDValue Src0 = peekThroughBitcasts(Ops[0]);
57235     SDValue Src1 = peekThroughBitcasts(Ops[1]);
57236     if (Src0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
57237         Src1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
57238       EVT SrcVT0 = Src0.getOperand(0).getValueType();
57239       EVT SrcVT1 = Src1.getOperand(0).getValueType();
57240       unsigned NumSrcElts0 = SrcVT0.getVectorNumElements();
57241       unsigned NumSrcElts1 = SrcVT1.getVectorNumElements();
57242       if (SrcVT0.is256BitVector() && SrcVT1.is256BitVector() &&
57243           Src0.getConstantOperandAPInt(1) == (NumSrcElts0 / 2) &&
57244           Src1.getConstantOperandAPInt(1) == (NumSrcElts1 / 2)) {
57245         return DAG.getNode(X86ISD::VPERM2X128, DL, VT,
57246                            DAG.getBitcast(VT, Src0.getOperand(0)),
57247                            DAG.getBitcast(VT, Src1.getOperand(0)),
57248                            DAG.getTargetConstant(0x31, DL, MVT::i8));
57249       }
57250     }
57251   }
57252 
57253   // Repeated opcode.
57254   // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
57255   // but it currently struggles with different vector widths.
57256   if (llvm::all_of(Ops, [Op0](SDValue Op) {
57257         return Op.getOpcode() == Op0.getOpcode() && Op.hasOneUse();
57258       })) {
57259     auto ConcatSubOperand = [&](EVT VT, ArrayRef<SDValue> SubOps, unsigned I) {
57260       SmallVector<SDValue> Subs;
57261       for (SDValue SubOp : SubOps)
57262         Subs.push_back(SubOp.getOperand(I));
57263       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
57264     };
57265     auto IsConcatFree = [](MVT VT, ArrayRef<SDValue> SubOps, unsigned Op) {
57266       for (unsigned I = 0, E = SubOps.size(); I != E; ++I) {
57267         SDValue Sub = SubOps[I].getOperand(Op);
57268         unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
57269         if (Sub.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
57270             Sub.getOperand(0).getValueType() != VT ||
57271             Sub.getConstantOperandAPInt(1) != (I * NumSubElts))
57272           return false;
57273       }
57274       return true;
57275     };
57276 
57277     unsigned NumOps = Ops.size();
57278     switch (Op0.getOpcode()) {
57279     case X86ISD::VBROADCAST: {
57280       if (!IsSplat && llvm::all_of(Ops, [](SDValue Op) {
57281             return Op.getOperand(0).getValueType().is128BitVector();
57282           })) {
57283         if (VT == MVT::v4f64 || VT == MVT::v4i64)
57284           return DAG.getNode(X86ISD::UNPCKL, DL, VT,
57285                              ConcatSubOperand(VT, Ops, 0),
57286                              ConcatSubOperand(VT, Ops, 0));
57287         // TODO: Add pseudo v8i32 PSHUFD handling to AVX1Only targets.
57288         if (VT == MVT::v8f32 || (VT == MVT::v8i32 && Subtarget.hasInt256()))
57289           return DAG.getNode(VT == MVT::v8f32 ? X86ISD::VPERMILPI
57290                                               : X86ISD::PSHUFD,
57291                              DL, VT, ConcatSubOperand(VT, Ops, 0),
57292                              getV4X86ShuffleImm8ForMask({0, 0, 0, 0}, DL, DAG));
57293       }
57294       break;
57295     }
57296     case X86ISD::MOVDDUP:
57297     case X86ISD::MOVSHDUP:
57298     case X86ISD::MOVSLDUP: {
57299       if (!IsSplat)
57300         return DAG.getNode(Op0.getOpcode(), DL, VT,
57301                            ConcatSubOperand(VT, Ops, 0));
57302       break;
57303     }
57304     case X86ISD::SHUFP: {
57305       // Add SHUFPD support if/when necessary.
57306       if (!IsSplat && VT.getScalarType() == MVT::f32 &&
57307           llvm::all_of(Ops, [Op0](SDValue Op) {
57308             return Op.getOperand(2) == Op0.getOperand(2);
57309           })) {
57310         return DAG.getNode(Op0.getOpcode(), DL, VT,
57311                            ConcatSubOperand(VT, Ops, 0),
57312                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
57313       }
57314       break;
57315     }
57316     case X86ISD::UNPCKH:
57317     case X86ISD::UNPCKL: {
57318       // Don't concatenate build_vector patterns.
57319       if (!IsSplat && VT.getScalarSizeInBits() >= 32 &&
57320           ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57321            (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
57322           none_of(Ops, [](SDValue Op) {
57323             return peekThroughBitcasts(Op.getOperand(0)).getOpcode() ==
57324                        ISD::SCALAR_TO_VECTOR ||
57325                    peekThroughBitcasts(Op.getOperand(1)).getOpcode() ==
57326                        ISD::SCALAR_TO_VECTOR;
57327           })) {
57328         return DAG.getNode(Op0.getOpcode(), DL, VT,
57329                            ConcatSubOperand(VT, Ops, 0),
57330                            ConcatSubOperand(VT, Ops, 1));
57331       }
57332       break;
57333     }
57334     case X86ISD::PSHUFHW:
57335     case X86ISD::PSHUFLW:
57336     case X86ISD::PSHUFD:
57337       if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
57338           Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
57339         return DAG.getNode(Op0.getOpcode(), DL, VT,
57340                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
57341       }
57342       [[fallthrough]];
57343     case X86ISD::VPERMILPI:
57344       if (!IsSplat && VT.getScalarSizeInBits() == 32 &&
57345           (VT.is256BitVector() ||
57346            (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
57347           all_of(Ops, [&Op0](SDValue Op) {
57348             return Op0.getOperand(1) == Op.getOperand(1);
57349           })) {
57350         MVT FloatVT = VT.changeVectorElementType(MVT::f32);
57351         SDValue Res = DAG.getBitcast(FloatVT, ConcatSubOperand(VT, Ops, 0));
57352         Res =
57353             DAG.getNode(X86ISD::VPERMILPI, DL, FloatVT, Res, Op0.getOperand(1));
57354         return DAG.getBitcast(VT, Res);
57355       }
57356       if (!IsSplat && NumOps == 2 && VT == MVT::v4f64) {
57357         uint64_t Idx0 = Ops[0].getConstantOperandVal(1);
57358         uint64_t Idx1 = Ops[1].getConstantOperandVal(1);
57359         uint64_t Idx = ((Idx1 & 3) << 2) | (Idx0 & 3);
57360         return DAG.getNode(Op0.getOpcode(), DL, VT,
57361                            ConcatSubOperand(VT, Ops, 0),
57362                            DAG.getTargetConstant(Idx, DL, MVT::i8));
57363       }
57364       break;
57365     case X86ISD::PSHUFB:
57366     case X86ISD::PSADBW:
57367       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57368                        (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
57369         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
57370         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
57371                                  NumOps * SrcVT.getVectorNumElements());
57372         return DAG.getNode(Op0.getOpcode(), DL, VT,
57373                            ConcatSubOperand(SrcVT, Ops, 0),
57374                            ConcatSubOperand(SrcVT, Ops, 1));
57375       }
57376       break;
57377     case X86ISD::VPERMV:
57378       if (!IsSplat && NumOps == 2 &&
57379           (VT.is512BitVector() && Subtarget.useAVX512Regs())) {
57380         MVT OpVT = Op0.getSimpleValueType();
57381         int NumSrcElts = OpVT.getVectorNumElements();
57382         SmallVector<int, 64> ConcatMask;
57383         for (unsigned i = 0; i != NumOps; ++i) {
57384           SmallVector<int, 64> SubMask;
57385           SmallVector<SDValue, 2> SubOps;
57386           if (!getTargetShuffleMask(Ops[i].getNode(), OpVT, false, SubOps,
57387                                     SubMask))
57388             break;
57389           for (int M : SubMask) {
57390             if (0 <= M)
57391               M += i * NumSrcElts;
57392             ConcatMask.push_back(M);
57393           }
57394         }
57395         if (ConcatMask.size() == (NumOps * NumSrcElts)) {
57396           SDValue Src = concatSubVectors(Ops[0].getOperand(1),
57397                                          Ops[1].getOperand(1), DAG, DL);
57398           MVT IntMaskSVT = MVT::getIntegerVT(EltSizeInBits);
57399           MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
57400           SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
57401           return DAG.getNode(X86ISD::VPERMV, DL, VT, Mask, Src);
57402         }
57403       }
57404       break;
57405     case X86ISD::VPERMV3:
57406       if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
57407         MVT OpVT = Op0.getSimpleValueType();
57408         int NumSrcElts = OpVT.getVectorNumElements();
57409         SmallVector<int, 64> ConcatMask;
57410         for (unsigned i = 0; i != NumOps; ++i) {
57411           SmallVector<int, 64> SubMask;
57412           SmallVector<SDValue, 2> SubOps;
57413           if (!getTargetShuffleMask(Ops[i].getNode(), OpVT, false, SubOps,
57414                                     SubMask))
57415             break;
57416           for (int M : SubMask) {
57417             if (0 <= M) {
57418               M += M < NumSrcElts ? 0 : NumSrcElts;
57419               M += i * NumSrcElts;
57420             }
57421             ConcatMask.push_back(M);
57422           }
57423         }
57424         if (ConcatMask.size() == (NumOps * NumSrcElts)) {
57425           SDValue Src0 = concatSubVectors(Ops[0].getOperand(0),
57426                                           Ops[1].getOperand(0), DAG, DL);
57427           SDValue Src1 = concatSubVectors(Ops[0].getOperand(2),
57428                                           Ops[1].getOperand(2), DAG, DL);
57429           MVT IntMaskSVT = MVT::getIntegerVT(EltSizeInBits);
57430           MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
57431           SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
57432           return DAG.getNode(X86ISD::VPERMV3, DL, VT, Src0, Mask, Src1);
57433         }
57434       }
57435       break;
57436     case ISD::TRUNCATE:
57437       if (!IsSplat && NumOps == 2 && VT.is256BitVector()) {
57438         EVT SrcVT = Ops[0].getOperand(0).getValueType();
57439         if (SrcVT.is256BitVector() && SrcVT.isSimple() &&
57440             SrcVT == Ops[1].getOperand(0).getValueType() &&
57441             Subtarget.useAVX512Regs() &&
57442             Subtarget.getPreferVectorWidth() >= 512 &&
57443             (SrcVT.getScalarSizeInBits() > 16 || Subtarget.useBWIRegs())) {
57444           EVT NewSrcVT = SrcVT.getDoubleNumVectorElementsVT(*DAG.getContext());
57445           return DAG.getNode(ISD::TRUNCATE, DL, VT,
57446                              ConcatSubOperand(NewSrcVT, Ops, 0));
57447         }
57448       }
57449       break;
57450     case X86ISD::VSHLI:
57451     case X86ISD::VSRLI:
57452       // Special case: SHL/SRL AVX1 V4i64 by 32-bits can lower as a shuffle.
57453       // TODO: Move this to LowerShiftByScalarImmediate?
57454       if (VT == MVT::v4i64 && !Subtarget.hasInt256() &&
57455           llvm::all_of(Ops, [](SDValue Op) {
57456             return Op.getConstantOperandAPInt(1) == 32;
57457           })) {
57458         SDValue Res = DAG.getBitcast(MVT::v8i32, ConcatSubOperand(VT, Ops, 0));
57459         SDValue Zero = getZeroVector(MVT::v8i32, Subtarget, DAG, DL);
57460         if (Op0.getOpcode() == X86ISD::VSHLI) {
57461           Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
57462                                      {8, 0, 8, 2, 8, 4, 8, 6});
57463         } else {
57464           Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
57465                                      {1, 8, 3, 8, 5, 8, 7, 8});
57466         }
57467         return DAG.getBitcast(VT, Res);
57468       }
57469       [[fallthrough]];
57470     case X86ISD::VSRAI:
57471     case X86ISD::VSHL:
57472     case X86ISD::VSRL:
57473     case X86ISD::VSRA:
57474       if (((VT.is256BitVector() && Subtarget.hasInt256()) ||
57475            (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
57476             (EltSizeInBits >= 32 || Subtarget.useBWIRegs()))) &&
57477           llvm::all_of(Ops, [Op0](SDValue Op) {
57478             return Op0.getOperand(1) == Op.getOperand(1);
57479           })) {
57480         return DAG.getNode(Op0.getOpcode(), DL, VT,
57481                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
57482       }
57483       break;
57484     case X86ISD::VPERMI:
57485     case X86ISD::VROTLI:
57486     case X86ISD::VROTRI:
57487       if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
57488           llvm::all_of(Ops, [Op0](SDValue Op) {
57489             return Op0.getOperand(1) == Op.getOperand(1);
57490           })) {
57491         return DAG.getNode(Op0.getOpcode(), DL, VT,
57492                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
57493       }
57494       break;
57495     case ISD::AND:
57496     case ISD::OR:
57497     case ISD::XOR:
57498     case X86ISD::ANDNP:
57499       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57500                        (VT.is512BitVector() && Subtarget.useAVX512Regs()))) {
57501         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
57502         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
57503                                  NumOps * SrcVT.getVectorNumElements());
57504         return DAG.getNode(Op0.getOpcode(), DL, VT,
57505                            ConcatSubOperand(SrcVT, Ops, 0),
57506                            ConcatSubOperand(SrcVT, Ops, 1));
57507       }
57508       break;
57509     case ISD::CTPOP:
57510     case ISD::CTTZ:
57511     case ISD::CTLZ:
57512     case ISD::CTTZ_ZERO_UNDEF:
57513     case ISD::CTLZ_ZERO_UNDEF:
57514       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57515                        (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
57516         return DAG.getNode(Op0.getOpcode(), DL, VT,
57517                            ConcatSubOperand(VT, Ops, 0));
57518       }
57519       break;
57520     case X86ISD::GF2P8AFFINEQB:
57521       if (!IsSplat &&
57522           (VT.is256BitVector() ||
57523            (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
57524           llvm::all_of(Ops, [Op0](SDValue Op) {
57525             return Op0.getOperand(2) == Op.getOperand(2);
57526           })) {
57527         return DAG.getNode(Op0.getOpcode(), DL, VT,
57528                            ConcatSubOperand(VT, Ops, 0),
57529                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
57530       }
57531       break;
57532     case ISD::ADD:
57533     case ISD::SUB:
57534     case ISD::MUL:
57535       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57536                        (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
57537                         (EltSizeInBits >= 32 || Subtarget.useBWIRegs())))) {
57538         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
57539         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
57540                                  NumOps * SrcVT.getVectorNumElements());
57541         return DAG.getNode(Op0.getOpcode(), DL, VT,
57542                            ConcatSubOperand(SrcVT, Ops, 0),
57543                            ConcatSubOperand(SrcVT, Ops, 1));
57544       }
57545       break;
57546     // Due to VADD, VSUB, VMUL can executed on more ports than VINSERT and
57547     // their latency are short, so here we don't replace them.
57548     case ISD::FDIV:
57549       if (!IsSplat && (VT.is256BitVector() ||
57550                        (VT.is512BitVector() && Subtarget.useAVX512Regs()))) {
57551         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
57552         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
57553                                  NumOps * SrcVT.getVectorNumElements());
57554         return DAG.getNode(Op0.getOpcode(), DL, VT,
57555                            ConcatSubOperand(SrcVT, Ops, 0),
57556                            ConcatSubOperand(SrcVT, Ops, 1));
57557       }
57558       break;
57559     case X86ISD::HADD:
57560     case X86ISD::HSUB:
57561     case X86ISD::FHADD:
57562     case X86ISD::FHSUB:
57563     case X86ISD::PACKSS:
57564     case X86ISD::PACKUS:
57565       if (!IsSplat && VT.is256BitVector() &&
57566           (VT.isFloatingPoint() || Subtarget.hasInt256())) {
57567         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
57568         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
57569                                  NumOps * SrcVT.getVectorNumElements());
57570         return DAG.getNode(Op0.getOpcode(), DL, VT,
57571                            ConcatSubOperand(SrcVT, Ops, 0),
57572                            ConcatSubOperand(SrcVT, Ops, 1));
57573       }
57574       break;
57575     case X86ISD::PALIGNR:
57576       if (!IsSplat &&
57577           ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57578            (VT.is512BitVector() && Subtarget.useBWIRegs())) &&
57579           llvm::all_of(Ops, [Op0](SDValue Op) {
57580             return Op0.getOperand(2) == Op.getOperand(2);
57581           })) {
57582         return DAG.getNode(Op0.getOpcode(), DL, VT,
57583                            ConcatSubOperand(VT, Ops, 0),
57584                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
57585       }
57586       break;
57587     case ISD::VSELECT:
57588       if (!IsSplat && Subtarget.hasAVX512() &&
57589           (VT.is256BitVector() ||
57590            (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
57591           (EltSizeInBits >= 32 || Subtarget.hasBWI())) {
57592         EVT SelVT = Ops[0].getOperand(0).getValueType();
57593         if (SelVT.getVectorElementType() == MVT::i1) {
57594           SelVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
57595                                    Ops.size() * SelVT.getVectorNumElements());
57596           if (DAG.getTargetLoweringInfo().isTypeLegal(SelVT))
57597             return DAG.getNode(Op0.getOpcode(), DL, VT,
57598                                ConcatSubOperand(SelVT.getSimpleVT(), Ops, 0),
57599                                ConcatSubOperand(VT, Ops, 1),
57600                                ConcatSubOperand(VT, Ops, 2));
57601         }
57602       }
57603       [[fallthrough]];
57604     case X86ISD::BLENDV:
57605       if (!IsSplat && VT.is256BitVector() && Ops.size() == 2 &&
57606           (EltSizeInBits >= 32 || Subtarget.hasInt256()) &&
57607           IsConcatFree(VT, Ops, 1) && IsConcatFree(VT, Ops, 2)) {
57608         EVT SelVT = Ops[0].getOperand(0).getValueType();
57609         SelVT = SelVT.getDoubleNumVectorElementsVT(*DAG.getContext());
57610         if (DAG.getTargetLoweringInfo().isTypeLegal(SelVT))
57611           return DAG.getNode(Op0.getOpcode(), DL, VT,
57612                              ConcatSubOperand(SelVT.getSimpleVT(), Ops, 0),
57613                              ConcatSubOperand(VT, Ops, 1),
57614                              ConcatSubOperand(VT, Ops, 2));
57615       }
57616       break;
57617     }
57618   }
57619 
57620   // Fold subvector loads into one.
57621   // If needed, look through bitcasts to get to the load.
57622   if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
57623     unsigned Fast;
57624     const X86TargetLowering *TLI = Subtarget.getTargetLowering();
57625     if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
57626                                 *FirstLd->getMemOperand(), &Fast) &&
57627         Fast) {
57628       if (SDValue Ld =
57629               EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
57630         return Ld;
57631     }
57632   }
57633 
57634   // Attempt to fold target constant loads.
57635   if (all_of(Ops, [](SDValue Op) { return getTargetConstantFromNode(Op); })) {
57636     SmallVector<APInt> EltBits;
57637     APInt UndefElts = APInt::getZero(VT.getVectorNumElements());
57638     for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
57639       APInt OpUndefElts;
57640       SmallVector<APInt> OpEltBits;
57641       if (!getTargetConstantBitsFromNode(Ops[I], EltSizeInBits, OpUndefElts,
57642                                         OpEltBits, true, false))
57643           break;
57644       EltBits.append(OpEltBits);
57645       UndefElts.insertBits(OpUndefElts, I * OpUndefElts.getBitWidth());
57646     }
57647     if (EltBits.size() == VT.getVectorNumElements())
57648       return getConstVector(EltBits, UndefElts, VT, DAG, DL);
57649   }
57650 
57651   return SDValue();
57652 }
57653 
57654 static SDValue combineCONCAT_VECTORS(SDNode *N, SelectionDAG &DAG,
57655                                      TargetLowering::DAGCombinerInfo &DCI,
57656                                      const X86Subtarget &Subtarget) {
57657   EVT VT = N->getValueType(0);
57658   EVT SrcVT = N->getOperand(0).getValueType();
57659   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
57660   SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
57661 
57662   if (VT.getVectorElementType() == MVT::i1) {
57663     // Attempt to constant fold.
57664     unsigned SubSizeInBits = SrcVT.getSizeInBits();
57665     APInt Constant = APInt::getZero(VT.getSizeInBits());
57666     for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
57667       auto *C = dyn_cast<ConstantSDNode>(peekThroughBitcasts(Ops[I]));
57668       if (!C) break;
57669       Constant.insertBits(C->getAPIntValue(), I * SubSizeInBits);
57670       if (I == (E - 1)) {
57671         EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
57672         if (TLI.isTypeLegal(IntVT))
57673           return DAG.getBitcast(VT, DAG.getConstant(Constant, SDLoc(N), IntVT));
57674       }
57675     }
57676 
57677     // Don't do anything else for i1 vectors.
57678     return SDValue();
57679   }
57680 
57681   if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
57682     if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
57683                                            DCI, Subtarget))
57684       return R;
57685   }
57686 
57687   return SDValue();
57688 }
57689 
57690 static SDValue combineINSERT_SUBVECTOR(SDNode *N, SelectionDAG &DAG,
57691                                        TargetLowering::DAGCombinerInfo &DCI,
57692                                        const X86Subtarget &Subtarget) {
57693   if (DCI.isBeforeLegalizeOps())
57694     return SDValue();
57695 
57696   MVT OpVT = N->getSimpleValueType(0);
57697 
57698   bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
57699 
57700   SDLoc dl(N);
57701   SDValue Vec = N->getOperand(0);
57702   SDValue SubVec = N->getOperand(1);
57703 
57704   uint64_t IdxVal = N->getConstantOperandVal(2);
57705   MVT SubVecVT = SubVec.getSimpleValueType();
57706 
57707   if (Vec.isUndef() && SubVec.isUndef())
57708     return DAG.getUNDEF(OpVT);
57709 
57710   // Inserting undefs/zeros into zeros/undefs is a zero vector.
57711   if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
57712       (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
57713     return getZeroVector(OpVT, Subtarget, DAG, dl);
57714 
57715   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
57716     // If we're inserting into a zero vector and then into a larger zero vector,
57717     // just insert into the larger zero vector directly.
57718     if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
57719         ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
57720       uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
57721       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
57722                          getZeroVector(OpVT, Subtarget, DAG, dl),
57723                          SubVec.getOperand(1),
57724                          DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
57725     }
57726 
57727     // If we're inserting into a zero vector and our input was extracted from an
57728     // insert into a zero vector of the same type and the extraction was at
57729     // least as large as the original insertion. Just insert the original
57730     // subvector into a zero vector.
57731     if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
57732         isNullConstant(SubVec.getOperand(1)) &&
57733         SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
57734       SDValue Ins = SubVec.getOperand(0);
57735       if (isNullConstant(Ins.getOperand(2)) &&
57736           ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
57737           Ins.getOperand(1).getValueSizeInBits().getFixedValue() <=
57738               SubVecVT.getFixedSizeInBits())
57739           return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
57740                              getZeroVector(OpVT, Subtarget, DAG, dl),
57741                              Ins.getOperand(1), N->getOperand(2));
57742     }
57743   }
57744 
57745   // Stop here if this is an i1 vector.
57746   if (IsI1Vector)
57747     return SDValue();
57748 
57749   // Eliminate an intermediate vector widening:
57750   // insert_subvector X, (insert_subvector undef, Y, 0), Idx -->
57751   // insert_subvector X, Y, Idx
57752   // TODO: This is a more general version of a DAGCombiner fold, can we move it
57753   // there?
57754   if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
57755       SubVec.getOperand(0).isUndef() && isNullConstant(SubVec.getOperand(2)))
57756     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Vec,
57757                        SubVec.getOperand(1), N->getOperand(2));
57758 
57759   // If this is an insert of an extract, combine to a shuffle. Don't do this
57760   // if the insert or extract can be represented with a subregister operation.
57761   if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
57762       SubVec.getOperand(0).getSimpleValueType() == OpVT &&
57763       (IdxVal != 0 ||
57764        !(Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())))) {
57765     int ExtIdxVal = SubVec.getConstantOperandVal(1);
57766     if (ExtIdxVal != 0) {
57767       int VecNumElts = OpVT.getVectorNumElements();
57768       int SubVecNumElts = SubVecVT.getVectorNumElements();
57769       SmallVector<int, 64> Mask(VecNumElts);
57770       // First create an identity shuffle mask.
57771       for (int i = 0; i != VecNumElts; ++i)
57772         Mask[i] = i;
57773       // Now insert the extracted portion.
57774       for (int i = 0; i != SubVecNumElts; ++i)
57775         Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
57776 
57777       return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
57778     }
57779   }
57780 
57781   // Match concat_vector style patterns.
57782   SmallVector<SDValue, 2> SubVectorOps;
57783   if (collectConcatOps(N, SubVectorOps, DAG)) {
57784     if (SDValue Fold =
57785             combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
57786       return Fold;
57787 
57788     // If we're inserting all zeros into the upper half, change this to
57789     // a concat with zero. We will match this to a move
57790     // with implicit upper bit zeroing during isel.
57791     // We do this here because we don't want combineConcatVectorOps to
57792     // create INSERT_SUBVECTOR from CONCAT_VECTORS.
57793     if (SubVectorOps.size() == 2 &&
57794         ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
57795       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
57796                          getZeroVector(OpVT, Subtarget, DAG, dl),
57797                          SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
57798   }
57799 
57800   // If this is a broadcast insert into an upper undef, use a larger broadcast.
57801   if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
57802     return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
57803 
57804   // If this is a broadcast load inserted into an upper undef, use a larger
57805   // broadcast load.
57806   if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
57807       SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
57808     auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
57809     SDVTList Tys = DAG.getVTList(OpVT, MVT::Other);
57810     SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
57811     SDValue BcastLd =
57812         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
57813                                 MemIntr->getMemoryVT(),
57814                                 MemIntr->getMemOperand());
57815     DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
57816     return BcastLd;
57817   }
57818 
57819   // If we're splatting the lower half subvector of a full vector load into the
57820   // upper half, attempt to create a subvector broadcast.
57821   if (IdxVal == (OpVT.getVectorNumElements() / 2) && SubVec.hasOneUse() &&
57822       Vec.getValueSizeInBits() == (2 * SubVec.getValueSizeInBits())) {
57823     auto *VecLd = dyn_cast<LoadSDNode>(Vec);
57824     auto *SubLd = dyn_cast<LoadSDNode>(SubVec);
57825     if (VecLd && SubLd &&
57826         DAG.areNonVolatileConsecutiveLoads(SubLd, VecLd,
57827                                            SubVec.getValueSizeInBits() / 8, 0))
57828       return getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, dl, OpVT, SubVecVT,
57829                                SubLd, 0, DAG);
57830   }
57831 
57832   return SDValue();
57833 }
57834 
57835 /// If we are extracting a subvector of a vector select and the select condition
57836 /// is composed of concatenated vectors, try to narrow the select width. This
57837 /// is a common pattern for AVX1 integer code because 256-bit selects may be
57838 /// legal, but there is almost no integer math/logic available for 256-bit.
57839 /// This function should only be called with legal types (otherwise, the calls
57840 /// to get simple value types will assert).
57841 static SDValue narrowExtractedVectorSelect(SDNode *Ext, SelectionDAG &DAG) {
57842   SDValue Sel = Ext->getOperand(0);
57843   if (Sel.getOpcode() != ISD::VSELECT ||
57844       !isFreeToSplitVector(Sel.getOperand(0).getNode(), DAG))
57845     return SDValue();
57846 
57847   // Note: We assume simple value types because this should only be called with
57848   //       legal operations/types.
57849   // TODO: This can be extended to handle extraction to 256-bits.
57850   MVT VT = Ext->getSimpleValueType(0);
57851   if (!VT.is128BitVector())
57852     return SDValue();
57853 
57854   MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
57855   if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
57856     return SDValue();
57857 
57858   MVT WideVT = Ext->getOperand(0).getSimpleValueType();
57859   MVT SelVT = Sel.getSimpleValueType();
57860   assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&
57861          "Unexpected vector type with legal operations");
57862 
57863   unsigned SelElts = SelVT.getVectorNumElements();
57864   unsigned CastedElts = WideVT.getVectorNumElements();
57865   unsigned ExtIdx = Ext->getConstantOperandVal(1);
57866   if (SelElts % CastedElts == 0) {
57867     // The select has the same or more (narrower) elements than the extract
57868     // operand. The extraction index gets scaled by that factor.
57869     ExtIdx *= (SelElts / CastedElts);
57870   } else if (CastedElts % SelElts == 0) {
57871     // The select has less (wider) elements than the extract operand. Make sure
57872     // that the extraction index can be divided evenly.
57873     unsigned IndexDivisor = CastedElts / SelElts;
57874     if (ExtIdx % IndexDivisor != 0)
57875       return SDValue();
57876     ExtIdx /= IndexDivisor;
57877   } else {
57878     llvm_unreachable("Element count of simple vector types are not divisible?");
57879   }
57880 
57881   unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
57882   unsigned NarrowElts = SelElts / NarrowingFactor;
57883   MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
57884   SDLoc DL(Ext);
57885   SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
57886   SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
57887   SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
57888   SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
57889   return DAG.getBitcast(VT, NarrowSel);
57890 }
57891 
57892 static SDValue combineEXTRACT_SUBVECTOR(SDNode *N, SelectionDAG &DAG,
57893                                         TargetLowering::DAGCombinerInfo &DCI,
57894                                         const X86Subtarget &Subtarget) {
57895   // For AVX1 only, if we are extracting from a 256-bit and+not (which will
57896   // eventually get combined/lowered into ANDNP) with a concatenated operand,
57897   // split the 'and' into 128-bit ops to avoid the concatenate and extract.
57898   // We let generic combining take over from there to simplify the
57899   // insert/extract and 'not'.
57900   // This pattern emerges during AVX1 legalization. We handle it before lowering
57901   // to avoid complications like splitting constant vector loads.
57902 
57903   // Capture the original wide type in the likely case that we need to bitcast
57904   // back to this type.
57905   if (!N->getValueType(0).isSimple())
57906     return SDValue();
57907 
57908   MVT VT = N->getSimpleValueType(0);
57909   SDValue InVec = N->getOperand(0);
57910   unsigned IdxVal = N->getConstantOperandVal(1);
57911   SDValue InVecBC = peekThroughBitcasts(InVec);
57912   EVT InVecVT = InVec.getValueType();
57913   unsigned SizeInBits = VT.getSizeInBits();
57914   unsigned InSizeInBits = InVecVT.getSizeInBits();
57915   unsigned NumSubElts = VT.getVectorNumElements();
57916   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
57917 
57918   if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
57919       TLI.isTypeLegal(InVecVT) &&
57920       InSizeInBits == 256 && InVecBC.getOpcode() == ISD::AND) {
57921     auto isConcatenatedNot = [](SDValue V) {
57922       V = peekThroughBitcasts(V);
57923       if (!isBitwiseNot(V))
57924         return false;
57925       SDValue NotOp = V->getOperand(0);
57926       return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
57927     };
57928     if (isConcatenatedNot(InVecBC.getOperand(0)) ||
57929         isConcatenatedNot(InVecBC.getOperand(1))) {
57930       // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
57931       SDValue Concat = splitVectorIntBinary(InVecBC, DAG);
57932       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
57933                          DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
57934     }
57935   }
57936 
57937   if (DCI.isBeforeLegalizeOps())
57938     return SDValue();
57939 
57940   if (SDValue V = narrowExtractedVectorSelect(N, DAG))
57941     return V;
57942 
57943   if (ISD::isBuildVectorAllZeros(InVec.getNode()))
57944     return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
57945 
57946   if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
57947     if (VT.getScalarType() == MVT::i1)
57948       return DAG.getConstant(1, SDLoc(N), VT);
57949     return getOnesVector(VT, DAG, SDLoc(N));
57950   }
57951 
57952   if (InVec.getOpcode() == ISD::BUILD_VECTOR)
57953     return DAG.getBuildVector(VT, SDLoc(N),
57954                               InVec->ops().slice(IdxVal, NumSubElts));
57955 
57956   // If we are extracting from an insert into a larger vector, replace with a
57957   // smaller insert if we don't access less than the original subvector. Don't
57958   // do this for i1 vectors.
57959   // TODO: Relax the matching indices requirement?
57960   if (VT.getVectorElementType() != MVT::i1 &&
57961       InVec.getOpcode() == ISD::INSERT_SUBVECTOR && InVec.hasOneUse() &&
57962       IdxVal == InVec.getConstantOperandVal(2) &&
57963       InVec.getOperand(1).getValueSizeInBits() <= SizeInBits) {
57964     SDLoc DL(N);
57965     SDValue NewExt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT,
57966                                  InVec.getOperand(0), N->getOperand(1));
57967     unsigned NewIdxVal = InVec.getConstantOperandVal(2) - IdxVal;
57968     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, NewExt,
57969                        InVec.getOperand(1),
57970                        DAG.getVectorIdxConstant(NewIdxVal, DL));
57971   }
57972 
57973   // If we're extracting an upper subvector from a broadcast we should just
57974   // extract the lowest subvector instead which should allow
57975   // SimplifyDemandedVectorElts do more simplifications.
57976   if (IdxVal != 0 && (InVec.getOpcode() == X86ISD::VBROADCAST ||
57977                       InVec.getOpcode() == X86ISD::VBROADCAST_LOAD ||
57978                       DAG.isSplatValue(InVec, /*AllowUndefs*/ false)))
57979     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
57980 
57981   // If we're extracting a broadcasted subvector, just use the lowest subvector.
57982   if (IdxVal != 0 && InVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
57983       cast<MemIntrinsicSDNode>(InVec)->getMemoryVT() == VT)
57984     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
57985 
57986   // Attempt to extract from the source of a shuffle vector.
57987   if ((InSizeInBits % SizeInBits) == 0 && (IdxVal % NumSubElts) == 0) {
57988     SmallVector<int, 32> ShuffleMask;
57989     SmallVector<int, 32> ScaledMask;
57990     SmallVector<SDValue, 2> ShuffleInputs;
57991     unsigned NumSubVecs = InSizeInBits / SizeInBits;
57992     // Decode the shuffle mask and scale it so its shuffling subvectors.
57993     if (getTargetShuffleInputs(InVecBC, ShuffleInputs, ShuffleMask, DAG) &&
57994         scaleShuffleElements(ShuffleMask, NumSubVecs, ScaledMask)) {
57995       unsigned SubVecIdx = IdxVal / NumSubElts;
57996       if (ScaledMask[SubVecIdx] == SM_SentinelUndef)
57997         return DAG.getUNDEF(VT);
57998       if (ScaledMask[SubVecIdx] == SM_SentinelZero)
57999         return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
58000       SDValue Src = ShuffleInputs[ScaledMask[SubVecIdx] / NumSubVecs];
58001       if (Src.getValueSizeInBits() == InSizeInBits) {
58002         unsigned SrcSubVecIdx = ScaledMask[SubVecIdx] % NumSubVecs;
58003         unsigned SrcEltIdx = SrcSubVecIdx * NumSubElts;
58004         return extractSubVector(DAG.getBitcast(InVecVT, Src), SrcEltIdx, DAG,
58005                                 SDLoc(N), SizeInBits);
58006       }
58007     }
58008   }
58009 
58010   // If we're extracting the lowest subvector and we're the only user,
58011   // we may be able to perform this with a smaller vector width.
58012   unsigned InOpcode = InVec.getOpcode();
58013   if (InVec.hasOneUse()) {
58014     if (IdxVal == 0 && VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
58015       // v2f64 CVTDQ2PD(v4i32).
58016       if (InOpcode == ISD::SINT_TO_FP &&
58017           InVec.getOperand(0).getValueType() == MVT::v4i32) {
58018         return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
58019       }
58020       // v2f64 CVTUDQ2PD(v4i32).
58021       if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
58022           InVec.getOperand(0).getValueType() == MVT::v4i32) {
58023         return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
58024       }
58025       // v2f64 CVTPS2PD(v4f32).
58026       if (InOpcode == ISD::FP_EXTEND &&
58027           InVec.getOperand(0).getValueType() == MVT::v4f32) {
58028         return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
58029       }
58030     }
58031     if (IdxVal == 0 &&
58032         (ISD::isExtOpcode(InOpcode) || ISD::isExtVecInRegOpcode(InOpcode)) &&
58033         (SizeInBits == 128 || SizeInBits == 256) &&
58034         InVec.getOperand(0).getValueSizeInBits() >= SizeInBits) {
58035       SDLoc DL(N);
58036       SDValue Ext = InVec.getOperand(0);
58037       if (Ext.getValueSizeInBits() > SizeInBits)
58038         Ext = extractSubVector(Ext, 0, DAG, DL, SizeInBits);
58039       unsigned ExtOp = DAG.getOpcode_EXTEND_VECTOR_INREG(InOpcode);
58040       return DAG.getNode(ExtOp, DL, VT, Ext);
58041     }
58042     if (IdxVal == 0 && InOpcode == ISD::VSELECT &&
58043         InVec.getOperand(0).getValueType().is256BitVector() &&
58044         InVec.getOperand(1).getValueType().is256BitVector() &&
58045         InVec.getOperand(2).getValueType().is256BitVector()) {
58046       SDLoc DL(N);
58047       SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
58048       SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
58049       SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
58050       return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
58051     }
58052     if (IdxVal == 0 && InOpcode == ISD::TRUNCATE && Subtarget.hasVLX() &&
58053         (VT.is128BitVector() || VT.is256BitVector())) {
58054       SDLoc DL(N);
58055       SDValue InVecSrc = InVec.getOperand(0);
58056       unsigned Scale = InVecSrc.getValueSizeInBits() / InSizeInBits;
58057       SDValue Ext = extractSubVector(InVecSrc, 0, DAG, DL, Scale * SizeInBits);
58058       return DAG.getNode(InOpcode, DL, VT, Ext);
58059     }
58060     if (InOpcode == X86ISD::MOVDDUP &&
58061         (VT.is128BitVector() || VT.is256BitVector())) {
58062       SDLoc DL(N);
58063       SDValue Ext0 =
58064           extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
58065       return DAG.getNode(InOpcode, DL, VT, Ext0);
58066     }
58067   }
58068 
58069   // Always split vXi64 logical shifts where we're extracting the upper 32-bits
58070   // as this is very likely to fold into a shuffle/truncation.
58071   if ((InOpcode == X86ISD::VSHLI || InOpcode == X86ISD::VSRLI) &&
58072       InVecVT.getScalarSizeInBits() == 64 &&
58073       InVec.getConstantOperandAPInt(1) == 32) {
58074     SDLoc DL(N);
58075     SDValue Ext =
58076         extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
58077     return DAG.getNode(InOpcode, DL, VT, Ext, InVec.getOperand(1));
58078   }
58079 
58080   return SDValue();
58081 }
58082 
58083 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
58084   EVT VT = N->getValueType(0);
58085   SDValue Src = N->getOperand(0);
58086   SDLoc DL(N);
58087 
58088   // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
58089   // This occurs frequently in our masked scalar intrinsic code and our
58090   // floating point select lowering with AVX512.
58091   // TODO: SimplifyDemandedBits instead?
58092   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse() &&
58093       isOneConstant(Src.getOperand(1)))
58094     return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Src.getOperand(0));
58095 
58096   // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
58097   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
58098       Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
58099       Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
58100     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
58101       if (C->isZero())
58102         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
58103                            Src.getOperand(1));
58104 
58105   // Reduce v2i64 to v4i32 if we don't need the upper bits or are known zero.
58106   // TODO: Move to DAGCombine/SimplifyDemandedBits?
58107   if ((VT == MVT::v2i64 || VT == MVT::v2f64) && Src.hasOneUse()) {
58108     auto IsExt64 = [&DAG](SDValue Op, bool IsZeroExt) {
58109       if (Op.getValueType() != MVT::i64)
58110         return SDValue();
58111       unsigned Opc = IsZeroExt ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND;
58112       if (Op.getOpcode() == Opc &&
58113           Op.getOperand(0).getScalarValueSizeInBits() <= 32)
58114         return Op.getOperand(0);
58115       unsigned Ext = IsZeroExt ? ISD::ZEXTLOAD : ISD::EXTLOAD;
58116       if (auto *Ld = dyn_cast<LoadSDNode>(Op))
58117         if (Ld->getExtensionType() == Ext &&
58118             Ld->getMemoryVT().getScalarSizeInBits() <= 32)
58119           return Op;
58120       if (IsZeroExt) {
58121         KnownBits Known = DAG.computeKnownBits(Op);
58122         if (!Known.isConstant() && Known.countMinLeadingZeros() >= 32)
58123           return Op;
58124       }
58125       return SDValue();
58126     };
58127 
58128     if (SDValue AnyExt = IsExt64(peekThroughOneUseBitcasts(Src), false))
58129       return DAG.getBitcast(
58130           VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
58131                           DAG.getAnyExtOrTrunc(AnyExt, DL, MVT::i32)));
58132 
58133     if (SDValue ZeroExt = IsExt64(peekThroughOneUseBitcasts(Src), true))
58134       return DAG.getBitcast(
58135           VT,
58136           DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v4i32,
58137                       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
58138                                   DAG.getZExtOrTrunc(ZeroExt, DL, MVT::i32))));
58139   }
58140 
58141   // Combine (v2i64 (scalar_to_vector (i64 (bitconvert (mmx))))) to MOVQ2DQ.
58142   if (VT == MVT::v2i64 && Src.getOpcode() == ISD::BITCAST &&
58143       Src.getOperand(0).getValueType() == MVT::x86mmx)
58144     return DAG.getNode(X86ISD::MOVQ2DQ, DL, VT, Src.getOperand(0));
58145 
58146   // See if we're broadcasting the scalar value, in which case just reuse that.
58147   // Ensure the same SDValue from the SDNode use is being used.
58148   if (VT.getScalarType() == Src.getValueType())
58149     for (SDNode *User : Src->uses())
58150       if (User->getOpcode() == X86ISD::VBROADCAST &&
58151           Src == User->getOperand(0)) {
58152         unsigned SizeInBits = VT.getFixedSizeInBits();
58153         unsigned BroadcastSizeInBits =
58154             User->getValueSizeInBits(0).getFixedValue();
58155         if (BroadcastSizeInBits == SizeInBits)
58156           return SDValue(User, 0);
58157         if (BroadcastSizeInBits > SizeInBits)
58158           return extractSubVector(SDValue(User, 0), 0, DAG, DL, SizeInBits);
58159         // TODO: Handle BroadcastSizeInBits < SizeInBits when we have test
58160         // coverage.
58161       }
58162 
58163   return SDValue();
58164 }
58165 
58166 // Simplify PMULDQ and PMULUDQ operations.
58167 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
58168                              TargetLowering::DAGCombinerInfo &DCI,
58169                              const X86Subtarget &Subtarget) {
58170   SDValue LHS = N->getOperand(0);
58171   SDValue RHS = N->getOperand(1);
58172 
58173   // Canonicalize constant to RHS.
58174   if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
58175       !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
58176     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
58177 
58178   // Multiply by zero.
58179   // Don't return RHS as it may contain UNDEFs.
58180   if (ISD::isBuildVectorAllZeros(RHS.getNode()))
58181     return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
58182 
58183   // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
58184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58185   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(64), DCI))
58186     return SDValue(N, 0);
58187 
58188   // If the input is an extend_invec and the SimplifyDemandedBits call didn't
58189   // convert it to any_extend_invec, due to the LegalOperations check, do the
58190   // conversion directly to a vector shuffle manually. This exposes combine
58191   // opportunities missed by combineEXTEND_VECTOR_INREG not calling
58192   // combineX86ShufflesRecursively on SSE4.1 targets.
58193   // FIXME: This is basically a hack around several other issues related to
58194   // ANY_EXTEND_VECTOR_INREG.
58195   if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
58196       (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
58197        LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
58198       LHS.getOperand(0).getValueType() == MVT::v4i32) {
58199     SDLoc dl(N);
58200     LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
58201                                LHS.getOperand(0), { 0, -1, 1, -1 });
58202     LHS = DAG.getBitcast(MVT::v2i64, LHS);
58203     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
58204   }
58205   if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
58206       (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
58207        RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
58208       RHS.getOperand(0).getValueType() == MVT::v4i32) {
58209     SDLoc dl(N);
58210     RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
58211                                RHS.getOperand(0), { 0, -1, 1, -1 });
58212     RHS = DAG.getBitcast(MVT::v2i64, RHS);
58213     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
58214   }
58215 
58216   return SDValue();
58217 }
58218 
58219 // Simplify VPMADDUBSW/VPMADDWD operations.
58220 static SDValue combineVPMADD(SDNode *N, SelectionDAG &DAG,
58221                              TargetLowering::DAGCombinerInfo &DCI) {
58222   EVT VT = N->getValueType(0);
58223   SDValue LHS = N->getOperand(0);
58224   SDValue RHS = N->getOperand(1);
58225 
58226   // Multiply by zero.
58227   // Don't return LHS/RHS as it may contain UNDEFs.
58228   if (ISD::isBuildVectorAllZeros(LHS.getNode()) ||
58229       ISD::isBuildVectorAllZeros(RHS.getNode()))
58230     return DAG.getConstant(0, SDLoc(N), VT);
58231 
58232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58233   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
58234   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
58235     return SDValue(N, 0);
58236 
58237   return SDValue();
58238 }
58239 
58240 static SDValue combineEXTEND_VECTOR_INREG(SDNode *N, SelectionDAG &DAG,
58241                                           TargetLowering::DAGCombinerInfo &DCI,
58242                                           const X86Subtarget &Subtarget) {
58243   EVT VT = N->getValueType(0);
58244   SDValue In = N->getOperand(0);
58245   unsigned Opcode = N->getOpcode();
58246   unsigned InOpcode = In.getOpcode();
58247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58248   SDLoc DL(N);
58249 
58250   // Try to merge vector loads and extend_inreg to an extload.
58251   if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
58252       In.hasOneUse()) {
58253     auto *Ld = cast<LoadSDNode>(In);
58254     if (Ld->isSimple()) {
58255       MVT SVT = In.getSimpleValueType().getVectorElementType();
58256       ISD::LoadExtType Ext = Opcode == ISD::SIGN_EXTEND_VECTOR_INREG
58257                                  ? ISD::SEXTLOAD
58258                                  : ISD::ZEXTLOAD;
58259       EVT MemVT = VT.changeVectorElementType(SVT);
58260       if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
58261         SDValue Load = DAG.getExtLoad(
58262             Ext, DL, VT, Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
58263             MemVT, Ld->getOriginalAlign(), Ld->getMemOperand()->getFlags());
58264         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
58265         return Load;
58266       }
58267     }
58268   }
58269 
58270   // Fold EXTEND_VECTOR_INREG(EXTEND_VECTOR_INREG(X)) -> EXTEND_VECTOR_INREG(X).
58271   if (Opcode == InOpcode)
58272     return DAG.getNode(Opcode, DL, VT, In.getOperand(0));
58273 
58274   // Fold EXTEND_VECTOR_INREG(EXTRACT_SUBVECTOR(EXTEND(X),0))
58275   // -> EXTEND_VECTOR_INREG(X).
58276   // TODO: Handle non-zero subvector indices.
58277   if (InOpcode == ISD::EXTRACT_SUBVECTOR && In.getConstantOperandVal(1) == 0 &&
58278       In.getOperand(0).getOpcode() == DAG.getOpcode_EXTEND(Opcode) &&
58279       In.getOperand(0).getOperand(0).getValueSizeInBits() ==
58280           In.getValueSizeInBits())
58281     return DAG.getNode(Opcode, DL, VT, In.getOperand(0).getOperand(0));
58282 
58283   // Fold EXTEND_VECTOR_INREG(BUILD_VECTOR(X,Y,?,?)) -> BUILD_VECTOR(X,0,Y,0).
58284   // TODO: Move to DAGCombine?
58285   if (!DCI.isBeforeLegalizeOps() && Opcode == ISD::ZERO_EXTEND_VECTOR_INREG &&
58286       In.getOpcode() == ISD::BUILD_VECTOR && In.hasOneUse() &&
58287       In.getValueSizeInBits() == VT.getSizeInBits()) {
58288     unsigned NumElts = VT.getVectorNumElements();
58289     unsigned Scale = VT.getScalarSizeInBits() / In.getScalarValueSizeInBits();
58290     EVT EltVT = In.getOperand(0).getValueType();
58291     SmallVector<SDValue> Elts(Scale * NumElts, DAG.getConstant(0, DL, EltVT));
58292     for (unsigned I = 0; I != NumElts; ++I)
58293       Elts[I * Scale] = In.getOperand(I);
58294     return DAG.getBitcast(VT, DAG.getBuildVector(In.getValueType(), DL, Elts));
58295   }
58296 
58297   // Attempt to combine as a shuffle on SSE41+ targets.
58298   if (Subtarget.hasSSE41()) {
58299     SDValue Op(N, 0);
58300     if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
58301       if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
58302         return Res;
58303   }
58304 
58305   return SDValue();
58306 }
58307 
58308 static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
58309                              TargetLowering::DAGCombinerInfo &DCI) {
58310   EVT VT = N->getValueType(0);
58311 
58312   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
58313     return DAG.getConstant(0, SDLoc(N), VT);
58314 
58315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58316   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
58317   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
58318     return SDValue(N, 0);
58319 
58320   return SDValue();
58321 }
58322 
58323 // Optimize (fp16_to_fp (fp_to_fp16 X)) to VCVTPS2PH followed by VCVTPH2PS.
58324 // Done as a combine because the lowering for fp16_to_fp and fp_to_fp16 produce
58325 // extra instructions between the conversion due to going to scalar and back.
58326 static SDValue combineFP16_TO_FP(SDNode *N, SelectionDAG &DAG,
58327                                  const X86Subtarget &Subtarget) {
58328   if (Subtarget.useSoftFloat() || !Subtarget.hasF16C())
58329     return SDValue();
58330 
58331   if (N->getOperand(0).getOpcode() != ISD::FP_TO_FP16)
58332     return SDValue();
58333 
58334   if (N->getValueType(0) != MVT::f32 ||
58335       N->getOperand(0).getOperand(0).getValueType() != MVT::f32)
58336     return SDValue();
58337 
58338   SDLoc dl(N);
58339   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32,
58340                             N->getOperand(0).getOperand(0));
58341   Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
58342                     DAG.getTargetConstant(4, dl, MVT::i32));
58343   Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
58344   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
58345                      DAG.getIntPtrConstant(0, dl));
58346 }
58347 
58348 static SDValue combineFP_EXTEND(SDNode *N, SelectionDAG &DAG,
58349                                 const X86Subtarget &Subtarget) {
58350   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
58351     return SDValue();
58352 
58353   if (Subtarget.hasFP16())
58354     return SDValue();
58355 
58356   bool IsStrict = N->isStrictFPOpcode();
58357   EVT VT = N->getValueType(0);
58358   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
58359   EVT SrcVT = Src.getValueType();
58360 
58361   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::f16)
58362     return SDValue();
58363 
58364   if (VT.getVectorElementType() != MVT::f32 &&
58365       VT.getVectorElementType() != MVT::f64)
58366     return SDValue();
58367 
58368   unsigned NumElts = VT.getVectorNumElements();
58369   if (NumElts == 1 || !isPowerOf2_32(NumElts))
58370     return SDValue();
58371 
58372   SDLoc dl(N);
58373 
58374   // Convert the input to vXi16.
58375   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
58376   Src = DAG.getBitcast(IntVT, Src);
58377 
58378   // Widen to at least 8 input elements.
58379   if (NumElts < 8) {
58380     unsigned NumConcats = 8 / NumElts;
58381     SDValue Fill = NumElts == 4 ? DAG.getUNDEF(IntVT)
58382                                 : DAG.getConstant(0, dl, IntVT);
58383     SmallVector<SDValue, 4> Ops(NumConcats, Fill);
58384     Ops[0] = Src;
58385     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, Ops);
58386   }
58387 
58388   // Destination is vXf32 with at least 4 elements.
58389   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32,
58390                                std::max(4U, NumElts));
58391   SDValue Cvt, Chain;
58392   if (IsStrict) {
58393     Cvt = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {CvtVT, MVT::Other},
58394                       {N->getOperand(0), Src});
58395     Chain = Cvt.getValue(1);
58396   } else {
58397     Cvt = DAG.getNode(X86ISD::CVTPH2PS, dl, CvtVT, Src);
58398   }
58399 
58400   if (NumElts < 4) {
58401     assert(NumElts == 2 && "Unexpected size");
58402     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Cvt,
58403                       DAG.getIntPtrConstant(0, dl));
58404   }
58405 
58406   if (IsStrict) {
58407     // Extend to the original VT if necessary.
58408     if (Cvt.getValueType() != VT) {
58409       Cvt = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {VT, MVT::Other},
58410                         {Chain, Cvt});
58411       Chain = Cvt.getValue(1);
58412     }
58413     return DAG.getMergeValues({Cvt, Chain}, dl);
58414   }
58415 
58416   // Extend to the original VT if necessary.
58417   return DAG.getNode(ISD::FP_EXTEND, dl, VT, Cvt);
58418 }
58419 
58420 // Try to find a larger VBROADCAST_LOAD/SUBV_BROADCAST_LOAD that we can extract
58421 // from. Limit this to cases where the loads have the same input chain and the
58422 // output chains are unused. This avoids any memory ordering issues.
58423 static SDValue combineBROADCAST_LOAD(SDNode *N, SelectionDAG &DAG,
58424                                      TargetLowering::DAGCombinerInfo &DCI) {
58425   assert((N->getOpcode() == X86ISD::VBROADCAST_LOAD ||
58426           N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
58427          "Unknown broadcast load type");
58428 
58429   // Only do this if the chain result is unused.
58430   if (N->hasAnyUseOfValue(1))
58431     return SDValue();
58432 
58433   auto *MemIntrin = cast<MemIntrinsicSDNode>(N);
58434 
58435   SDValue Ptr = MemIntrin->getBasePtr();
58436   SDValue Chain = MemIntrin->getChain();
58437   EVT VT = N->getSimpleValueType(0);
58438   EVT MemVT = MemIntrin->getMemoryVT();
58439 
58440   // Look at other users of our base pointer and try to find a wider broadcast.
58441   // The input chain and the size of the memory VT must match.
58442   for (SDNode *User : Ptr->uses())
58443     if (User != N && User->getOpcode() == N->getOpcode() &&
58444         cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
58445         cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
58446         cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
58447             MemVT.getSizeInBits() &&
58448         !User->hasAnyUseOfValue(1) &&
58449         User->getValueSizeInBits(0).getFixedValue() > VT.getFixedSizeInBits()) {
58450       SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
58451                                          VT.getSizeInBits());
58452       Extract = DAG.getBitcast(VT, Extract);
58453       return DCI.CombineTo(N, Extract, SDValue(User, 1));
58454     }
58455 
58456   return SDValue();
58457 }
58458 
58459 static SDValue combineFP_ROUND(SDNode *N, SelectionDAG &DAG,
58460                                const X86Subtarget &Subtarget) {
58461   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
58462     return SDValue();
58463 
58464   bool IsStrict = N->isStrictFPOpcode();
58465   EVT VT = N->getValueType(0);
58466   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
58467   EVT SrcVT = Src.getValueType();
58468 
58469   if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
58470       SrcVT.getVectorElementType() != MVT::f32)
58471     return SDValue();
58472 
58473   SDLoc dl(N);
58474 
58475   SDValue Cvt, Chain;
58476   unsigned NumElts = VT.getVectorNumElements();
58477   if (Subtarget.hasFP16()) {
58478     // Combine (v8f16 fp_round(concat_vectors(v4f32 (xint_to_fp v4i64), ..)))
58479     // into (v8f16 vector_shuffle(v8f16 (CVTXI2P v4i64), ..))
58480     if (NumElts == 8 && Src.getOpcode() == ISD::CONCAT_VECTORS) {
58481       SDValue Cvt0, Cvt1;
58482       SDValue Op0 = Src.getOperand(0);
58483       SDValue Op1 = Src.getOperand(1);
58484       bool IsOp0Strict = Op0->isStrictFPOpcode();
58485       if (Op0.getOpcode() != Op1.getOpcode() ||
58486           Op0.getOperand(IsOp0Strict ? 1 : 0).getValueType() != MVT::v4i64 ||
58487           Op1.getOperand(IsOp0Strict ? 1 : 0).getValueType() != MVT::v4i64) {
58488         return SDValue();
58489       }
58490       int Mask[8] = {0, 1, 2, 3, 8, 9, 10, 11};
58491       if (IsStrict) {
58492         assert(IsOp0Strict && "Op0 must be strict node");
58493         unsigned Opc = Op0.getOpcode() == ISD::STRICT_SINT_TO_FP
58494                            ? X86ISD::STRICT_CVTSI2P
58495                            : X86ISD::STRICT_CVTUI2P;
58496         Cvt0 = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
58497                            {Op0.getOperand(0), Op0.getOperand(1)});
58498         Cvt1 = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
58499                            {Op1.getOperand(0), Op1.getOperand(1)});
58500         Cvt = DAG.getVectorShuffle(MVT::v8f16, dl, Cvt0, Cvt1, Mask);
58501         return DAG.getMergeValues({Cvt, Cvt0.getValue(1)}, dl);
58502       }
58503       unsigned Opc = Op0.getOpcode() == ISD::SINT_TO_FP ? X86ISD::CVTSI2P
58504                                                         : X86ISD::CVTUI2P;
58505       Cvt0 = DAG.getNode(Opc, dl, MVT::v8f16, Op0.getOperand(0));
58506       Cvt1 = DAG.getNode(Opc, dl, MVT::v8f16, Op1.getOperand(0));
58507       return Cvt = DAG.getVectorShuffle(MVT::v8f16, dl, Cvt0, Cvt1, Mask);
58508     }
58509     return SDValue();
58510   }
58511 
58512   if (NumElts == 1 || !isPowerOf2_32(NumElts))
58513     return SDValue();
58514 
58515   // Widen to at least 4 input elements.
58516   if (NumElts < 4)
58517     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
58518                       DAG.getConstantFP(0.0, dl, SrcVT));
58519 
58520   // Destination is v8i16 with at least 8 elements.
58521   EVT CvtVT =
58522       EVT::getVectorVT(*DAG.getContext(), MVT::i16, std::max(8U, NumElts));
58523   SDValue Rnd = DAG.getTargetConstant(4, dl, MVT::i32);
58524   if (IsStrict) {
58525     Cvt = DAG.getNode(X86ISD::STRICT_CVTPS2PH, dl, {CvtVT, MVT::Other},
58526                       {N->getOperand(0), Src, Rnd});
58527     Chain = Cvt.getValue(1);
58528   } else {
58529     Cvt = DAG.getNode(X86ISD::CVTPS2PH, dl, CvtVT, Src, Rnd);
58530   }
58531 
58532   // Extract down to real number of elements.
58533   if (NumElts < 8) {
58534     EVT IntVT = VT.changeVectorElementTypeToInteger();
58535     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, IntVT, Cvt,
58536                       DAG.getIntPtrConstant(0, dl));
58537   }
58538 
58539   Cvt = DAG.getBitcast(VT, Cvt);
58540 
58541   if (IsStrict)
58542     return DAG.getMergeValues({Cvt, Chain}, dl);
58543 
58544   return Cvt;
58545 }
58546 
58547 static SDValue combineMOVDQ2Q(SDNode *N, SelectionDAG &DAG) {
58548   SDValue Src = N->getOperand(0);
58549 
58550   // Turn MOVDQ2Q+simple_load into an mmx load.
58551   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
58552     LoadSDNode *LN = cast<LoadSDNode>(Src.getNode());
58553 
58554     if (LN->isSimple()) {
58555       SDValue NewLd = DAG.getLoad(MVT::x86mmx, SDLoc(N), LN->getChain(),
58556                                   LN->getBasePtr(),
58557                                   LN->getPointerInfo(),
58558                                   LN->getOriginalAlign(),
58559                                   LN->getMemOperand()->getFlags());
58560       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), NewLd.getValue(1));
58561       return NewLd;
58562     }
58563   }
58564 
58565   return SDValue();
58566 }
58567 
58568 static SDValue combinePDEP(SDNode *N, SelectionDAG &DAG,
58569                            TargetLowering::DAGCombinerInfo &DCI) {
58570   unsigned NumBits = N->getSimpleValueType(0).getSizeInBits();
58571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58572   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBits), DCI))
58573     return SDValue(N, 0);
58574 
58575   return SDValue();
58576 }
58577 
58578 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
58579                                              DAGCombinerInfo &DCI) const {
58580   SelectionDAG &DAG = DCI.DAG;
58581   switch (N->getOpcode()) {
58582   default: break;
58583   case ISD::SCALAR_TO_VECTOR:
58584     return combineScalarToVector(N, DAG);
58585   case ISD::EXTRACT_VECTOR_ELT:
58586   case X86ISD::PEXTRW:
58587   case X86ISD::PEXTRB:
58588     return combineExtractVectorElt(N, DAG, DCI, Subtarget);
58589   case ISD::CONCAT_VECTORS:
58590     return combineCONCAT_VECTORS(N, DAG, DCI, Subtarget);
58591   case ISD::INSERT_SUBVECTOR:
58592     return combineINSERT_SUBVECTOR(N, DAG, DCI, Subtarget);
58593   case ISD::EXTRACT_SUBVECTOR:
58594     return combineEXTRACT_SUBVECTOR(N, DAG, DCI, Subtarget);
58595   case ISD::VSELECT:
58596   case ISD::SELECT:
58597   case X86ISD::BLENDV:      return combineSelect(N, DAG, DCI, Subtarget);
58598   case ISD::BITCAST:        return combineBitcast(N, DAG, DCI, Subtarget);
58599   case X86ISD::CMOV:        return combineCMov(N, DAG, DCI, Subtarget);
58600   case X86ISD::CMP:         return combineCMP(N, DAG);
58601   case ISD::ADD:            return combineAdd(N, DAG, DCI, Subtarget);
58602   case ISD::SUB:            return combineSub(N, DAG, DCI, Subtarget);
58603   case X86ISD::ADD:
58604   case X86ISD::SUB:         return combineX86AddSub(N, DAG, DCI);
58605   case X86ISD::SBB:         return combineSBB(N, DAG);
58606   case X86ISD::ADC:         return combineADC(N, DAG, DCI);
58607   case ISD::MUL:            return combineMul(N, DAG, DCI, Subtarget);
58608   case ISD::SHL:            return combineShiftLeft(N, DAG);
58609   case ISD::SRA:            return combineShiftRightArithmetic(N, DAG, Subtarget);
58610   case ISD::SRL:            return combineShiftRightLogical(N, DAG, DCI, Subtarget);
58611   case ISD::AND:            return combineAnd(N, DAG, DCI, Subtarget);
58612   case ISD::OR:             return combineOr(N, DAG, DCI, Subtarget);
58613   case ISD::XOR:            return combineXor(N, DAG, DCI, Subtarget);
58614   case X86ISD::BEXTR:
58615   case X86ISD::BEXTRI:      return combineBEXTR(N, DAG, DCI, Subtarget);
58616   case ISD::LOAD:           return combineLoad(N, DAG, DCI, Subtarget);
58617   case ISD::MLOAD:          return combineMaskedLoad(N, DAG, DCI, Subtarget);
58618   case ISD::STORE:          return combineStore(N, DAG, DCI, Subtarget);
58619   case ISD::MSTORE:         return combineMaskedStore(N, DAG, DCI, Subtarget);
58620   case X86ISD::VEXTRACT_STORE:
58621     return combineVEXTRACT_STORE(N, DAG, DCI, Subtarget);
58622   case ISD::SINT_TO_FP:
58623   case ISD::STRICT_SINT_TO_FP:
58624     return combineSIntToFP(N, DAG, DCI, Subtarget);
58625   case ISD::UINT_TO_FP:
58626   case ISD::STRICT_UINT_TO_FP:
58627     return combineUIntToFP(N, DAG, Subtarget);
58628   case ISD::FADD:
58629   case ISD::FSUB:           return combineFaddFsub(N, DAG, Subtarget);
58630   case X86ISD::VFCMULC:
58631   case X86ISD::VFMULC:      return combineFMulcFCMulc(N, DAG, Subtarget);
58632   case ISD::FNEG:           return combineFneg(N, DAG, DCI, Subtarget);
58633   case ISD::TRUNCATE:       return combineTruncate(N, DAG, Subtarget);
58634   case X86ISD::VTRUNC:      return combineVTRUNC(N, DAG, DCI);
58635   case X86ISD::ANDNP:       return combineAndnp(N, DAG, DCI, Subtarget);
58636   case X86ISD::FAND:        return combineFAnd(N, DAG, Subtarget);
58637   case X86ISD::FANDN:       return combineFAndn(N, DAG, Subtarget);
58638   case X86ISD::FXOR:
58639   case X86ISD::FOR:         return combineFOr(N, DAG, DCI, Subtarget);
58640   case X86ISD::FMIN:
58641   case X86ISD::FMAX:        return combineFMinFMax(N, DAG);
58642   case ISD::FMINNUM:
58643   case ISD::FMAXNUM:        return combineFMinNumFMaxNum(N, DAG, Subtarget);
58644   case X86ISD::CVTSI2P:
58645   case X86ISD::CVTUI2P:     return combineX86INT_TO_FP(N, DAG, DCI);
58646   case X86ISD::CVTP2SI:
58647   case X86ISD::CVTP2UI:
58648   case X86ISD::STRICT_CVTTP2SI:
58649   case X86ISD::CVTTP2SI:
58650   case X86ISD::STRICT_CVTTP2UI:
58651   case X86ISD::CVTTP2UI:
58652                             return combineCVTP2I_CVTTP2I(N, DAG, DCI);
58653   case X86ISD::STRICT_CVTPH2PS:
58654   case X86ISD::CVTPH2PS:    return combineCVTPH2PS(N, DAG, DCI);
58655   case X86ISD::BT:          return combineBT(N, DAG, DCI);
58656   case ISD::ANY_EXTEND:
58657   case ISD::ZERO_EXTEND:    return combineZext(N, DAG, DCI, Subtarget);
58658   case ISD::SIGN_EXTEND:    return combineSext(N, DAG, DCI, Subtarget);
58659   case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
58660   case ISD::ANY_EXTEND_VECTOR_INREG:
58661   case ISD::SIGN_EXTEND_VECTOR_INREG:
58662   case ISD::ZERO_EXTEND_VECTOR_INREG:
58663     return combineEXTEND_VECTOR_INREG(N, DAG, DCI, Subtarget);
58664   case ISD::SETCC:          return combineSetCC(N, DAG, DCI, Subtarget);
58665   case X86ISD::SETCC:       return combineX86SetCC(N, DAG, Subtarget);
58666   case X86ISD::BRCOND:      return combineBrCond(N, DAG, Subtarget);
58667   case X86ISD::PACKSS:
58668   case X86ISD::PACKUS:      return combineVectorPack(N, DAG, DCI, Subtarget);
58669   case X86ISD::HADD:
58670   case X86ISD::HSUB:
58671   case X86ISD::FHADD:
58672   case X86ISD::FHSUB:       return combineVectorHADDSUB(N, DAG, DCI, Subtarget);
58673   case X86ISD::VSHL:
58674   case X86ISD::VSRA:
58675   case X86ISD::VSRL:
58676     return combineVectorShiftVar(N, DAG, DCI, Subtarget);
58677   case X86ISD::VSHLI:
58678   case X86ISD::VSRAI:
58679   case X86ISD::VSRLI:
58680     return combineVectorShiftImm(N, DAG, DCI, Subtarget);
58681   case ISD::INSERT_VECTOR_ELT:
58682   case X86ISD::PINSRB:
58683   case X86ISD::PINSRW:      return combineVectorInsert(N, DAG, DCI, Subtarget);
58684   case X86ISD::SHUFP:       // Handle all target specific shuffles
58685   case X86ISD::INSERTPS:
58686   case X86ISD::EXTRQI:
58687   case X86ISD::INSERTQI:
58688   case X86ISD::VALIGN:
58689   case X86ISD::PALIGNR:
58690   case X86ISD::VSHLDQ:
58691   case X86ISD::VSRLDQ:
58692   case X86ISD::BLENDI:
58693   case X86ISD::UNPCKH:
58694   case X86ISD::UNPCKL:
58695   case X86ISD::MOVHLPS:
58696   case X86ISD::MOVLHPS:
58697   case X86ISD::PSHUFB:
58698   case X86ISD::PSHUFD:
58699   case X86ISD::PSHUFHW:
58700   case X86ISD::PSHUFLW:
58701   case X86ISD::MOVSHDUP:
58702   case X86ISD::MOVSLDUP:
58703   case X86ISD::MOVDDUP:
58704   case X86ISD::MOVSS:
58705   case X86ISD::MOVSD:
58706   case X86ISD::MOVSH:
58707   case X86ISD::VBROADCAST:
58708   case X86ISD::VPPERM:
58709   case X86ISD::VPERMI:
58710   case X86ISD::VPERMV:
58711   case X86ISD::VPERMV3:
58712   case X86ISD::VPERMIL2:
58713   case X86ISD::VPERMILPI:
58714   case X86ISD::VPERMILPV:
58715   case X86ISD::VPERM2X128:
58716   case X86ISD::SHUF128:
58717   case X86ISD::VZEXT_MOVL:
58718   case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
58719   case X86ISD::FMADD_RND:
58720   case X86ISD::FMSUB:
58721   case X86ISD::STRICT_FMSUB:
58722   case X86ISD::FMSUB_RND:
58723   case X86ISD::FNMADD:
58724   case X86ISD::STRICT_FNMADD:
58725   case X86ISD::FNMADD_RND:
58726   case X86ISD::FNMSUB:
58727   case X86ISD::STRICT_FNMSUB:
58728   case X86ISD::FNMSUB_RND:
58729   case ISD::FMA:
58730   case ISD::STRICT_FMA:     return combineFMA(N, DAG, DCI, Subtarget);
58731   case X86ISD::FMADDSUB_RND:
58732   case X86ISD::FMSUBADD_RND:
58733   case X86ISD::FMADDSUB:
58734   case X86ISD::FMSUBADD:    return combineFMADDSUB(N, DAG, DCI);
58735   case X86ISD::MOVMSK:      return combineMOVMSK(N, DAG, DCI, Subtarget);
58736   case X86ISD::TESTP:       return combineTESTP(N, DAG, DCI, Subtarget);
58737   case X86ISD::MGATHER:
58738   case X86ISD::MSCATTER:
58739     return combineX86GatherScatter(N, DAG, DCI, Subtarget);
58740   case ISD::MGATHER:
58741   case ISD::MSCATTER:       return combineGatherScatter(N, DAG, DCI);
58742   case X86ISD::PCMPEQ:
58743   case X86ISD::PCMPGT:      return combineVectorCompare(N, DAG, Subtarget);
58744   case X86ISD::PMULDQ:
58745   case X86ISD::PMULUDQ:     return combinePMULDQ(N, DAG, DCI, Subtarget);
58746   case X86ISD::VPMADDUBSW:
58747   case X86ISD::VPMADDWD:    return combineVPMADD(N, DAG, DCI);
58748   case X86ISD::KSHIFTL:
58749   case X86ISD::KSHIFTR:     return combineKSHIFT(N, DAG, DCI);
58750   case ISD::FP16_TO_FP:     return combineFP16_TO_FP(N, DAG, Subtarget);
58751   case ISD::STRICT_FP_EXTEND:
58752   case ISD::FP_EXTEND:      return combineFP_EXTEND(N, DAG, Subtarget);
58753   case ISD::STRICT_FP_ROUND:
58754   case ISD::FP_ROUND:       return combineFP_ROUND(N, DAG, Subtarget);
58755   case X86ISD::VBROADCAST_LOAD:
58756   case X86ISD::SUBV_BROADCAST_LOAD: return combineBROADCAST_LOAD(N, DAG, DCI);
58757   case X86ISD::MOVDQ2Q:     return combineMOVDQ2Q(N, DAG);
58758   case X86ISD::PDEP:        return combinePDEP(N, DAG, DCI);
58759   }
58760 
58761   return SDValue();
58762 }
58763 
58764 bool X86TargetLowering::preferABDSToABSWithNSW(EVT VT) const {
58765   return false;
58766 }
58767 
58768 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
58769   if (!isTypeLegal(VT))
58770     return false;
58771 
58772   // There are no vXi8 shifts.
58773   if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
58774     return false;
58775 
58776   // TODO: Almost no 8-bit ops are desirable because they have no actual
58777   //       size/speed advantages vs. 32-bit ops, but they do have a major
58778   //       potential disadvantage by causing partial register stalls.
58779   //
58780   // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
58781   // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
58782   // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
58783   // check for a constant operand to the multiply.
58784   if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
58785     return false;
58786 
58787   // i16 instruction encodings are longer and some i16 instructions are slow,
58788   // so those are not desirable.
58789   if (VT == MVT::i16) {
58790     switch (Opc) {
58791     default:
58792       break;
58793     case ISD::LOAD:
58794     case ISD::SIGN_EXTEND:
58795     case ISD::ZERO_EXTEND:
58796     case ISD::ANY_EXTEND:
58797     case ISD::SHL:
58798     case ISD::SRA:
58799     case ISD::SRL:
58800     case ISD::SUB:
58801     case ISD::ADD:
58802     case ISD::MUL:
58803     case ISD::AND:
58804     case ISD::OR:
58805     case ISD::XOR:
58806       return false;
58807     }
58808   }
58809 
58810   // Any legal type not explicitly accounted for above here is desirable.
58811   return true;
58812 }
58813 
58814 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
58815                                                   SDValue Value, SDValue Addr,
58816                                                   SelectionDAG &DAG) const {
58817   const Module *M = DAG.getMachineFunction().getMMI().getModule();
58818   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
58819   if (IsCFProtectionSupported) {
58820     // In case control-flow branch protection is enabled, we need to add
58821     // notrack prefix to the indirect branch.
58822     // In order to do that we create NT_BRIND SDNode.
58823     // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
58824     return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
58825   }
58826 
58827   return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
58828 }
58829 
58830 TargetLowering::AndOrSETCCFoldKind
58831 X86TargetLowering::isDesirableToCombineLogicOpOfSETCC(
58832     const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const {
58833   using AndOrSETCCFoldKind = TargetLowering::AndOrSETCCFoldKind;
58834   EVT VT = LogicOp->getValueType(0);
58835   EVT OpVT = SETCC0->getOperand(0).getValueType();
58836   if (!VT.isInteger())
58837     return AndOrSETCCFoldKind::None;
58838 
58839   if (VT.isVector())
58840     return AndOrSETCCFoldKind(AndOrSETCCFoldKind::NotAnd |
58841                               (isOperationLegal(ISD::ABS, OpVT)
58842                                    ? AndOrSETCCFoldKind::ABS
58843                                    : AndOrSETCCFoldKind::None));
58844 
58845   // Don't use `NotAnd` as even though `not` is generally shorter code size than
58846   // `add`, `add` can lower to LEA which can save moves / spills. Any case where
58847   // `NotAnd` applies, `AddAnd` does as well.
58848   // TODO: Currently we lower (icmp eq/ne (and ~X, Y), 0) -> `test (not X), Y`,
58849   // if we change that to `andn Y, X` it may be worth prefering `NotAnd` here.
58850   return AndOrSETCCFoldKind::AddAnd;
58851 }
58852 
58853 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
58854   EVT VT = Op.getValueType();
58855   bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
58856                              isa<ConstantSDNode>(Op.getOperand(1));
58857 
58858   // i16 is legal, but undesirable since i16 instruction encodings are longer
58859   // and some i16 instructions are slow.
58860   // 8-bit multiply-by-constant can usually be expanded to something cheaper
58861   // using LEA and/or other ALU ops.
58862   if (VT != MVT::i16 && !Is8BitMulByConstant)
58863     return false;
58864 
58865   auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
58866     if (!Op.hasOneUse())
58867       return false;
58868     SDNode *User = *Op->use_begin();
58869     if (!ISD::isNormalStore(User))
58870       return false;
58871     auto *Ld = cast<LoadSDNode>(Load);
58872     auto *St = cast<StoreSDNode>(User);
58873     return Ld->getBasePtr() == St->getBasePtr();
58874   };
58875 
58876   auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
58877     if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
58878       return false;
58879     if (!Op.hasOneUse())
58880       return false;
58881     SDNode *User = *Op->use_begin();
58882     if (User->getOpcode() != ISD::ATOMIC_STORE)
58883       return false;
58884     auto *Ld = cast<AtomicSDNode>(Load);
58885     auto *St = cast<AtomicSDNode>(User);
58886     return Ld->getBasePtr() == St->getBasePtr();
58887   };
58888 
58889   bool Commute = false;
58890   switch (Op.getOpcode()) {
58891   default: return false;
58892   case ISD::SIGN_EXTEND:
58893   case ISD::ZERO_EXTEND:
58894   case ISD::ANY_EXTEND:
58895     break;
58896   case ISD::SHL:
58897   case ISD::SRA:
58898   case ISD::SRL: {
58899     SDValue N0 = Op.getOperand(0);
58900     // Look out for (store (shl (load), x)).
58901     if (X86::mayFoldLoad(N0, Subtarget) && IsFoldableRMW(N0, Op))
58902       return false;
58903     break;
58904   }
58905   case ISD::ADD:
58906   case ISD::MUL:
58907   case ISD::AND:
58908   case ISD::OR:
58909   case ISD::XOR:
58910     Commute = true;
58911     [[fallthrough]];
58912   case ISD::SUB: {
58913     SDValue N0 = Op.getOperand(0);
58914     SDValue N1 = Op.getOperand(1);
58915     // Avoid disabling potential load folding opportunities.
58916     if (X86::mayFoldLoad(N1, Subtarget) &&
58917         (!Commute || !isa<ConstantSDNode>(N0) ||
58918          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
58919       return false;
58920     if (X86::mayFoldLoad(N0, Subtarget) &&
58921         ((Commute && !isa<ConstantSDNode>(N1)) ||
58922          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
58923       return false;
58924     if (IsFoldableAtomicRMW(N0, Op) ||
58925         (Commute && IsFoldableAtomicRMW(N1, Op)))
58926       return false;
58927   }
58928   }
58929 
58930   PVT = MVT::i32;
58931   return true;
58932 }
58933 
58934 //===----------------------------------------------------------------------===//
58935 //                           X86 Inline Assembly Support
58936 //===----------------------------------------------------------------------===//
58937 
58938 // Helper to match a string separated by whitespace.
58939 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
58940   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
58941 
58942   for (StringRef Piece : Pieces) {
58943     if (!S.startswith(Piece)) // Check if the piece matches.
58944       return false;
58945 
58946     S = S.substr(Piece.size());
58947     StringRef::size_type Pos = S.find_first_not_of(" \t");
58948     if (Pos == 0) // We matched a prefix.
58949       return false;
58950 
58951     S = S.substr(Pos);
58952   }
58953 
58954   return S.empty();
58955 }
58956 
58957 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
58958 
58959   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
58960     if (llvm::is_contained(AsmPieces, "~{cc}") &&
58961         llvm::is_contained(AsmPieces, "~{flags}") &&
58962         llvm::is_contained(AsmPieces, "~{fpsr}")) {
58963 
58964       if (AsmPieces.size() == 3)
58965         return true;
58966       else if (llvm::is_contained(AsmPieces, "~{dirflag}"))
58967         return true;
58968     }
58969   }
58970   return false;
58971 }
58972 
58973 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
58974   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
58975 
58976   const std::string &AsmStr = IA->getAsmString();
58977 
58978   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
58979   if (!Ty || Ty->getBitWidth() % 16 != 0)
58980     return false;
58981 
58982   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
58983   SmallVector<StringRef, 4> AsmPieces;
58984   SplitString(AsmStr, AsmPieces, ";\n");
58985 
58986   switch (AsmPieces.size()) {
58987   default: return false;
58988   case 1:
58989     // FIXME: this should verify that we are targeting a 486 or better.  If not,
58990     // we will turn this bswap into something that will be lowered to logical
58991     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
58992     // lower so don't worry about this.
58993     // bswap $0
58994     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
58995         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
58996         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
58997         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
58998         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
58999         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
59000       // No need to check constraints, nothing other than the equivalent of
59001       // "=r,0" would be valid here.
59002       return IntrinsicLowering::LowerToByteSwap(CI);
59003     }
59004 
59005     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
59006     if (CI->getType()->isIntegerTy(16) &&
59007         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
59008         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
59009          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
59010       AsmPieces.clear();
59011       StringRef ConstraintsStr = IA->getConstraintString();
59012       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
59013       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
59014       if (clobbersFlagRegisters(AsmPieces))
59015         return IntrinsicLowering::LowerToByteSwap(CI);
59016     }
59017     break;
59018   case 3:
59019     if (CI->getType()->isIntegerTy(32) &&
59020         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
59021         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
59022         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
59023         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
59024       AsmPieces.clear();
59025       StringRef ConstraintsStr = IA->getConstraintString();
59026       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
59027       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
59028       if (clobbersFlagRegisters(AsmPieces))
59029         return IntrinsicLowering::LowerToByteSwap(CI);
59030     }
59031 
59032     if (CI->getType()->isIntegerTy(64)) {
59033       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
59034       if (Constraints.size() >= 2 &&
59035           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
59036           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
59037         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
59038         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
59039             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
59040             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
59041           return IntrinsicLowering::LowerToByteSwap(CI);
59042       }
59043     }
59044     break;
59045   }
59046   return false;
59047 }
59048 
59049 static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
59050   X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
59051                            .Case("{@cca}", X86::COND_A)
59052                            .Case("{@ccae}", X86::COND_AE)
59053                            .Case("{@ccb}", X86::COND_B)
59054                            .Case("{@ccbe}", X86::COND_BE)
59055                            .Case("{@ccc}", X86::COND_B)
59056                            .Case("{@cce}", X86::COND_E)
59057                            .Case("{@ccz}", X86::COND_E)
59058                            .Case("{@ccg}", X86::COND_G)
59059                            .Case("{@ccge}", X86::COND_GE)
59060                            .Case("{@ccl}", X86::COND_L)
59061                            .Case("{@ccle}", X86::COND_LE)
59062                            .Case("{@ccna}", X86::COND_BE)
59063                            .Case("{@ccnae}", X86::COND_B)
59064                            .Case("{@ccnb}", X86::COND_AE)
59065                            .Case("{@ccnbe}", X86::COND_A)
59066                            .Case("{@ccnc}", X86::COND_AE)
59067                            .Case("{@ccne}", X86::COND_NE)
59068                            .Case("{@ccnz}", X86::COND_NE)
59069                            .Case("{@ccng}", X86::COND_LE)
59070                            .Case("{@ccnge}", X86::COND_L)
59071                            .Case("{@ccnl}", X86::COND_GE)
59072                            .Case("{@ccnle}", X86::COND_G)
59073                            .Case("{@ccno}", X86::COND_NO)
59074                            .Case("{@ccnp}", X86::COND_NP)
59075                            .Case("{@ccns}", X86::COND_NS)
59076                            .Case("{@cco}", X86::COND_O)
59077                            .Case("{@ccp}", X86::COND_P)
59078                            .Case("{@ccs}", X86::COND_S)
59079                            .Default(X86::COND_INVALID);
59080   return Cond;
59081 }
59082 
59083 /// Given a constraint letter, return the type of constraint for this target.
59084 X86TargetLowering::ConstraintType
59085 X86TargetLowering::getConstraintType(StringRef Constraint) const {
59086   if (Constraint.size() == 1) {
59087     switch (Constraint[0]) {
59088     case 'R':
59089     case 'q':
59090     case 'Q':
59091     case 'f':
59092     case 't':
59093     case 'u':
59094     case 'y':
59095     case 'x':
59096     case 'v':
59097     case 'l':
59098     case 'k': // AVX512 masking registers.
59099       return C_RegisterClass;
59100     case 'a':
59101     case 'b':
59102     case 'c':
59103     case 'd':
59104     case 'S':
59105     case 'D':
59106     case 'A':
59107       return C_Register;
59108     case 'I':
59109     case 'J':
59110     case 'K':
59111     case 'N':
59112     case 'G':
59113     case 'L':
59114     case 'M':
59115       return C_Immediate;
59116     case 'C':
59117     case 'e':
59118     case 'Z':
59119       return C_Other;
59120     default:
59121       break;
59122     }
59123   }
59124   else if (Constraint.size() == 2) {
59125     switch (Constraint[0]) {
59126     default:
59127       break;
59128     case 'Y':
59129       switch (Constraint[1]) {
59130       default:
59131         break;
59132       case 'z':
59133         return C_Register;
59134       case 'i':
59135       case 'm':
59136       case 'k':
59137       case 't':
59138       case '2':
59139         return C_RegisterClass;
59140       }
59141     }
59142   } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
59143     return C_Other;
59144   return TargetLowering::getConstraintType(Constraint);
59145 }
59146 
59147 /// Examine constraint type and operand type and determine a weight value.
59148 /// This object must already have been set up with the operand type
59149 /// and the current alternative constraint selected.
59150 TargetLowering::ConstraintWeight
59151   X86TargetLowering::getSingleConstraintMatchWeight(
59152     AsmOperandInfo &info, const char *constraint) const {
59153   ConstraintWeight weight = CW_Invalid;
59154   Value *CallOperandVal = info.CallOperandVal;
59155     // If we don't have a value, we can't do a match,
59156     // but allow it at the lowest weight.
59157   if (!CallOperandVal)
59158     return CW_Default;
59159   Type *type = CallOperandVal->getType();
59160   // Look at the constraint type.
59161   switch (*constraint) {
59162   default:
59163     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
59164     [[fallthrough]];
59165   case 'R':
59166   case 'q':
59167   case 'Q':
59168   case 'a':
59169   case 'b':
59170   case 'c':
59171   case 'd':
59172   case 'S':
59173   case 'D':
59174   case 'A':
59175     if (CallOperandVal->getType()->isIntegerTy())
59176       weight = CW_SpecificReg;
59177     break;
59178   case 'f':
59179   case 't':
59180   case 'u':
59181     if (type->isFloatingPointTy())
59182       weight = CW_SpecificReg;
59183     break;
59184   case 'y':
59185     if (type->isX86_MMXTy() && Subtarget.hasMMX())
59186       weight = CW_SpecificReg;
59187     break;
59188   case 'Y':
59189     if (StringRef(constraint).size() != 2)
59190       break;
59191     switch (constraint[1]) {
59192       default:
59193         return CW_Invalid;
59194       // XMM0
59195       case 'z':
59196         if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
59197             ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()) ||
59198             ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512()))
59199           return CW_SpecificReg;
59200         return CW_Invalid;
59201       // Conditional OpMask regs (AVX512)
59202       case 'k':
59203         if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
59204           return CW_Register;
59205         return CW_Invalid;
59206       // Any MMX reg
59207       case 'm':
59208         if (type->isX86_MMXTy() && Subtarget.hasMMX())
59209           return weight;
59210         return CW_Invalid;
59211       // Any SSE reg when ISA >= SSE2, same as 'x'
59212       case 'i':
59213       case 't':
59214       case '2':
59215         if (!Subtarget.hasSSE2())
59216           return CW_Invalid;
59217         break;
59218     }
59219     break;
59220   case 'v':
59221     if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
59222       weight = CW_Register;
59223     [[fallthrough]];
59224   case 'x':
59225     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
59226         ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
59227       weight = CW_Register;
59228     break;
59229   case 'k':
59230     // Enable conditional vector operations using %k<#> registers.
59231     if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
59232       weight = CW_Register;
59233     break;
59234   case 'I':
59235     if (auto *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
59236       if (C->getZExtValue() <= 31)
59237         weight = CW_Constant;
59238     }
59239     break;
59240   case 'J':
59241     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
59242       if (C->getZExtValue() <= 63)
59243         weight = CW_Constant;
59244     }
59245     break;
59246   case 'K':
59247     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
59248       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
59249         weight = CW_Constant;
59250     }
59251     break;
59252   case 'L':
59253     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
59254       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
59255         weight = CW_Constant;
59256     }
59257     break;
59258   case 'M':
59259     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
59260       if (C->getZExtValue() <= 3)
59261         weight = CW_Constant;
59262     }
59263     break;
59264   case 'N':
59265     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
59266       if (C->getZExtValue() <= 0xff)
59267         weight = CW_Constant;
59268     }
59269     break;
59270   case 'G':
59271   case 'C':
59272     if (isa<ConstantFP>(CallOperandVal)) {
59273       weight = CW_Constant;
59274     }
59275     break;
59276   case 'e':
59277     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
59278       if ((C->getSExtValue() >= -0x80000000LL) &&
59279           (C->getSExtValue() <= 0x7fffffffLL))
59280         weight = CW_Constant;
59281     }
59282     break;
59283   case 'Z':
59284     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal)) {
59285       if (C->getZExtValue() <= 0xffffffff)
59286         weight = CW_Constant;
59287     }
59288     break;
59289   }
59290   return weight;
59291 }
59292 
59293 /// Try to replace an X constraint, which matches anything, with another that
59294 /// has more specific requirements based on the type of the corresponding
59295 /// operand.
59296 const char *X86TargetLowering::
59297 LowerXConstraint(EVT ConstraintVT) const {
59298   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
59299   // 'f' like normal targets.
59300   if (ConstraintVT.isFloatingPoint()) {
59301     if (Subtarget.hasSSE1())
59302       return "x";
59303   }
59304 
59305   return TargetLowering::LowerXConstraint(ConstraintVT);
59306 }
59307 
59308 // Lower @cc targets via setcc.
59309 SDValue X86TargetLowering::LowerAsmOutputForConstraint(
59310     SDValue &Chain, SDValue &Glue, const SDLoc &DL,
59311     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
59312   X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
59313   if (Cond == X86::COND_INVALID)
59314     return SDValue();
59315   // Check that return type is valid.
59316   if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
59317       OpInfo.ConstraintVT.getSizeInBits() < 8)
59318     report_fatal_error("Glue output operand is of invalid type");
59319 
59320   // Get EFLAGS register. Only update chain when copyfrom is glued.
59321   if (Glue.getNode()) {
59322     Glue = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Glue);
59323     Chain = Glue.getValue(1);
59324   } else
59325     Glue = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
59326   // Extract CC code.
59327   SDValue CC = getSETCC(Cond, Glue, DL, DAG);
59328   // Extend to 32-bits
59329   SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
59330 
59331   return Result;
59332 }
59333 
59334 /// Lower the specified operand into the Ops vector.
59335 /// If it is invalid, don't add anything to Ops.
59336 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
59337                                                      std::string &Constraint,
59338                                                      std::vector<SDValue>&Ops,
59339                                                      SelectionDAG &DAG) const {
59340   SDValue Result;
59341 
59342   // Only support length 1 constraints for now.
59343   if (Constraint.length() > 1) return;
59344 
59345   char ConstraintLetter = Constraint[0];
59346   switch (ConstraintLetter) {
59347   default: break;
59348   case 'I':
59349     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59350       if (C->getZExtValue() <= 31) {
59351         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59352                                        Op.getValueType());
59353         break;
59354       }
59355     }
59356     return;
59357   case 'J':
59358     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59359       if (C->getZExtValue() <= 63) {
59360         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59361                                        Op.getValueType());
59362         break;
59363       }
59364     }
59365     return;
59366   case 'K':
59367     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59368       if (isInt<8>(C->getSExtValue())) {
59369         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59370                                        Op.getValueType());
59371         break;
59372       }
59373     }
59374     return;
59375   case 'L':
59376     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59377       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
59378           (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
59379         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
59380                                        Op.getValueType());
59381         break;
59382       }
59383     }
59384     return;
59385   case 'M':
59386     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59387       if (C->getZExtValue() <= 3) {
59388         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59389                                        Op.getValueType());
59390         break;
59391       }
59392     }
59393     return;
59394   case 'N':
59395     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59396       if (C->getZExtValue() <= 255) {
59397         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59398                                        Op.getValueType());
59399         break;
59400       }
59401     }
59402     return;
59403   case 'O':
59404     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59405       if (C->getZExtValue() <= 127) {
59406         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59407                                        Op.getValueType());
59408         break;
59409       }
59410     }
59411     return;
59412   case 'e': {
59413     // 32-bit signed value
59414     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59415       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
59416                                            C->getSExtValue())) {
59417         // Widen to 64 bits here to get it sign extended.
59418         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
59419         break;
59420       }
59421     // FIXME gcc accepts some relocatable values here too, but only in certain
59422     // memory models; it's complicated.
59423     }
59424     return;
59425   }
59426   case 'Z': {
59427     // 32-bit unsigned value
59428     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59429       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
59430                                            C->getZExtValue())) {
59431         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59432                                        Op.getValueType());
59433         break;
59434       }
59435     }
59436     // FIXME gcc accepts some relocatable values here too, but only in certain
59437     // memory models; it's complicated.
59438     return;
59439   }
59440   case 'i': {
59441     // Literal immediates are always ok.
59442     if (auto *CST = dyn_cast<ConstantSDNode>(Op)) {
59443       bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
59444       BooleanContent BCont = getBooleanContents(MVT::i64);
59445       ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
59446                                     : ISD::SIGN_EXTEND;
59447       int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
59448                                                   : CST->getSExtValue();
59449       Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
59450       break;
59451     }
59452 
59453     // In any sort of PIC mode addresses need to be computed at runtime by
59454     // adding in a register or some sort of table lookup.  These can't
59455     // be used as immediates. BlockAddresses and BasicBlocks are fine though.
59456     if ((Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC()) &&
59457         !(isa<BlockAddressSDNode>(Op) || isa<BasicBlockSDNode>(Op)))
59458       return;
59459 
59460     // If we are in non-pic codegen mode, we allow the address of a global (with
59461     // an optional displacement) to be used with 'i'.
59462     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
59463       // If we require an extra load to get this address, as in PIC mode, we
59464       // can't accept it.
59465       if (isGlobalStubReference(
59466               Subtarget.classifyGlobalReference(GA->getGlobal())))
59467         return;
59468     break;
59469   }
59470   }
59471 
59472   if (Result.getNode()) {
59473     Ops.push_back(Result);
59474     return;
59475   }
59476   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
59477 }
59478 
59479 /// Check if \p RC is a general purpose register class.
59480 /// I.e., GR* or one of their variant.
59481 static bool isGRClass(const TargetRegisterClass &RC) {
59482   return RC.hasSuperClassEq(&X86::GR8RegClass) ||
59483          RC.hasSuperClassEq(&X86::GR16RegClass) ||
59484          RC.hasSuperClassEq(&X86::GR32RegClass) ||
59485          RC.hasSuperClassEq(&X86::GR64RegClass) ||
59486          RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
59487 }
59488 
59489 /// Check if \p RC is a vector register class.
59490 /// I.e., FR* / VR* or one of their variant.
59491 static bool isFRClass(const TargetRegisterClass &RC) {
59492   return RC.hasSuperClassEq(&X86::FR16XRegClass) ||
59493          RC.hasSuperClassEq(&X86::FR32XRegClass) ||
59494          RC.hasSuperClassEq(&X86::FR64XRegClass) ||
59495          RC.hasSuperClassEq(&X86::VR128XRegClass) ||
59496          RC.hasSuperClassEq(&X86::VR256XRegClass) ||
59497          RC.hasSuperClassEq(&X86::VR512RegClass);
59498 }
59499 
59500 /// Check if \p RC is a mask register class.
59501 /// I.e., VK* or one of their variant.
59502 static bool isVKClass(const TargetRegisterClass &RC) {
59503   return RC.hasSuperClassEq(&X86::VK1RegClass) ||
59504          RC.hasSuperClassEq(&X86::VK2RegClass) ||
59505          RC.hasSuperClassEq(&X86::VK4RegClass) ||
59506          RC.hasSuperClassEq(&X86::VK8RegClass) ||
59507          RC.hasSuperClassEq(&X86::VK16RegClass) ||
59508          RC.hasSuperClassEq(&X86::VK32RegClass) ||
59509          RC.hasSuperClassEq(&X86::VK64RegClass);
59510 }
59511 
59512 std::pair<unsigned, const TargetRegisterClass *>
59513 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
59514                                                 StringRef Constraint,
59515                                                 MVT VT) const {
59516   // First, see if this is a constraint that directly corresponds to an LLVM
59517   // register class.
59518   if (Constraint.size() == 1) {
59519     // GCC Constraint Letters
59520     switch (Constraint[0]) {
59521     default: break;
59522     // 'A' means [ER]AX + [ER]DX.
59523     case 'A':
59524       if (Subtarget.is64Bit())
59525         return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
59526       assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
59527              "Expecting 64, 32 or 16 bit subtarget");
59528       return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
59529 
59530       // TODO: Slight differences here in allocation order and leaving
59531       // RIP in the class. Do they matter any more here than they do
59532       // in the normal allocation?
59533     case 'k':
59534       if (Subtarget.hasAVX512()) {
59535         if (VT == MVT::i1)
59536           return std::make_pair(0U, &X86::VK1RegClass);
59537         if (VT == MVT::i8)
59538           return std::make_pair(0U, &X86::VK8RegClass);
59539         if (VT == MVT::i16)
59540           return std::make_pair(0U, &X86::VK16RegClass);
59541       }
59542       if (Subtarget.hasBWI()) {
59543         if (VT == MVT::i32)
59544           return std::make_pair(0U, &X86::VK32RegClass);
59545         if (VT == MVT::i64)
59546           return std::make_pair(0U, &X86::VK64RegClass);
59547       }
59548       break;
59549     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
59550       if (Subtarget.is64Bit()) {
59551         if (VT == MVT::i8 || VT == MVT::i1)
59552           return std::make_pair(0U, &X86::GR8RegClass);
59553         if (VT == MVT::i16)
59554           return std::make_pair(0U, &X86::GR16RegClass);
59555         if (VT == MVT::i32 || VT == MVT::f32)
59556           return std::make_pair(0U, &X86::GR32RegClass);
59557         if (VT != MVT::f80 && !VT.isVector())
59558           return std::make_pair(0U, &X86::GR64RegClass);
59559         break;
59560       }
59561       [[fallthrough]];
59562       // 32-bit fallthrough
59563     case 'Q':   // Q_REGS
59564       if (VT == MVT::i8 || VT == MVT::i1)
59565         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
59566       if (VT == MVT::i16)
59567         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
59568       if (VT == MVT::i32 || VT == MVT::f32 ||
59569           (!VT.isVector() && !Subtarget.is64Bit()))
59570         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
59571       if (VT != MVT::f80 && !VT.isVector())
59572         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
59573       break;
59574     case 'r':   // GENERAL_REGS
59575     case 'l':   // INDEX_REGS
59576       if (VT == MVT::i8 || VT == MVT::i1)
59577         return std::make_pair(0U, &X86::GR8RegClass);
59578       if (VT == MVT::i16)
59579         return std::make_pair(0U, &X86::GR16RegClass);
59580       if (VT == MVT::i32 || VT == MVT::f32 ||
59581           (!VT.isVector() && !Subtarget.is64Bit()))
59582         return std::make_pair(0U, &X86::GR32RegClass);
59583       if (VT != MVT::f80 && !VT.isVector())
59584         return std::make_pair(0U, &X86::GR64RegClass);
59585       break;
59586     case 'R':   // LEGACY_REGS
59587       if (VT == MVT::i8 || VT == MVT::i1)
59588         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
59589       if (VT == MVT::i16)
59590         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
59591       if (VT == MVT::i32 || VT == MVT::f32 ||
59592           (!VT.isVector() && !Subtarget.is64Bit()))
59593         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
59594       if (VT != MVT::f80 && !VT.isVector())
59595         return std::make_pair(0U, &X86::GR64_NOREXRegClass);
59596       break;
59597     case 'f':  // FP Stack registers.
59598       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
59599       // value to the correct fpstack register class.
59600       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
59601         return std::make_pair(0U, &X86::RFP32RegClass);
59602       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
59603         return std::make_pair(0U, &X86::RFP64RegClass);
59604       if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80)
59605         return std::make_pair(0U, &X86::RFP80RegClass);
59606       break;
59607     case 'y':   // MMX_REGS if MMX allowed.
59608       if (!Subtarget.hasMMX()) break;
59609       return std::make_pair(0U, &X86::VR64RegClass);
59610     case 'v':
59611     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
59612       if (!Subtarget.hasSSE1()) break;
59613       bool VConstraint = (Constraint[0] == 'v');
59614 
59615       switch (VT.SimpleTy) {
59616       default: break;
59617       // Scalar SSE types.
59618       case MVT::f16:
59619         if (VConstraint && Subtarget.hasFP16())
59620           return std::make_pair(0U, &X86::FR16XRegClass);
59621         break;
59622       case MVT::f32:
59623       case MVT::i32:
59624         if (VConstraint && Subtarget.hasVLX())
59625           return std::make_pair(0U, &X86::FR32XRegClass);
59626         return std::make_pair(0U, &X86::FR32RegClass);
59627       case MVT::f64:
59628       case MVT::i64:
59629         if (VConstraint && Subtarget.hasVLX())
59630           return std::make_pair(0U, &X86::FR64XRegClass);
59631         return std::make_pair(0U, &X86::FR64RegClass);
59632       case MVT::i128:
59633         if (Subtarget.is64Bit()) {
59634           if (VConstraint && Subtarget.hasVLX())
59635             return std::make_pair(0U, &X86::VR128XRegClass);
59636           return std::make_pair(0U, &X86::VR128RegClass);
59637         }
59638         break;
59639       // Vector types and fp128.
59640       case MVT::v8f16:
59641         if (!Subtarget.hasFP16())
59642           break;
59643         [[fallthrough]];
59644       case MVT::f128:
59645       case MVT::v16i8:
59646       case MVT::v8i16:
59647       case MVT::v4i32:
59648       case MVT::v2i64:
59649       case MVT::v4f32:
59650       case MVT::v2f64:
59651         if (VConstraint && Subtarget.hasVLX())
59652           return std::make_pair(0U, &X86::VR128XRegClass);
59653         return std::make_pair(0U, &X86::VR128RegClass);
59654       // AVX types.
59655       case MVT::v16f16:
59656         if (!Subtarget.hasFP16())
59657           break;
59658         [[fallthrough]];
59659       case MVT::v32i8:
59660       case MVT::v16i16:
59661       case MVT::v8i32:
59662       case MVT::v4i64:
59663       case MVT::v8f32:
59664       case MVT::v4f64:
59665         if (VConstraint && Subtarget.hasVLX())
59666           return std::make_pair(0U, &X86::VR256XRegClass);
59667         if (Subtarget.hasAVX())
59668           return std::make_pair(0U, &X86::VR256RegClass);
59669         break;
59670       case MVT::v32f16:
59671         if (!Subtarget.hasFP16())
59672           break;
59673         [[fallthrough]];
59674       case MVT::v64i8:
59675       case MVT::v32i16:
59676       case MVT::v8f64:
59677       case MVT::v16f32:
59678       case MVT::v16i32:
59679       case MVT::v8i64:
59680         if (!Subtarget.hasAVX512()) break;
59681         if (VConstraint)
59682           return std::make_pair(0U, &X86::VR512RegClass);
59683         return std::make_pair(0U, &X86::VR512_0_15RegClass);
59684       }
59685       break;
59686     }
59687   } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
59688     switch (Constraint[1]) {
59689     default:
59690       break;
59691     case 'i':
59692     case 't':
59693     case '2':
59694       return getRegForInlineAsmConstraint(TRI, "x", VT);
59695     case 'm':
59696       if (!Subtarget.hasMMX()) break;
59697       return std::make_pair(0U, &X86::VR64RegClass);
59698     case 'z':
59699       if (!Subtarget.hasSSE1()) break;
59700       switch (VT.SimpleTy) {
59701       default: break;
59702       // Scalar SSE types.
59703       case MVT::f16:
59704         if (!Subtarget.hasFP16())
59705           break;
59706         return std::make_pair(X86::XMM0, &X86::FR16XRegClass);
59707       case MVT::f32:
59708       case MVT::i32:
59709         return std::make_pair(X86::XMM0, &X86::FR32RegClass);
59710       case MVT::f64:
59711       case MVT::i64:
59712         return std::make_pair(X86::XMM0, &X86::FR64RegClass);
59713       case MVT::v8f16:
59714         if (!Subtarget.hasFP16())
59715           break;
59716         [[fallthrough]];
59717       case MVT::f128:
59718       case MVT::v16i8:
59719       case MVT::v8i16:
59720       case MVT::v4i32:
59721       case MVT::v2i64:
59722       case MVT::v4f32:
59723       case MVT::v2f64:
59724         return std::make_pair(X86::XMM0, &X86::VR128RegClass);
59725       // AVX types.
59726       case MVT::v16f16:
59727         if (!Subtarget.hasFP16())
59728           break;
59729         [[fallthrough]];
59730       case MVT::v32i8:
59731       case MVT::v16i16:
59732       case MVT::v8i32:
59733       case MVT::v4i64:
59734       case MVT::v8f32:
59735       case MVT::v4f64:
59736         if (Subtarget.hasAVX())
59737           return std::make_pair(X86::YMM0, &X86::VR256RegClass);
59738         break;
59739       case MVT::v32f16:
59740         if (!Subtarget.hasFP16())
59741           break;
59742         [[fallthrough]];
59743       case MVT::v64i8:
59744       case MVT::v32i16:
59745       case MVT::v8f64:
59746       case MVT::v16f32:
59747       case MVT::v16i32:
59748       case MVT::v8i64:
59749         if (Subtarget.hasAVX512())
59750           return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
59751         break;
59752       }
59753       break;
59754     case 'k':
59755       // This register class doesn't allocate k0 for masked vector operation.
59756       if (Subtarget.hasAVX512()) {
59757         if (VT == MVT::i1)
59758           return std::make_pair(0U, &X86::VK1WMRegClass);
59759         if (VT == MVT::i8)
59760           return std::make_pair(0U, &X86::VK8WMRegClass);
59761         if (VT == MVT::i16)
59762           return std::make_pair(0U, &X86::VK16WMRegClass);
59763       }
59764       if (Subtarget.hasBWI()) {
59765         if (VT == MVT::i32)
59766           return std::make_pair(0U, &X86::VK32WMRegClass);
59767         if (VT == MVT::i64)
59768           return std::make_pair(0U, &X86::VK64WMRegClass);
59769       }
59770       break;
59771     }
59772   }
59773 
59774   if (parseConstraintCode(Constraint) != X86::COND_INVALID)
59775     return std::make_pair(0U, &X86::GR32RegClass);
59776 
59777   // Use the default implementation in TargetLowering to convert the register
59778   // constraint into a member of a register class.
59779   std::pair<Register, const TargetRegisterClass*> Res;
59780   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
59781 
59782   // Not found as a standard register?
59783   if (!Res.second) {
59784     // Only match x87 registers if the VT is one SelectionDAGBuilder can convert
59785     // to/from f80.
59786     if (VT == MVT::Other || VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80) {
59787       // Map st(0) -> st(7) -> ST0
59788       if (Constraint.size() == 7 && Constraint[0] == '{' &&
59789           tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
59790           Constraint[3] == '(' &&
59791           (Constraint[4] >= '0' && Constraint[4] <= '7') &&
59792           Constraint[5] == ')' && Constraint[6] == '}') {
59793         // st(7) is not allocatable and thus not a member of RFP80. Return
59794         // singleton class in cases where we have a reference to it.
59795         if (Constraint[4] == '7')
59796           return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
59797         return std::make_pair(X86::FP0 + Constraint[4] - '0',
59798                               &X86::RFP80RegClass);
59799       }
59800 
59801       // GCC allows "st(0)" to be called just plain "st".
59802       if (StringRef("{st}").equals_insensitive(Constraint))
59803         return std::make_pair(X86::FP0, &X86::RFP80RegClass);
59804     }
59805 
59806     // flags -> EFLAGS
59807     if (StringRef("{flags}").equals_insensitive(Constraint))
59808       return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
59809 
59810     // dirflag -> DF
59811     // Only allow for clobber.
59812     if (StringRef("{dirflag}").equals_insensitive(Constraint) &&
59813         VT == MVT::Other)
59814       return std::make_pair(X86::DF, &X86::DFCCRRegClass);
59815 
59816     // fpsr -> FPSW
59817     if (StringRef("{fpsr}").equals_insensitive(Constraint))
59818       return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
59819 
59820     return Res;
59821   }
59822 
59823   // Make sure it isn't a register that requires 64-bit mode.
59824   if (!Subtarget.is64Bit() &&
59825       (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
59826       TRI->getEncodingValue(Res.first) >= 8) {
59827     // Register requires REX prefix, but we're in 32-bit mode.
59828     return std::make_pair(0, nullptr);
59829   }
59830 
59831   // Make sure it isn't a register that requires AVX512.
59832   if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
59833       TRI->getEncodingValue(Res.first) & 0x10) {
59834     // Register requires EVEX prefix.
59835     return std::make_pair(0, nullptr);
59836   }
59837 
59838   // Otherwise, check to see if this is a register class of the wrong value
59839   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
59840   // turn into {ax},{dx}.
59841   // MVT::Other is used to specify clobber names.
59842   if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
59843     return Res;   // Correct type already, nothing to do.
59844 
59845   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
59846   // return "eax". This should even work for things like getting 64bit integer
59847   // registers when given an f64 type.
59848   const TargetRegisterClass *Class = Res.second;
59849   // The generic code will match the first register class that contains the
59850   // given register. Thus, based on the ordering of the tablegened file,
59851   // the "plain" GR classes might not come first.
59852   // Therefore, use a helper method.
59853   if (isGRClass(*Class)) {
59854     unsigned Size = VT.getSizeInBits();
59855     if (Size == 1) Size = 8;
59856     if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
59857       return std::make_pair(0, nullptr);
59858     Register DestReg = getX86SubSuperRegister(Res.first, Size);
59859     if (DestReg.isValid()) {
59860       bool is64Bit = Subtarget.is64Bit();
59861       const TargetRegisterClass *RC =
59862           Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
59863         : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
59864         : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
59865         : /*Size == 64*/ (is64Bit ? &X86::GR64RegClass : nullptr);
59866       if (Size == 64 && !is64Bit) {
59867         // Model GCC's behavior here and select a fixed pair of 32-bit
59868         // registers.
59869         switch (DestReg) {
59870         case X86::RAX:
59871           return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
59872         case X86::RDX:
59873           return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
59874         case X86::RCX:
59875           return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
59876         case X86::RBX:
59877           return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
59878         case X86::RSI:
59879           return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
59880         case X86::RDI:
59881           return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
59882         case X86::RBP:
59883           return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
59884         default:
59885           return std::make_pair(0, nullptr);
59886         }
59887       }
59888       if (RC && RC->contains(DestReg))
59889         return std::make_pair(DestReg, RC);
59890       return Res;
59891     }
59892     // No register found/type mismatch.
59893     return std::make_pair(0, nullptr);
59894   } else if (isFRClass(*Class)) {
59895     // Handle references to XMM physical registers that got mapped into the
59896     // wrong class.  This can happen with constraints like {xmm0} where the
59897     // target independent register mapper will just pick the first match it can
59898     // find, ignoring the required type.
59899 
59900     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
59901     if (VT == MVT::f16)
59902       Res.second = &X86::FR16XRegClass;
59903     else if (VT == MVT::f32 || VT == MVT::i32)
59904       Res.second = &X86::FR32XRegClass;
59905     else if (VT == MVT::f64 || VT == MVT::i64)
59906       Res.second = &X86::FR64XRegClass;
59907     else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
59908       Res.second = &X86::VR128XRegClass;
59909     else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
59910       Res.second = &X86::VR256XRegClass;
59911     else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
59912       Res.second = &X86::VR512RegClass;
59913     else {
59914       // Type mismatch and not a clobber: Return an error;
59915       Res.first = 0;
59916       Res.second = nullptr;
59917     }
59918   } else if (isVKClass(*Class)) {
59919     if (VT == MVT::i1)
59920       Res.second = &X86::VK1RegClass;
59921     else if (VT == MVT::i8)
59922       Res.second = &X86::VK8RegClass;
59923     else if (VT == MVT::i16)
59924       Res.second = &X86::VK16RegClass;
59925     else if (VT == MVT::i32)
59926       Res.second = &X86::VK32RegClass;
59927     else if (VT == MVT::i64)
59928       Res.second = &X86::VK64RegClass;
59929     else {
59930       // Type mismatch and not a clobber: Return an error;
59931       Res.first = 0;
59932       Res.second = nullptr;
59933     }
59934   }
59935 
59936   return Res;
59937 }
59938 
59939 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
59940   // Integer division on x86 is expensive. However, when aggressively optimizing
59941   // for code size, we prefer to use a div instruction, as it is usually smaller
59942   // than the alternative sequence.
59943   // The exception to this is vector division. Since x86 doesn't have vector
59944   // integer division, leaving the division as-is is a loss even in terms of
59945   // size, because it will have to be scalarized, while the alternative code
59946   // sequence can be performed in vector form.
59947   bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
59948   return OptSize && !VT.isVector();
59949 }
59950 
59951 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
59952   if (!Subtarget.is64Bit())
59953     return;
59954 
59955   // Update IsSplitCSR in X86MachineFunctionInfo.
59956   X86MachineFunctionInfo *AFI =
59957       Entry->getParent()->getInfo<X86MachineFunctionInfo>();
59958   AFI->setIsSplitCSR(true);
59959 }
59960 
59961 void X86TargetLowering::insertCopiesSplitCSR(
59962     MachineBasicBlock *Entry,
59963     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
59964   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
59965   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
59966   if (!IStart)
59967     return;
59968 
59969   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
59970   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
59971   MachineBasicBlock::iterator MBBI = Entry->begin();
59972   for (const MCPhysReg *I = IStart; *I; ++I) {
59973     const TargetRegisterClass *RC = nullptr;
59974     if (X86::GR64RegClass.contains(*I))
59975       RC = &X86::GR64RegClass;
59976     else
59977       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
59978 
59979     Register NewVR = MRI->createVirtualRegister(RC);
59980     // Create copy from CSR to a virtual register.
59981     // FIXME: this currently does not emit CFI pseudo-instructions, it works
59982     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
59983     // nounwind. If we want to generalize this later, we may need to emit
59984     // CFI pseudo-instructions.
59985     assert(
59986         Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&
59987         "Function should be nounwind in insertCopiesSplitCSR!");
59988     Entry->addLiveIn(*I);
59989     BuildMI(*Entry, MBBI, MIMetadata(), TII->get(TargetOpcode::COPY), NewVR)
59990         .addReg(*I);
59991 
59992     // Insert the copy-back instructions right before the terminator.
59993     for (auto *Exit : Exits)
59994       BuildMI(*Exit, Exit->getFirstTerminator(), MIMetadata(),
59995               TII->get(TargetOpcode::COPY), *I)
59996           .addReg(NewVR);
59997   }
59998 }
59999 
60000 bool X86TargetLowering::supportSwiftError() const {
60001   return Subtarget.is64Bit();
60002 }
60003 
60004 MachineInstr *
60005 X86TargetLowering::EmitKCFICheck(MachineBasicBlock &MBB,
60006                                  MachineBasicBlock::instr_iterator &MBBI,
60007                                  const TargetInstrInfo *TII) const {
60008   assert(MBBI->isCall() && MBBI->getCFIType() &&
60009          "Invalid call instruction for a KCFI check");
60010 
60011   MachineFunction &MF = *MBB.getParent();
60012   // If the call target is a memory operand, unfold it and use R11 for the
60013   // call, so KCFI_CHECK won't have to recompute the address.
60014   switch (MBBI->getOpcode()) {
60015   case X86::CALL64m:
60016   case X86::CALL64m_NT:
60017   case X86::TAILJMPm64:
60018   case X86::TAILJMPm64_REX: {
60019     MachineBasicBlock::instr_iterator OrigCall = MBBI;
60020     SmallVector<MachineInstr *, 2> NewMIs;
60021     if (!TII->unfoldMemoryOperand(MF, *OrigCall, X86::R11, /*UnfoldLoad=*/true,
60022                                   /*UnfoldStore=*/false, NewMIs))
60023       report_fatal_error("Failed to unfold memory operand for a KCFI check");
60024     for (auto *NewMI : NewMIs)
60025       MBBI = MBB.insert(OrigCall, NewMI);
60026     assert(MBBI->isCall() &&
60027            "Unexpected instruction after memory operand unfolding");
60028     if (OrigCall->shouldUpdateCallSiteInfo())
60029       MF.moveCallSiteInfo(&*OrigCall, &*MBBI);
60030     MBBI->setCFIType(MF, OrigCall->getCFIType());
60031     OrigCall->eraseFromParent();
60032     break;
60033   }
60034   default:
60035     break;
60036   }
60037 
60038   MachineOperand &Target = MBBI->getOperand(0);
60039   Register TargetReg;
60040   switch (MBBI->getOpcode()) {
60041   case X86::CALL64r:
60042   case X86::CALL64r_NT:
60043   case X86::TAILJMPr64:
60044   case X86::TAILJMPr64_REX:
60045     assert(Target.isReg() && "Unexpected target operand for an indirect call");
60046     Target.setIsRenamable(false);
60047     TargetReg = Target.getReg();
60048     break;
60049   case X86::CALL64pcrel32:
60050   case X86::TAILJMPd64:
60051     assert(Target.isSymbol() && "Unexpected target operand for a direct call");
60052     // X86TargetLowering::EmitLoweredIndirectThunk always uses r11 for
60053     // 64-bit indirect thunk calls.
60054     assert(StringRef(Target.getSymbolName()).endswith("_r11") &&
60055            "Unexpected register for an indirect thunk call");
60056     TargetReg = X86::R11;
60057     break;
60058   default:
60059     llvm_unreachable("Unexpected CFI call opcode");
60060     break;
60061   }
60062 
60063   return BuildMI(MBB, MBBI, MIMetadata(*MBBI), TII->get(X86::KCFI_CHECK))
60064       .addReg(TargetReg)
60065       .addImm(MBBI->getCFIType())
60066       .getInstr();
60067 }
60068 
60069 /// Returns true if stack probing through a function call is requested.
60070 bool X86TargetLowering::hasStackProbeSymbol(const MachineFunction &MF) const {
60071   return !getStackProbeSymbolName(MF).empty();
60072 }
60073 
60074 /// Returns true if stack probing through inline assembly is requested.
60075 bool X86TargetLowering::hasInlineStackProbe(const MachineFunction &MF) const {
60076 
60077   // No inline stack probe for Windows, they have their own mechanism.
60078   if (Subtarget.isOSWindows() ||
60079       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
60080     return false;
60081 
60082   // If the function specifically requests inline stack probes, emit them.
60083   if (MF.getFunction().hasFnAttribute("probe-stack"))
60084     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
60085            "inline-asm";
60086 
60087   return false;
60088 }
60089 
60090 /// Returns the name of the symbol used to emit stack probes or the empty
60091 /// string if not applicable.
60092 StringRef
60093 X86TargetLowering::getStackProbeSymbolName(const MachineFunction &MF) const {
60094   // Inline Stack probes disable stack probe call
60095   if (hasInlineStackProbe(MF))
60096     return "";
60097 
60098   // If the function specifically requests stack probes, emit them.
60099   if (MF.getFunction().hasFnAttribute("probe-stack"))
60100     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
60101 
60102   // Generally, if we aren't on Windows, the platform ABI does not include
60103   // support for stack probes, so don't emit them.
60104   if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
60105       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
60106     return "";
60107 
60108   // We need a stack probe to conform to the Windows ABI. Choose the right
60109   // symbol.
60110   if (Subtarget.is64Bit())
60111     return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
60112   return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
60113 }
60114 
60115 unsigned
60116 X86TargetLowering::getStackProbeSize(const MachineFunction &MF) const {
60117   // The default stack probe size is 4096 if the function has no stackprobesize
60118   // attribute.
60119   return MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size",
60120                                                         4096);
60121 }
60122 
60123 Align X86TargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
60124   if (ML->isInnermost() &&
60125       ExperimentalPrefInnermostLoopAlignment.getNumOccurrences())
60126     return Align(1ULL << ExperimentalPrefInnermostLoopAlignment);
60127   return TargetLowering::getPrefLoopAlignment();
60128 }
60129