xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/X86/X86ISelLowering.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that X86 uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86ISelLowering.h"
15 #include "MCTargetDesc/X86ShuffleDecode.h"
16 #include "X86.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86IntrinsicsInfo.h"
21 #include "X86MachineFunctionInfo.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/BlockFrequencyInfo.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/ObjCARCUtil.h"
32 #include "llvm/Analysis/ProfileSummaryInfo.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/CodeGen/IntrinsicLowering.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineJumpTableInfo.h"
39 #include "llvm/CodeGen/MachineLoopInfo.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/WinEHFuncInfo.h"
44 #include "llvm/IR/CallingConv.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/DiagnosticInfo.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalAlias.h"
50 #include "llvm/IR/GlobalVariable.h"
51 #include "llvm/IR/IRBuilder.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/PatternMatch.h"
55 #include "llvm/MC/MCAsmInfo.h"
56 #include "llvm/MC/MCContext.h"
57 #include "llvm/MC/MCExpr.h"
58 #include "llvm/MC/MCSymbol.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Target/TargetOptions.h"
65 #include <algorithm>
66 #include <bitset>
67 #include <cctype>
68 #include <numeric>
69 using namespace llvm;
70 
71 #define DEBUG_TYPE "x86-isel"
72 
73 STATISTIC(NumTailCalls, "Number of tail calls");
74 
75 static cl::opt<int> ExperimentalPrefInnermostLoopAlignment(
76     "x86-experimental-pref-innermost-loop-alignment", cl::init(4),
77     cl::desc(
78         "Sets the preferable loop alignment for experiments (as log2 bytes) "
79         "for innermost loops only. If specified, this option overrides "
80         "alignment set by x86-experimental-pref-loop-alignment."),
81     cl::Hidden);
82 
83 static cl::opt<bool> MulConstantOptimization(
84     "mul-constant-optimization", cl::init(true),
85     cl::desc("Replace 'mul x, Const' with more effective instructions like "
86              "SHIFT, LEA, etc."),
87     cl::Hidden);
88 
89 static cl::opt<bool> ExperimentalUnorderedISEL(
90     "x86-experimental-unordered-atomic-isel", cl::init(false),
91     cl::desc("Use LoadSDNode and StoreSDNode instead of "
92              "AtomicSDNode for unordered atomic loads and "
93              "stores respectively."),
94     cl::Hidden);
95 
96 /// Call this when the user attempts to do something unsupported, like
97 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
98 /// report_fatal_error, so calling code should attempt to recover without
99 /// crashing.
100 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
101                              const char *Msg) {
102   MachineFunction &MF = DAG.getMachineFunction();
103   DAG.getContext()->diagnose(
104       DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
105 }
106 
107 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
108                                      const X86Subtarget &STI)
109     : TargetLowering(TM), Subtarget(STI) {
110   bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
111   X86ScalarSSEf64 = Subtarget.hasSSE2();
112   X86ScalarSSEf32 = Subtarget.hasSSE1();
113   X86ScalarSSEf16 = Subtarget.hasFP16();
114   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
115 
116   // Set up the TargetLowering object.
117 
118   // X86 is weird. It always uses i8 for shift amounts and setcc results.
119   setBooleanContents(ZeroOrOneBooleanContent);
120   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
121   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
122 
123   // For 64-bit, since we have so many registers, use the ILP scheduler.
124   // For 32-bit, use the register pressure specific scheduling.
125   // For Atom, always use ILP scheduling.
126   if (Subtarget.isAtom())
127     setSchedulingPreference(Sched::ILP);
128   else if (Subtarget.is64Bit())
129     setSchedulingPreference(Sched::ILP);
130   else
131     setSchedulingPreference(Sched::RegPressure);
132   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
133   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
134 
135   // Bypass expensive divides and use cheaper ones.
136   if (TM.getOptLevel() >= CodeGenOpt::Default) {
137     if (Subtarget.hasSlowDivide32())
138       addBypassSlowDiv(32, 8);
139     if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
140       addBypassSlowDiv(64, 32);
141   }
142 
143   // Setup Windows compiler runtime calls.
144   if (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()) {
145     static const struct {
146       const RTLIB::Libcall Op;
147       const char * const Name;
148       const CallingConv::ID CC;
149     } LibraryCalls[] = {
150       { RTLIB::SDIV_I64, "_alldiv", CallingConv::X86_StdCall },
151       { RTLIB::UDIV_I64, "_aulldiv", CallingConv::X86_StdCall },
152       { RTLIB::SREM_I64, "_allrem", CallingConv::X86_StdCall },
153       { RTLIB::UREM_I64, "_aullrem", CallingConv::X86_StdCall },
154       { RTLIB::MUL_I64, "_allmul", CallingConv::X86_StdCall },
155     };
156 
157     for (const auto &LC : LibraryCalls) {
158       setLibcallName(LC.Op, LC.Name);
159       setLibcallCallingConv(LC.Op, LC.CC);
160     }
161   }
162 
163   if (Subtarget.getTargetTriple().isOSMSVCRT()) {
164     // MSVCRT doesn't have powi; fall back to pow
165     setLibcallName(RTLIB::POWI_F32, nullptr);
166     setLibcallName(RTLIB::POWI_F64, nullptr);
167   }
168 
169   // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
170   // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
171   // FIXME: Should we be limiting the atomic size on other configs? Default is
172   // 1024.
173   if (!Subtarget.hasCmpxchg8b())
174     setMaxAtomicSizeInBitsSupported(32);
175 
176   // Set up the register classes.
177   addRegisterClass(MVT::i8, &X86::GR8RegClass);
178   addRegisterClass(MVT::i16, &X86::GR16RegClass);
179   addRegisterClass(MVT::i32, &X86::GR32RegClass);
180   if (Subtarget.is64Bit())
181     addRegisterClass(MVT::i64, &X86::GR64RegClass);
182 
183   for (MVT VT : MVT::integer_valuetypes())
184     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
185 
186   // We don't accept any truncstore of integer registers.
187   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
188   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
189   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
190   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
191   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
192   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
193 
194   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
195 
196   // SETOEQ and SETUNE require checking two conditions.
197   for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
198     setCondCodeAction(ISD::SETOEQ, VT, Expand);
199     setCondCodeAction(ISD::SETUNE, VT, Expand);
200   }
201 
202   // Integer absolute.
203   if (Subtarget.hasCMov()) {
204     setOperationAction(ISD::ABS            , MVT::i16  , Custom);
205     setOperationAction(ISD::ABS            , MVT::i32  , Custom);
206     if (Subtarget.is64Bit())
207       setOperationAction(ISD::ABS          , MVT::i64  , Custom);
208   }
209 
210   // Signed saturation subtraction.
211   setOperationAction(ISD::SSUBSAT          , MVT::i8   , Custom);
212   setOperationAction(ISD::SSUBSAT          , MVT::i16  , Custom);
213   setOperationAction(ISD::SSUBSAT          , MVT::i32  , Custom);
214   if (Subtarget.is64Bit())
215     setOperationAction(ISD::SSUBSAT        , MVT::i64  , Custom);
216 
217   // Funnel shifts.
218   for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
219     // For slow shld targets we only lower for code size.
220     LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
221 
222     setOperationAction(ShiftOp             , MVT::i8   , Custom);
223     setOperationAction(ShiftOp             , MVT::i16  , Custom);
224     setOperationAction(ShiftOp             , MVT::i32  , ShiftDoubleAction);
225     if (Subtarget.is64Bit())
226       setOperationAction(ShiftOp           , MVT::i64  , ShiftDoubleAction);
227   }
228 
229   if (!Subtarget.useSoftFloat()) {
230     // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
231     // operation.
232     setOperationAction(ISD::UINT_TO_FP,        MVT::i8, Promote);
233     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
234     setOperationAction(ISD::UINT_TO_FP,        MVT::i16, Promote);
235     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
236     // We have an algorithm for SSE2, and we turn this into a 64-bit
237     // FILD or VCVTUSI2SS/SD for other targets.
238     setOperationAction(ISD::UINT_TO_FP,        MVT::i32, Custom);
239     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
240     // We have an algorithm for SSE2->double, and we turn this into a
241     // 64-bit FILD followed by conditional FADD for other targets.
242     setOperationAction(ISD::UINT_TO_FP,        MVT::i64, Custom);
243     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
244 
245     // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
246     // this operation.
247     setOperationAction(ISD::SINT_TO_FP,        MVT::i8, Promote);
248     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
249     // SSE has no i16 to fp conversion, only i32. We promote in the handler
250     // to allow f80 to use i16 and f64 to use i16 with sse1 only
251     setOperationAction(ISD::SINT_TO_FP,        MVT::i16, Custom);
252     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
253     // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
254     setOperationAction(ISD::SINT_TO_FP,        MVT::i32, Custom);
255     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
256     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
257     // are Legal, f80 is custom lowered.
258     setOperationAction(ISD::SINT_TO_FP,        MVT::i64, Custom);
259     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
260 
261     // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
262     // this operation.
263     setOperationAction(ISD::FP_TO_SINT,        MVT::i8,  Promote);
264     // FIXME: This doesn't generate invalid exception when it should. PR44019.
265     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8,  Promote);
266     setOperationAction(ISD::FP_TO_SINT,        MVT::i16, Custom);
267     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
268     setOperationAction(ISD::FP_TO_SINT,        MVT::i32, Custom);
269     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
270     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
271     // are Legal, f80 is custom lowered.
272     setOperationAction(ISD::FP_TO_SINT,        MVT::i64, Custom);
273     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
274 
275     // Handle FP_TO_UINT by promoting the destination to a larger signed
276     // conversion.
277     setOperationAction(ISD::FP_TO_UINT,        MVT::i8,  Promote);
278     // FIXME: This doesn't generate invalid exception when it should. PR44019.
279     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8,  Promote);
280     setOperationAction(ISD::FP_TO_UINT,        MVT::i16, Promote);
281     // FIXME: This doesn't generate invalid exception when it should. PR44019.
282     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
283     setOperationAction(ISD::FP_TO_UINT,        MVT::i32, Custom);
284     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
285     setOperationAction(ISD::FP_TO_UINT,        MVT::i64, Custom);
286     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
287 
288     setOperationAction(ISD::LRINT,             MVT::f32, Custom);
289     setOperationAction(ISD::LRINT,             MVT::f64, Custom);
290     setOperationAction(ISD::LLRINT,            MVT::f32, Custom);
291     setOperationAction(ISD::LLRINT,            MVT::f64, Custom);
292 
293     if (!Subtarget.is64Bit()) {
294       setOperationAction(ISD::LRINT,  MVT::i64, Custom);
295       setOperationAction(ISD::LLRINT, MVT::i64, Custom);
296     }
297   }
298 
299   if (Subtarget.hasSSE2()) {
300     // Custom lowering for saturating float to int conversions.
301     // We handle promotion to larger result types manually.
302     for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
303       setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
304       setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
305     }
306     if (Subtarget.is64Bit()) {
307       setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
308       setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
309     }
310   }
311 
312   // Handle address space casts between mixed sized pointers.
313   setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
314   setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
315 
316   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
317   if (!X86ScalarSSEf64) {
318     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
319     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
320     if (Subtarget.is64Bit()) {
321       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
322       // Without SSE, i64->f64 goes through memory.
323       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
324     }
325   } else if (!Subtarget.is64Bit())
326     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
327 
328   // Scalar integer divide and remainder are lowered to use operations that
329   // produce two results, to match the available instructions. This exposes
330   // the two-result form to trivial CSE, which is able to combine x/y and x%y
331   // into a single instruction.
332   //
333   // Scalar integer multiply-high is also lowered to use two-result
334   // operations, to match the available instructions. However, plain multiply
335   // (low) operations are left as Legal, as there are single-result
336   // instructions for this in x86. Using the two-result multiply instructions
337   // when both high and low results are needed must be arranged by dagcombine.
338   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
339     setOperationAction(ISD::MULHS, VT, Expand);
340     setOperationAction(ISD::MULHU, VT, Expand);
341     setOperationAction(ISD::SDIV, VT, Expand);
342     setOperationAction(ISD::UDIV, VT, Expand);
343     setOperationAction(ISD::SREM, VT, Expand);
344     setOperationAction(ISD::UREM, VT, Expand);
345   }
346 
347   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
348   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
349   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
350                    MVT::i8,  MVT::i16, MVT::i32, MVT::i64 }) {
351     setOperationAction(ISD::BR_CC,     VT, Expand);
352     setOperationAction(ISD::SELECT_CC, VT, Expand);
353   }
354   if (Subtarget.is64Bit())
355     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
356   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
357   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
358   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
359 
360   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
361   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
362   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
363   setOperationAction(ISD::FREM             , MVT::f128 , Expand);
364 
365   if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
366     setOperationAction(ISD::FLT_ROUNDS_    , MVT::i32  , Custom);
367     setOperationAction(ISD::SET_ROUNDING   , MVT::Other, Custom);
368   }
369 
370   // Promote the i8 variants and force them on up to i32 which has a shorter
371   // encoding.
372   setOperationPromotedToType(ISD::CTTZ           , MVT::i8   , MVT::i32);
373   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
374 
375   if (Subtarget.hasBMI()) {
376     // Promote the i16 zero undef variant and force it on up to i32 when tzcnt
377     // is enabled.
378     setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i16, MVT::i32);
379   } else {
380     setOperationAction(ISD::CTTZ, MVT::i16, Custom);
381     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
382     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Legal);
383     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Legal);
384     if (Subtarget.is64Bit()) {
385       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
386       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
387     }
388   }
389 
390   if (Subtarget.hasLZCNT()) {
391     // When promoting the i8 variants, force them to i32 for a shorter
392     // encoding.
393     setOperationPromotedToType(ISD::CTLZ           , MVT::i8   , MVT::i32);
394     setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
395   } else {
396     for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
397       if (VT == MVT::i64 && !Subtarget.is64Bit())
398         continue;
399       setOperationAction(ISD::CTLZ           , VT, Custom);
400       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
401     }
402   }
403 
404   for (auto Op : {ISD::FP16_TO_FP, ISD::STRICT_FP16_TO_FP, ISD::FP_TO_FP16,
405                   ISD::STRICT_FP_TO_FP16}) {
406     // Special handling for half-precision floating point conversions.
407     // If we don't have F16C support, then lower half float conversions
408     // into library calls.
409     setOperationAction(
410         Op, MVT::f32,
411         (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
412     // There's never any support for operations beyond MVT::f32.
413     setOperationAction(Op, MVT::f64, Expand);
414     setOperationAction(Op, MVT::f80, Expand);
415     setOperationAction(Op, MVT::f128, Expand);
416   }
417 
418   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
419   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
420   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
421   setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Expand);
422   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
423   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
424   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
425   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
426 
427   setOperationAction(ISD::PARITY, MVT::i8, Custom);
428   setOperationAction(ISD::PARITY, MVT::i16, Custom);
429   setOperationAction(ISD::PARITY, MVT::i32, Custom);
430   if (Subtarget.is64Bit())
431     setOperationAction(ISD::PARITY, MVT::i64, Custom);
432   if (Subtarget.hasPOPCNT()) {
433     setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
434     // popcntw is longer to encode than popcntl and also has a false dependency
435     // on the dest that popcntl hasn't had since Cannon Lake.
436     setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
437   } else {
438     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
439     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
440     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
441     if (Subtarget.is64Bit())
442       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
443     else
444       setOperationAction(ISD::CTPOP        , MVT::i64  , Custom);
445   }
446 
447   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
448 
449   if (!Subtarget.hasMOVBE())
450     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
451 
452   // X86 wants to expand cmov itself.
453   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
454     setOperationAction(ISD::SELECT, VT, Custom);
455     setOperationAction(ISD::SETCC, VT, Custom);
456     setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
457     setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
458   }
459   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
460     if (VT == MVT::i64 && !Subtarget.is64Bit())
461       continue;
462     setOperationAction(ISD::SELECT, VT, Custom);
463     setOperationAction(ISD::SETCC,  VT, Custom);
464   }
465 
466   // Custom action for SELECT MMX and expand action for SELECT_CC MMX
467   setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
468   setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
469 
470   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
471   // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
472   // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
473   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
474   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
475   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
476   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
477     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
478 
479   // Darwin ABI issue.
480   for (auto VT : { MVT::i32, MVT::i64 }) {
481     if (VT == MVT::i64 && !Subtarget.is64Bit())
482       continue;
483     setOperationAction(ISD::ConstantPool    , VT, Custom);
484     setOperationAction(ISD::JumpTable       , VT, Custom);
485     setOperationAction(ISD::GlobalAddress   , VT, Custom);
486     setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
487     setOperationAction(ISD::ExternalSymbol  , VT, Custom);
488     setOperationAction(ISD::BlockAddress    , VT, Custom);
489   }
490 
491   // 64-bit shl, sra, srl (iff 32-bit x86)
492   for (auto VT : { MVT::i32, MVT::i64 }) {
493     if (VT == MVT::i64 && !Subtarget.is64Bit())
494       continue;
495     setOperationAction(ISD::SHL_PARTS, VT, Custom);
496     setOperationAction(ISD::SRA_PARTS, VT, Custom);
497     setOperationAction(ISD::SRL_PARTS, VT, Custom);
498   }
499 
500   if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
501     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
502 
503   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
504 
505   // Expand certain atomics
506   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
507     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
513     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
514   }
515 
516   if (!Subtarget.is64Bit())
517     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518 
519   if (Subtarget.hasCmpxchg16b()) {
520     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
521   }
522 
523   // FIXME - use subtarget debug flags
524   if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
525       !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
526       TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
527     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
528   }
529 
530   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
531   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
532 
533   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
534   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
535 
536   setOperationAction(ISD::TRAP, MVT::Other, Legal);
537   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
538   if (Subtarget.getTargetTriple().isPS4CPU())
539     setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand);
540   else
541     setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
542 
543   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
544   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
545   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
546   bool Is64Bit = Subtarget.is64Bit();
547   setOperationAction(ISD::VAARG,  MVT::Other, Is64Bit ? Custom : Expand);
548   setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
549 
550   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
551   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
552 
553   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
554 
555   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
556   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
557   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
558 
559   if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
563                                                      : &X86::FR32RegClass);
564     addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
565                                                      : &X86::FR64RegClass);
566 
567     // Disable f32->f64 extload as we can only generate this in one instruction
568     // under optsize. So its easier to pattern match (fpext (load)) for that
569     // case instead of needing to emit 2 instructions for extload in the
570     // non-optsize case.
571     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
572 
573     for (auto VT : { MVT::f32, MVT::f64 }) {
574       // Use ANDPD to simulate FABS.
575       setOperationAction(ISD::FABS, VT, Custom);
576 
577       // Use XORP to simulate FNEG.
578       setOperationAction(ISD::FNEG, VT, Custom);
579 
580       // Use ANDPD and ORPD to simulate FCOPYSIGN.
581       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
582 
583       // These might be better off as horizontal vector ops.
584       setOperationAction(ISD::FADD, VT, Custom);
585       setOperationAction(ISD::FSUB, VT, Custom);
586 
587       // We don't support sin/cos/fmod
588       setOperationAction(ISD::FSIN   , VT, Expand);
589       setOperationAction(ISD::FCOS   , VT, Expand);
590       setOperationAction(ISD::FSINCOS, VT, Expand);
591     }
592 
593     // Lower this to MOVMSK plus an AND.
594     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
595     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
596 
597   } else if (!Subtarget.useSoftFloat() && X86ScalarSSEf32 &&
598              (UseX87 || Is64Bit)) {
599     // Use SSE for f32, x87 for f64.
600     // Set up the FP register classes.
601     addRegisterClass(MVT::f32, &X86::FR32RegClass);
602     if (UseX87)
603       addRegisterClass(MVT::f64, &X86::RFP64RegClass);
604 
605     // Use ANDPS to simulate FABS.
606     setOperationAction(ISD::FABS , MVT::f32, Custom);
607 
608     // Use XORP to simulate FNEG.
609     setOperationAction(ISD::FNEG , MVT::f32, Custom);
610 
611     if (UseX87)
612       setOperationAction(ISD::UNDEF, MVT::f64, Expand);
613 
614     // Use ANDPS and ORPS to simulate FCOPYSIGN.
615     if (UseX87)
616       setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
617     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
618 
619     // We don't support sin/cos/fmod
620     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
621     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
622     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
623 
624     if (UseX87) {
625       // Always expand sin/cos functions even though x87 has an instruction.
626       setOperationAction(ISD::FSIN, MVT::f64, Expand);
627       setOperationAction(ISD::FCOS, MVT::f64, Expand);
628       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
629     }
630   } else if (UseX87) {
631     // f32 and f64 in x87.
632     // Set up the FP register classes.
633     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
634     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
635 
636     for (auto VT : { MVT::f32, MVT::f64 }) {
637       setOperationAction(ISD::UNDEF,     VT, Expand);
638       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
639 
640       // Always expand sin/cos functions even though x87 has an instruction.
641       setOperationAction(ISD::FSIN   , VT, Expand);
642       setOperationAction(ISD::FCOS   , VT, Expand);
643       setOperationAction(ISD::FSINCOS, VT, Expand);
644     }
645   }
646 
647   // Expand FP32 immediates into loads from the stack, save special cases.
648   if (isTypeLegal(MVT::f32)) {
649     if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
650       addLegalFPImmediate(APFloat(+0.0f)); // FLD0
651       addLegalFPImmediate(APFloat(+1.0f)); // FLD1
652       addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
653       addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
654     } else // SSE immediates.
655       addLegalFPImmediate(APFloat(+0.0f)); // xorps
656   }
657   // Expand FP64 immediates into loads from the stack, save special cases.
658   if (isTypeLegal(MVT::f64)) {
659     if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
660       addLegalFPImmediate(APFloat(+0.0)); // FLD0
661       addLegalFPImmediate(APFloat(+1.0)); // FLD1
662       addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
663       addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
664     } else // SSE immediates.
665       addLegalFPImmediate(APFloat(+0.0)); // xorpd
666   }
667   // Handle constrained floating-point operations of scalar.
668   setOperationAction(ISD::STRICT_FADD,      MVT::f32, Legal);
669   setOperationAction(ISD::STRICT_FADD,      MVT::f64, Legal);
670   setOperationAction(ISD::STRICT_FSUB,      MVT::f32, Legal);
671   setOperationAction(ISD::STRICT_FSUB,      MVT::f64, Legal);
672   setOperationAction(ISD::STRICT_FMUL,      MVT::f32, Legal);
673   setOperationAction(ISD::STRICT_FMUL,      MVT::f64, Legal);
674   setOperationAction(ISD::STRICT_FDIV,      MVT::f32, Legal);
675   setOperationAction(ISD::STRICT_FDIV,      MVT::f64, Legal);
676   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
677   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f32, Legal);
678   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f64, Legal);
679   setOperationAction(ISD::STRICT_FSQRT,     MVT::f32, Legal);
680   setOperationAction(ISD::STRICT_FSQRT,     MVT::f64, Legal);
681 
682   // We don't support FMA.
683   setOperationAction(ISD::FMA, MVT::f64, Expand);
684   setOperationAction(ISD::FMA, MVT::f32, Expand);
685 
686   // f80 always uses X87.
687   if (UseX87) {
688     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
689     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
690     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
691     {
692       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
693       addLegalFPImmediate(TmpFlt);  // FLD0
694       TmpFlt.changeSign();
695       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
696 
697       bool ignored;
698       APFloat TmpFlt2(+1.0);
699       TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
700                       &ignored);
701       addLegalFPImmediate(TmpFlt2);  // FLD1
702       TmpFlt2.changeSign();
703       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
704     }
705 
706     // Always expand sin/cos functions even though x87 has an instruction.
707     setOperationAction(ISD::FSIN   , MVT::f80, Expand);
708     setOperationAction(ISD::FCOS   , MVT::f80, Expand);
709     setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
710 
711     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
712     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
713     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
714     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
715     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
716     setOperationAction(ISD::FMA, MVT::f80, Expand);
717     setOperationAction(ISD::LROUND, MVT::f80, Expand);
718     setOperationAction(ISD::LLROUND, MVT::f80, Expand);
719     setOperationAction(ISD::LRINT, MVT::f80, Custom);
720     setOperationAction(ISD::LLRINT, MVT::f80, Custom);
721 
722     // Handle constrained floating-point operations of scalar.
723     setOperationAction(ISD::STRICT_FADD     , MVT::f80, Legal);
724     setOperationAction(ISD::STRICT_FSUB     , MVT::f80, Legal);
725     setOperationAction(ISD::STRICT_FMUL     , MVT::f80, Legal);
726     setOperationAction(ISD::STRICT_FDIV     , MVT::f80, Legal);
727     setOperationAction(ISD::STRICT_FSQRT    , MVT::f80, Legal);
728     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
729     // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
730     // as Custom.
731     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
732   }
733 
734   // f128 uses xmm registers, but most operations require libcalls.
735   if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
736     addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
737                                                    : &X86::VR128RegClass);
738 
739     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
740 
741     setOperationAction(ISD::FADD,        MVT::f128, LibCall);
742     setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
743     setOperationAction(ISD::FSUB,        MVT::f128, LibCall);
744     setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
745     setOperationAction(ISD::FDIV,        MVT::f128, LibCall);
746     setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
747     setOperationAction(ISD::FMUL,        MVT::f128, LibCall);
748     setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
749     setOperationAction(ISD::FMA,         MVT::f128, LibCall);
750     setOperationAction(ISD::STRICT_FMA,  MVT::f128, LibCall);
751 
752     setOperationAction(ISD::FABS, MVT::f128, Custom);
753     setOperationAction(ISD::FNEG, MVT::f128, Custom);
754     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
755 
756     setOperationAction(ISD::FSIN,         MVT::f128, LibCall);
757     setOperationAction(ISD::STRICT_FSIN,  MVT::f128, LibCall);
758     setOperationAction(ISD::FCOS,         MVT::f128, LibCall);
759     setOperationAction(ISD::STRICT_FCOS,  MVT::f128, LibCall);
760     setOperationAction(ISD::FSINCOS,      MVT::f128, LibCall);
761     // No STRICT_FSINCOS
762     setOperationAction(ISD::FSQRT,        MVT::f128, LibCall);
763     setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
764 
765     setOperationAction(ISD::FP_EXTEND,        MVT::f128, Custom);
766     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
767     // We need to custom handle any FP_ROUND with an f128 input, but
768     // LegalizeDAG uses the result type to know when to run a custom handler.
769     // So we have to list all legal floating point result types here.
770     if (isTypeLegal(MVT::f32)) {
771       setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
772       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
773     }
774     if (isTypeLegal(MVT::f64)) {
775       setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
776       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
777     }
778     if (isTypeLegal(MVT::f80)) {
779       setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
780       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
781     }
782 
783     setOperationAction(ISD::SETCC, MVT::f128, Custom);
784 
785     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
786     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
787     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
788     setTruncStoreAction(MVT::f128, MVT::f32, Expand);
789     setTruncStoreAction(MVT::f128, MVT::f64, Expand);
790     setTruncStoreAction(MVT::f128, MVT::f80, Expand);
791   }
792 
793   // Always use a library call for pow.
794   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
795   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
796   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
797   setOperationAction(ISD::FPOW             , MVT::f128 , Expand);
798 
799   setOperationAction(ISD::FLOG, MVT::f80, Expand);
800   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
801   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
802   setOperationAction(ISD::FEXP, MVT::f80, Expand);
803   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
804   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
805   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
806 
807   // Some FP actions are always expanded for vector types.
808   for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
809                    MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
810     setOperationAction(ISD::FSIN,      VT, Expand);
811     setOperationAction(ISD::FSINCOS,   VT, Expand);
812     setOperationAction(ISD::FCOS,      VT, Expand);
813     setOperationAction(ISD::FREM,      VT, Expand);
814     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
815     setOperationAction(ISD::FPOW,      VT, Expand);
816     setOperationAction(ISD::FLOG,      VT, Expand);
817     setOperationAction(ISD::FLOG2,     VT, Expand);
818     setOperationAction(ISD::FLOG10,    VT, Expand);
819     setOperationAction(ISD::FEXP,      VT, Expand);
820     setOperationAction(ISD::FEXP2,     VT, Expand);
821   }
822 
823   // First set operation action for all vector types to either promote
824   // (for widening) or expand (for scalarization). Then we will selectively
825   // turn on ones that can be effectively codegen'd.
826   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
827     setOperationAction(ISD::SDIV, VT, Expand);
828     setOperationAction(ISD::UDIV, VT, Expand);
829     setOperationAction(ISD::SREM, VT, Expand);
830     setOperationAction(ISD::UREM, VT, Expand);
831     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
832     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
833     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
834     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::FMA,  VT, Expand);
836     setOperationAction(ISD::FFLOOR, VT, Expand);
837     setOperationAction(ISD::FCEIL, VT, Expand);
838     setOperationAction(ISD::FTRUNC, VT, Expand);
839     setOperationAction(ISD::FRINT, VT, Expand);
840     setOperationAction(ISD::FNEARBYINT, VT, Expand);
841     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
842     setOperationAction(ISD::MULHS, VT, Expand);
843     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
844     setOperationAction(ISD::MULHU, VT, Expand);
845     setOperationAction(ISD::SDIVREM, VT, Expand);
846     setOperationAction(ISD::UDIVREM, VT, Expand);
847     setOperationAction(ISD::CTPOP, VT, Expand);
848     setOperationAction(ISD::CTTZ, VT, Expand);
849     setOperationAction(ISD::CTLZ, VT, Expand);
850     setOperationAction(ISD::ROTL, VT, Expand);
851     setOperationAction(ISD::ROTR, VT, Expand);
852     setOperationAction(ISD::BSWAP, VT, Expand);
853     setOperationAction(ISD::SETCC, VT, Expand);
854     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859     setOperationAction(ISD::TRUNCATE, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863     setOperationAction(ISD::SELECT_CC, VT, Expand);
864     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
865       setTruncStoreAction(InnerVT, VT, Expand);
866 
867       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
868       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
869 
870       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
871       // types, we have to deal with them whether we ask for Expansion or not.
872       // Setting Expand causes its own optimisation problems though, so leave
873       // them legal.
874       if (VT.getVectorElementType() == MVT::i1)
875         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
876 
877       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
878       // split/scalarized right now.
879       if (VT.getVectorElementType() == MVT::f16)
880         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
881     }
882   }
883 
884   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
885   // with -msoft-float, disable use of MMX as well.
886   if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
887     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
888     // No operations on x86mmx supported, everything uses intrinsics.
889   }
890 
891   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
892     addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
893                                                     : &X86::VR128RegClass);
894 
895     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
896     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
897     setOperationAction(ISD::FCOPYSIGN,          MVT::v4f32, Custom);
898     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
899     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
900     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
901     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
902     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
903 
904     setOperationAction(ISD::LOAD,               MVT::v2f32, Custom);
905     setOperationAction(ISD::STORE,              MVT::v2f32, Custom);
906 
907     setOperationAction(ISD::STRICT_FADD,        MVT::v4f32, Legal);
908     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f32, Legal);
909     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f32, Legal);
910     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f32, Legal);
911     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f32, Legal);
912   }
913 
914   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
915     addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
916                                                     : &X86::VR128RegClass);
917 
918     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
919     // registers cannot be used even for integer operations.
920     addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
921                                                     : &X86::VR128RegClass);
922     addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
923                                                     : &X86::VR128RegClass);
924     addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
925                                                     : &X86::VR128RegClass);
926     addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
927                                                     : &X86::VR128RegClass);
928 
929     for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
930                      MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
931       setOperationAction(ISD::SDIV, VT, Custom);
932       setOperationAction(ISD::SREM, VT, Custom);
933       setOperationAction(ISD::UDIV, VT, Custom);
934       setOperationAction(ISD::UREM, VT, Custom);
935     }
936 
937     setOperationAction(ISD::MUL,                MVT::v2i8,  Custom);
938     setOperationAction(ISD::MUL,                MVT::v4i8,  Custom);
939     setOperationAction(ISD::MUL,                MVT::v8i8,  Custom);
940 
941     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
942     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
943     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
944     setOperationAction(ISD::MULHU,              MVT::v4i32, Custom);
945     setOperationAction(ISD::MULHS,              MVT::v4i32, Custom);
946     setOperationAction(ISD::MULHU,              MVT::v16i8, Custom);
947     setOperationAction(ISD::MULHS,              MVT::v16i8, Custom);
948     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
949     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
950     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
951 
952     setOperationAction(ISD::SMULO,              MVT::v16i8, Custom);
953     setOperationAction(ISD::UMULO,              MVT::v16i8, Custom);
954 
955     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
956     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
957     setOperationAction(ISD::FCOPYSIGN,          MVT::v2f64, Custom);
958 
959     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
960       setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
961       setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
962       setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
963       setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
964     }
965 
966     setOperationAction(ISD::UADDSAT,            MVT::v16i8, Legal);
967     setOperationAction(ISD::SADDSAT,            MVT::v16i8, Legal);
968     setOperationAction(ISD::USUBSAT,            MVT::v16i8, Legal);
969     setOperationAction(ISD::SSUBSAT,            MVT::v16i8, Legal);
970     setOperationAction(ISD::UADDSAT,            MVT::v8i16, Legal);
971     setOperationAction(ISD::SADDSAT,            MVT::v8i16, Legal);
972     setOperationAction(ISD::USUBSAT,            MVT::v8i16, Legal);
973     setOperationAction(ISD::SSUBSAT,            MVT::v8i16, Legal);
974     setOperationAction(ISD::USUBSAT,            MVT::v4i32, Custom);
975     setOperationAction(ISD::USUBSAT,            MVT::v2i64, Custom);
976 
977     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
978     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
979     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
980     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
981 
982     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
983       setOperationAction(ISD::SETCC,              VT, Custom);
984       setOperationAction(ISD::STRICT_FSETCC,      VT, Custom);
985       setOperationAction(ISD::STRICT_FSETCCS,     VT, Custom);
986       setOperationAction(ISD::CTPOP,              VT, Custom);
987       setOperationAction(ISD::ABS,                VT, Custom);
988 
989       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
990       // setcc all the way to isel and prefer SETGT in some isel patterns.
991       setCondCodeAction(ISD::SETLT, VT, Custom);
992       setCondCodeAction(ISD::SETLE, VT, Custom);
993     }
994 
995     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
996       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
997       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
998       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
999       setOperationAction(ISD::VSELECT,            VT, Custom);
1000       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1001     }
1002 
1003     for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
1004       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1005       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1006       setOperationAction(ISD::VSELECT,            VT, Custom);
1007 
1008       if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1009         continue;
1010 
1011       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1012       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1013     }
1014 
1015     // Custom lower v2i64 and v2f64 selects.
1016     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1017     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1018     setOperationAction(ISD::SELECT,             MVT::v4i32, Custom);
1019     setOperationAction(ISD::SELECT,             MVT::v8i16, Custom);
1020     setOperationAction(ISD::SELECT,             MVT::v16i8, Custom);
1021 
1022     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1023     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Custom);
1024     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
1025     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i32, Custom);
1026     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v4i32, Legal);
1027     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v2i32, Custom);
1028 
1029     // Custom legalize these to avoid over promotion or custom promotion.
1030     for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1031       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
1032       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
1033       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1034       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1035     }
1036 
1037     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1038     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v4i32, Legal);
1039     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
1040     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2i32, Custom);
1041 
1042     setOperationAction(ISD::UINT_TO_FP,         MVT::v2i32, Custom);
1043     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2i32, Custom);
1044 
1045     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
1046     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v4i32, Custom);
1047 
1048     // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1049     setOperationAction(ISD::SINT_TO_FP,         MVT::v2f32, Custom);
1050     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2f32, Custom);
1051     setOperationAction(ISD::UINT_TO_FP,         MVT::v2f32, Custom);
1052     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2f32, Custom);
1053 
1054     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1055     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v2f32, Custom);
1056     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1057     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v2f32, Custom);
1058 
1059     // We want to legalize this to an f64 load rather than an i64 load on
1060     // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1061     // store.
1062     setOperationAction(ISD::LOAD,               MVT::v2i32, Custom);
1063     setOperationAction(ISD::LOAD,               MVT::v4i16, Custom);
1064     setOperationAction(ISD::LOAD,               MVT::v8i8,  Custom);
1065     setOperationAction(ISD::STORE,              MVT::v2i32, Custom);
1066     setOperationAction(ISD::STORE,              MVT::v4i16, Custom);
1067     setOperationAction(ISD::STORE,              MVT::v8i8,  Custom);
1068 
1069     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1070     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1071     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1072     if (!Subtarget.hasAVX512())
1073       setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1074 
1075     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1076     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1077     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1078 
1079     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1080 
1081     setOperationAction(ISD::TRUNCATE,    MVT::v2i8,  Custom);
1082     setOperationAction(ISD::TRUNCATE,    MVT::v2i16, Custom);
1083     setOperationAction(ISD::TRUNCATE,    MVT::v2i32, Custom);
1084     setOperationAction(ISD::TRUNCATE,    MVT::v4i8,  Custom);
1085     setOperationAction(ISD::TRUNCATE,    MVT::v4i16, Custom);
1086     setOperationAction(ISD::TRUNCATE,    MVT::v8i8,  Custom);
1087 
1088     // In the customized shift lowering, the legal v4i32/v2i64 cases
1089     // in AVX2 will be recognized.
1090     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1091       setOperationAction(ISD::SRL,              VT, Custom);
1092       setOperationAction(ISD::SHL,              VT, Custom);
1093       setOperationAction(ISD::SRA,              VT, Custom);
1094       if (VT == MVT::v2i64) continue;
1095       setOperationAction(ISD::ROTL,             VT, Custom);
1096       setOperationAction(ISD::ROTR,             VT, Custom);
1097     }
1098 
1099     setOperationAction(ISD::STRICT_FSQRT,       MVT::v2f64, Legal);
1100     setOperationAction(ISD::STRICT_FADD,        MVT::v2f64, Legal);
1101     setOperationAction(ISD::STRICT_FSUB,        MVT::v2f64, Legal);
1102     setOperationAction(ISD::STRICT_FMUL,        MVT::v2f64, Legal);
1103     setOperationAction(ISD::STRICT_FDIV,        MVT::v2f64, Legal);
1104   }
1105 
1106   if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1107     setOperationAction(ISD::ABS,                MVT::v16i8, Legal);
1108     setOperationAction(ISD::ABS,                MVT::v8i16, Legal);
1109     setOperationAction(ISD::ABS,                MVT::v4i32, Legal);
1110     setOperationAction(ISD::BITREVERSE,         MVT::v16i8, Custom);
1111     setOperationAction(ISD::CTLZ,               MVT::v16i8, Custom);
1112     setOperationAction(ISD::CTLZ,               MVT::v8i16, Custom);
1113     setOperationAction(ISD::CTLZ,               MVT::v4i32, Custom);
1114     setOperationAction(ISD::CTLZ,               MVT::v2i64, Custom);
1115 
1116     // These might be better off as horizontal vector ops.
1117     setOperationAction(ISD::ADD,                MVT::i16, Custom);
1118     setOperationAction(ISD::ADD,                MVT::i32, Custom);
1119     setOperationAction(ISD::SUB,                MVT::i16, Custom);
1120     setOperationAction(ISD::SUB,                MVT::i32, Custom);
1121   }
1122 
1123   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1124     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1125       setOperationAction(ISD::FFLOOR,            RoundedTy,  Legal);
1126       setOperationAction(ISD::STRICT_FFLOOR,     RoundedTy,  Legal);
1127       setOperationAction(ISD::FCEIL,             RoundedTy,  Legal);
1128       setOperationAction(ISD::STRICT_FCEIL,      RoundedTy,  Legal);
1129       setOperationAction(ISD::FTRUNC,            RoundedTy,  Legal);
1130       setOperationAction(ISD::STRICT_FTRUNC,     RoundedTy,  Legal);
1131       setOperationAction(ISD::FRINT,             RoundedTy,  Legal);
1132       setOperationAction(ISD::STRICT_FRINT,      RoundedTy,  Legal);
1133       setOperationAction(ISD::FNEARBYINT,        RoundedTy,  Legal);
1134       setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy,  Legal);
1135       setOperationAction(ISD::FROUNDEVEN,        RoundedTy,  Legal);
1136       setOperationAction(ISD::STRICT_FROUNDEVEN, RoundedTy,  Legal);
1137 
1138       setOperationAction(ISD::FROUND,            RoundedTy,  Custom);
1139     }
1140 
1141     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
1142     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
1143     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
1144     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
1145     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
1146     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
1147     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
1148     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
1149 
1150     setOperationAction(ISD::UADDSAT,            MVT::v4i32, Custom);
1151     setOperationAction(ISD::SADDSAT,            MVT::v2i64, Custom);
1152     setOperationAction(ISD::SSUBSAT,            MVT::v2i64, Custom);
1153 
1154     // FIXME: Do we need to handle scalar-to-vector here?
1155     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1156 
1157     // We directly match byte blends in the backend as they match the VSELECT
1158     // condition form.
1159     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1160 
1161     // SSE41 brings specific instructions for doing vector sign extend even in
1162     // cases where we don't have SRA.
1163     for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1164       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1165       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1166     }
1167 
1168     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1169     for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1170       setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8,  Legal);
1171       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8,  Legal);
1172       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8,  Legal);
1173       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1174       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1175       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1176     }
1177 
1178     if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1179       // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1180       // do the pre and post work in the vector domain.
1181       setOperationAction(ISD::UINT_TO_FP,        MVT::v4i64, Custom);
1182       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1183       // We need to mark SINT_TO_FP as Custom even though we want to expand it
1184       // so that DAG combine doesn't try to turn it into uint_to_fp.
1185       setOperationAction(ISD::SINT_TO_FP,        MVT::v4i64, Custom);
1186       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1187     }
1188   }
1189 
1190   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1191     setOperationAction(ISD::UADDSAT,            MVT::v2i64, Custom);
1192   }
1193 
1194   if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1195     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1196                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1197       setOperationAction(ISD::ROTL, VT, Custom);
1198       setOperationAction(ISD::ROTR, VT, Custom);
1199     }
1200 
1201     // XOP can efficiently perform BITREVERSE with VPPERM.
1202     for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1203       setOperationAction(ISD::BITREVERSE, VT, Custom);
1204 
1205     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1206                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1207       setOperationAction(ISD::BITREVERSE, VT, Custom);
1208   }
1209 
1210   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1211     bool HasInt256 = Subtarget.hasInt256();
1212 
1213     addRegisterClass(MVT::v32i8,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1214                                                      : &X86::VR256RegClass);
1215     addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1216                                                      : &X86::VR256RegClass);
1217     addRegisterClass(MVT::v8i32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1218                                                      : &X86::VR256RegClass);
1219     addRegisterClass(MVT::v8f32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1220                                                      : &X86::VR256RegClass);
1221     addRegisterClass(MVT::v4i64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1222                                                      : &X86::VR256RegClass);
1223     addRegisterClass(MVT::v4f64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1224                                                      : &X86::VR256RegClass);
1225 
1226     for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1227       setOperationAction(ISD::FFLOOR,            VT, Legal);
1228       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1229       setOperationAction(ISD::FCEIL,             VT, Legal);
1230       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1231       setOperationAction(ISD::FTRUNC,            VT, Legal);
1232       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1233       setOperationAction(ISD::FRINT,             VT, Legal);
1234       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1235       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1236       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1237       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1238       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1239 
1240       setOperationAction(ISD::FROUND,            VT, Custom);
1241 
1242       setOperationAction(ISD::FNEG,              VT, Custom);
1243       setOperationAction(ISD::FABS,              VT, Custom);
1244       setOperationAction(ISD::FCOPYSIGN,         VT, Custom);
1245     }
1246 
1247     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1248     // even though v8i16 is a legal type.
1249     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i16, MVT::v8i32);
1250     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i16, MVT::v8i32);
1251     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1252     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1253     setOperationAction(ISD::FP_TO_SINT,                MVT::v8i32, Legal);
1254     setOperationAction(ISD::FP_TO_UINT,                MVT::v8i32, Custom);
1255     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v8i32, Legal);
1256 
1257     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1258     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i32, Legal);
1259 
1260     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v4f32, Legal);
1261     setOperationAction(ISD::STRICT_FADD,        MVT::v8f32, Legal);
1262     setOperationAction(ISD::STRICT_FADD,        MVT::v4f64, Legal);
1263     setOperationAction(ISD::STRICT_FSUB,        MVT::v8f32, Legal);
1264     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f64, Legal);
1265     setOperationAction(ISD::STRICT_FMUL,        MVT::v8f32, Legal);
1266     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f64, Legal);
1267     setOperationAction(ISD::STRICT_FDIV,        MVT::v8f32, Legal);
1268     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f64, Legal);
1269     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Legal);
1270     setOperationAction(ISD::STRICT_FSQRT,       MVT::v8f32, Legal);
1271     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f64, Legal);
1272 
1273     if (!Subtarget.hasAVX512())
1274       setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1275 
1276     // In the customized shift lowering, the legal v8i32/v4i64 cases
1277     // in AVX2 will be recognized.
1278     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1279       setOperationAction(ISD::SRL, VT, Custom);
1280       setOperationAction(ISD::SHL, VT, Custom);
1281       setOperationAction(ISD::SRA, VT, Custom);
1282       if (VT == MVT::v4i64) continue;
1283       setOperationAction(ISD::ROTL, VT, Custom);
1284       setOperationAction(ISD::ROTR, VT, Custom);
1285     }
1286 
1287     // These types need custom splitting if their input is a 128-bit vector.
1288     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i64,  Custom);
1289     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i32, Custom);
1290     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i64,  Custom);
1291     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i32, Custom);
1292 
1293     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1294     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1295     setOperationAction(ISD::SELECT,            MVT::v8i32, Custom);
1296     setOperationAction(ISD::SELECT,            MVT::v16i16, Custom);
1297     setOperationAction(ISD::SELECT,            MVT::v32i8, Custom);
1298     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1299 
1300     for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1301       setOperationAction(ISD::SIGN_EXTEND,     VT, Custom);
1302       setOperationAction(ISD::ZERO_EXTEND,     VT, Custom);
1303       setOperationAction(ISD::ANY_EXTEND,      VT, Custom);
1304     }
1305 
1306     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1307     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1308     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1309     setOperationAction(ISD::BITREVERSE,        MVT::v32i8, Custom);
1310 
1311     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1312       setOperationAction(ISD::SETCC,           VT, Custom);
1313       setOperationAction(ISD::STRICT_FSETCC,   VT, Custom);
1314       setOperationAction(ISD::STRICT_FSETCCS,  VT, Custom);
1315       setOperationAction(ISD::CTPOP,           VT, Custom);
1316       setOperationAction(ISD::CTLZ,            VT, Custom);
1317 
1318       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1319       // setcc all the way to isel and prefer SETGT in some isel patterns.
1320       setCondCodeAction(ISD::SETLT, VT, Custom);
1321       setCondCodeAction(ISD::SETLE, VT, Custom);
1322     }
1323 
1324     if (Subtarget.hasAnyFMA()) {
1325       for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1326                        MVT::v2f64, MVT::v4f64 }) {
1327         setOperationAction(ISD::FMA, VT, Legal);
1328         setOperationAction(ISD::STRICT_FMA, VT, Legal);
1329       }
1330     }
1331 
1332     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1333       setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1334       setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1335     }
1336 
1337     setOperationAction(ISD::MUL,       MVT::v4i64,  Custom);
1338     setOperationAction(ISD::MUL,       MVT::v8i32,  HasInt256 ? Legal : Custom);
1339     setOperationAction(ISD::MUL,       MVT::v16i16, HasInt256 ? Legal : Custom);
1340     setOperationAction(ISD::MUL,       MVT::v32i8,  Custom);
1341 
1342     setOperationAction(ISD::MULHU,     MVT::v8i32,  Custom);
1343     setOperationAction(ISD::MULHS,     MVT::v8i32,  Custom);
1344     setOperationAction(ISD::MULHU,     MVT::v16i16, HasInt256 ? Legal : Custom);
1345     setOperationAction(ISD::MULHS,     MVT::v16i16, HasInt256 ? Legal : Custom);
1346     setOperationAction(ISD::MULHU,     MVT::v32i8,  Custom);
1347     setOperationAction(ISD::MULHS,     MVT::v32i8,  Custom);
1348 
1349     setOperationAction(ISD::SMULO,     MVT::v32i8, Custom);
1350     setOperationAction(ISD::UMULO,     MVT::v32i8, Custom);
1351 
1352     setOperationAction(ISD::ABS,       MVT::v4i64,  Custom);
1353     setOperationAction(ISD::SMAX,      MVT::v4i64,  Custom);
1354     setOperationAction(ISD::UMAX,      MVT::v4i64,  Custom);
1355     setOperationAction(ISD::SMIN,      MVT::v4i64,  Custom);
1356     setOperationAction(ISD::UMIN,      MVT::v4i64,  Custom);
1357 
1358     setOperationAction(ISD::UADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1359     setOperationAction(ISD::SADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1360     setOperationAction(ISD::USUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1361     setOperationAction(ISD::SSUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1362     setOperationAction(ISD::UADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1363     setOperationAction(ISD::SADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1364     setOperationAction(ISD::USUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1365     setOperationAction(ISD::SSUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1366     setOperationAction(ISD::UADDSAT,   MVT::v8i32, Custom);
1367     setOperationAction(ISD::USUBSAT,   MVT::v8i32, Custom);
1368     setOperationAction(ISD::UADDSAT,   MVT::v4i64, Custom);
1369     setOperationAction(ISD::USUBSAT,   MVT::v4i64, Custom);
1370 
1371     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1372       setOperationAction(ISD::ABS,  VT, HasInt256 ? Legal : Custom);
1373       setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1374       setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1375       setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1376       setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1377     }
1378 
1379     for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1380       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1381       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1382     }
1383 
1384     if (HasInt256) {
1385       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1386       // when we have a 256bit-wide blend with immediate.
1387       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1388       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1389 
1390       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1391       for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1392         setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1393         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i8,  Legal);
1394         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i8,  Legal);
1395         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i16, Legal);
1396         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i16, Legal);
1397         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i32, Legal);
1398       }
1399     }
1400 
1401     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1402                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1403       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1404       setOperationAction(ISD::MSTORE, VT, Legal);
1405     }
1406 
1407     // Extract subvector is special because the value type
1408     // (result) is 128-bit but the source is 256-bit wide.
1409     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1410                      MVT::v4f32, MVT::v2f64 }) {
1411       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1412     }
1413 
1414     // Custom lower several nodes for 256-bit types.
1415     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1416                     MVT::v8f32, MVT::v4f64 }) {
1417       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1418       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1419       setOperationAction(ISD::VSELECT,            VT, Custom);
1420       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1421       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1422       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1423       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1424       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1425       setOperationAction(ISD::STORE,              VT, Custom);
1426     }
1427 
1428     if (HasInt256) {
1429       setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1430 
1431       // Custom legalize 2x32 to get a little better code.
1432       setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1433       setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1434 
1435       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1436                        MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1437         setOperationAction(ISD::MGATHER,  VT, Custom);
1438     }
1439   }
1440 
1441   // This block controls legalization of the mask vector sizes that are
1442   // available with AVX512. 512-bit vectors are in a separate block controlled
1443   // by useAVX512Regs.
1444   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1445     addRegisterClass(MVT::v1i1,   &X86::VK1RegClass);
1446     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1447     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1448     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1449     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1450 
1451     setOperationAction(ISD::SELECT,             MVT::v1i1, Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i1, Custom);
1454 
1455     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i1,  MVT::v8i32);
1456     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i1,  MVT::v8i32);
1457     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v4i1,  MVT::v4i32);
1458     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v4i1,  MVT::v4i32);
1459     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1,  MVT::v8i32);
1460     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1,  MVT::v8i32);
1461     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1,  MVT::v4i32);
1462     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1,  MVT::v4i32);
1463     setOperationAction(ISD::FP_TO_SINT,                MVT::v2i1,  Custom);
1464     setOperationAction(ISD::FP_TO_UINT,                MVT::v2i1,  Custom);
1465     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v2i1,  Custom);
1466     setOperationAction(ISD::STRICT_FP_TO_UINT,         MVT::v2i1,  Custom);
1467 
1468     // There is no byte sized k-register load or store without AVX512DQ.
1469     if (!Subtarget.hasDQI()) {
1470       setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1471       setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1472       setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1473       setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1474 
1475       setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1476       setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1477       setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1478       setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1479     }
1480 
1481     // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1482     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1483       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1484       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1485       setOperationAction(ISD::ANY_EXTEND,  VT, Custom);
1486     }
1487 
1488     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1489       setOperationAction(ISD::VSELECT,          VT, Expand);
1490 
1491     for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1492       setOperationAction(ISD::SETCC,            VT, Custom);
1493       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1494       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1495       setOperationAction(ISD::SELECT,           VT, Custom);
1496       setOperationAction(ISD::TRUNCATE,         VT, Custom);
1497 
1498       setOperationAction(ISD::BUILD_VECTOR,     VT, Custom);
1499       setOperationAction(ISD::CONCAT_VECTORS,   VT, Custom);
1500       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1501       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1502       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1503       setOperationAction(ISD::VECTOR_SHUFFLE,   VT,  Custom);
1504     }
1505 
1506     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1507       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1508   }
1509 
1510   // This block controls legalization for 512-bit operations with 32/64 bit
1511   // elements. 512-bits can be disabled based on prefer-vector-width and
1512   // required-vector-width function attributes.
1513   if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1514     bool HasBWI = Subtarget.hasBWI();
1515 
1516     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1517     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1518     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1519     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1520     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1521     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1522 
1523     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1524       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8,  Legal);
1525       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1526       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i8,   Legal);
1527       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i16,  Legal);
1528       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i32,  Legal);
1529       if (HasBWI)
1530         setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1531     }
1532 
1533     for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1534       setOperationAction(ISD::FNEG,  VT, Custom);
1535       setOperationAction(ISD::FABS,  VT, Custom);
1536       setOperationAction(ISD::FMA,   VT, Legal);
1537       setOperationAction(ISD::STRICT_FMA, VT, Legal);
1538       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1539     }
1540 
1541     for (MVT VT : { MVT::v16i1, MVT::v16i8, MVT::v16i16 }) {
1542       setOperationPromotedToType(ISD::FP_TO_SINT       , VT, MVT::v16i32);
1543       setOperationPromotedToType(ISD::FP_TO_UINT       , VT, MVT::v16i32);
1544       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1545       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1546     }
1547     setOperationAction(ISD::FP_TO_SINT,        MVT::v16i32, Legal);
1548     setOperationAction(ISD::FP_TO_UINT,        MVT::v16i32, Legal);
1549     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v16i32, Legal);
1550     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v16i32, Legal);
1551     setOperationAction(ISD::SINT_TO_FP,        MVT::v16i32, Legal);
1552     setOperationAction(ISD::UINT_TO_FP,        MVT::v16i32, Legal);
1553     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Legal);
1554     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Legal);
1555 
1556     setOperationAction(ISD::STRICT_FADD,      MVT::v16f32, Legal);
1557     setOperationAction(ISD::STRICT_FADD,      MVT::v8f64,  Legal);
1558     setOperationAction(ISD::STRICT_FSUB,      MVT::v16f32, Legal);
1559     setOperationAction(ISD::STRICT_FSUB,      MVT::v8f64,  Legal);
1560     setOperationAction(ISD::STRICT_FMUL,      MVT::v16f32, Legal);
1561     setOperationAction(ISD::STRICT_FMUL,      MVT::v8f64,  Legal);
1562     setOperationAction(ISD::STRICT_FDIV,      MVT::v16f32, Legal);
1563     setOperationAction(ISD::STRICT_FDIV,      MVT::v8f64,  Legal);
1564     setOperationAction(ISD::STRICT_FSQRT,     MVT::v16f32, Legal);
1565     setOperationAction(ISD::STRICT_FSQRT,     MVT::v8f64,  Legal);
1566     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f64,  Legal);
1567     setOperationAction(ISD::STRICT_FP_ROUND,  MVT::v8f32,  Legal);
1568 
1569     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1570     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1571     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1572     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1573     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1574     if (HasBWI)
1575       setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1576 
1577     // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1578     // to 512-bit rather than use the AVX2 instructions so that we can use
1579     // k-masks.
1580     if (!Subtarget.hasVLX()) {
1581       for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1582            MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1583         setOperationAction(ISD::MLOAD,  VT, Custom);
1584         setOperationAction(ISD::MSTORE, VT, Custom);
1585       }
1586     }
1587 
1588     setOperationAction(ISD::TRUNCATE,    MVT::v8i32,  Legal);
1589     setOperationAction(ISD::TRUNCATE,    MVT::v16i16, Legal);
1590     setOperationAction(ISD::TRUNCATE,    MVT::v32i8,  HasBWI ? Legal : Custom);
1591     setOperationAction(ISD::TRUNCATE,    MVT::v16i64, Custom);
1592     setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1593     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1594     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
1595     setOperationAction(ISD::ANY_EXTEND,  MVT::v32i16, Custom);
1596     setOperationAction(ISD::ANY_EXTEND,  MVT::v16i32, Custom);
1597     setOperationAction(ISD::ANY_EXTEND,  MVT::v8i64,  Custom);
1598     setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1599     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1600     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
1601 
1602     if (HasBWI) {
1603       // Extends from v64i1 masks to 512-bit vectors.
1604       setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1605       setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1606       setOperationAction(ISD::ANY_EXTEND,         MVT::v64i8, Custom);
1607     }
1608 
1609     for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1610       setOperationAction(ISD::FFLOOR,            VT, Legal);
1611       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1612       setOperationAction(ISD::FCEIL,             VT, Legal);
1613       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1614       setOperationAction(ISD::FTRUNC,            VT, Legal);
1615       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1616       setOperationAction(ISD::FRINT,             VT, Legal);
1617       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1618       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1619       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1620       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1621       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1622 
1623       setOperationAction(ISD::FROUND,            VT, Custom);
1624     }
1625 
1626     for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1627       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1628       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1629     }
1630 
1631     setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1632     setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1633     setOperationAction(ISD::ADD, MVT::v64i8,  HasBWI ? Legal : Custom);
1634     setOperationAction(ISD::SUB, MVT::v64i8,  HasBWI ? Legal : Custom);
1635 
1636     setOperationAction(ISD::MUL, MVT::v8i64,  Custom);
1637     setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1638     setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1639     setOperationAction(ISD::MUL, MVT::v64i8,  Custom);
1640 
1641     setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1642     setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1643     setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1644     setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1645     setOperationAction(ISD::MULHS, MVT::v64i8,  Custom);
1646     setOperationAction(ISD::MULHU, MVT::v64i8,  Custom);
1647 
1648     setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
1649     setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
1650 
1651     setOperationAction(ISD::BITREVERSE, MVT::v64i8,  Custom);
1652 
1653     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1654       setOperationAction(ISD::SRL,              VT, Custom);
1655       setOperationAction(ISD::SHL,              VT, Custom);
1656       setOperationAction(ISD::SRA,              VT, Custom);
1657       setOperationAction(ISD::ROTL,             VT, Custom);
1658       setOperationAction(ISD::ROTR,             VT, Custom);
1659       setOperationAction(ISD::SETCC,            VT, Custom);
1660 
1661       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1662       // setcc all the way to isel and prefer SETGT in some isel patterns.
1663       setCondCodeAction(ISD::SETLT, VT, Custom);
1664       setCondCodeAction(ISD::SETLE, VT, Custom);
1665     }
1666     for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1667       setOperationAction(ISD::SMAX,             VT, Legal);
1668       setOperationAction(ISD::UMAX,             VT, Legal);
1669       setOperationAction(ISD::SMIN,             VT, Legal);
1670       setOperationAction(ISD::UMIN,             VT, Legal);
1671       setOperationAction(ISD::ABS,              VT, Legal);
1672       setOperationAction(ISD::CTPOP,            VT, Custom);
1673       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1674       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1675     }
1676 
1677     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1678       setOperationAction(ISD::ABS,     VT, HasBWI ? Legal : Custom);
1679       setOperationAction(ISD::CTPOP,   VT, Subtarget.hasBITALG() ? Legal : Custom);
1680       setOperationAction(ISD::CTLZ,    VT, Custom);
1681       setOperationAction(ISD::SMAX,    VT, HasBWI ? Legal : Custom);
1682       setOperationAction(ISD::UMAX,    VT, HasBWI ? Legal : Custom);
1683       setOperationAction(ISD::SMIN,    VT, HasBWI ? Legal : Custom);
1684       setOperationAction(ISD::UMIN,    VT, HasBWI ? Legal : Custom);
1685       setOperationAction(ISD::UADDSAT, VT, HasBWI ? Legal : Custom);
1686       setOperationAction(ISD::SADDSAT, VT, HasBWI ? Legal : Custom);
1687       setOperationAction(ISD::USUBSAT, VT, HasBWI ? Legal : Custom);
1688       setOperationAction(ISD::SSUBSAT, VT, HasBWI ? Legal : Custom);
1689     }
1690 
1691     if (Subtarget.hasDQI()) {
1692       setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1693       setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1694       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v8i64, Legal);
1695       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i64, Legal);
1696       setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1697       setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1698       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v8i64, Legal);
1699       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i64, Legal);
1700 
1701       setOperationAction(ISD::MUL,        MVT::v8i64, Legal);
1702     }
1703 
1704     if (Subtarget.hasCDI()) {
1705       // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1706       for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1707         setOperationAction(ISD::CTLZ,            VT, Legal);
1708       }
1709     } // Subtarget.hasCDI()
1710 
1711     if (Subtarget.hasVPOPCNTDQ()) {
1712       for (auto VT : { MVT::v16i32, MVT::v8i64 })
1713         setOperationAction(ISD::CTPOP, VT, Legal);
1714     }
1715 
1716     // Extract subvector is special because the value type
1717     // (result) is 256-bit but the source is 512-bit wide.
1718     // 128-bit was made Legal under AVX1.
1719     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1720                      MVT::v8f32, MVT::v4f64 })
1721       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1722 
1723     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
1724                      MVT::v16f32, MVT::v8f64 }) {
1725       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1726       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1727       setOperationAction(ISD::SELECT,             VT, Custom);
1728       setOperationAction(ISD::VSELECT,            VT, Custom);
1729       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1730       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1731       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1732       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1733       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1734     }
1735 
1736     for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1737       setOperationAction(ISD::MLOAD,               VT, Legal);
1738       setOperationAction(ISD::MSTORE,              VT, Legal);
1739       setOperationAction(ISD::MGATHER,             VT, Custom);
1740       setOperationAction(ISD::MSCATTER,            VT, Custom);
1741     }
1742     if (HasBWI) {
1743       for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1744         setOperationAction(ISD::MLOAD,        VT, Legal);
1745         setOperationAction(ISD::MSTORE,       VT, Legal);
1746       }
1747     } else {
1748       setOperationAction(ISD::STORE, MVT::v32i16, Custom);
1749       setOperationAction(ISD::STORE, MVT::v64i8,  Custom);
1750     }
1751 
1752     if (Subtarget.hasVBMI2()) {
1753       for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
1754                        MVT::v16i16, MVT::v8i32, MVT::v4i64,
1755                        MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1756         setOperationAction(ISD::FSHL, VT, Custom);
1757         setOperationAction(ISD::FSHR, VT, Custom);
1758       }
1759 
1760       setOperationAction(ISD::ROTL, MVT::v32i16, Custom);
1761       setOperationAction(ISD::ROTR, MVT::v8i16,  Custom);
1762       setOperationAction(ISD::ROTR, MVT::v16i16, Custom);
1763       setOperationAction(ISD::ROTR, MVT::v32i16, Custom);
1764     }
1765   }// useAVX512Regs
1766 
1767   // This block controls legalization for operations that don't have
1768   // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1769   // narrower widths.
1770   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1771     // These operations are handled on non-VLX by artificially widening in
1772     // isel patterns.
1773 
1774     setOperationAction(ISD::FP_TO_UINT, MVT::v8i32,
1775                        Subtarget.hasVLX() ? Legal : Custom);
1776     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32,
1777                        Subtarget.hasVLX() ? Legal : Custom);
1778     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i32,
1779                        Subtarget.hasVLX() ? Legal : Custom);
1780     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32,
1781                        Subtarget.hasVLX() ? Legal : Custom);
1782     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v2i32, Custom);
1783     setOperationAction(ISD::UINT_TO_FP, MVT::v8i32,
1784                        Subtarget.hasVLX() ? Legal : Custom);
1785     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32,
1786                        Subtarget.hasVLX() ? Legal : Custom);
1787     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32,
1788                        Subtarget.hasVLX() ? Legal : Custom);
1789     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32,
1790                        Subtarget.hasVLX() ? Legal : Custom);
1791 
1792     if (Subtarget.hasDQI()) {
1793       // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1794       // v2f32 UINT_TO_FP is already custom under SSE2.
1795       assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
1796              isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&
1797              "Unexpected operation action!");
1798       // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1799       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f32, Custom);
1800       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f32, Custom);
1801       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
1802       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
1803     }
1804 
1805     for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1806       setOperationAction(ISD::SMAX, VT, Legal);
1807       setOperationAction(ISD::UMAX, VT, Legal);
1808       setOperationAction(ISD::SMIN, VT, Legal);
1809       setOperationAction(ISD::UMIN, VT, Legal);
1810       setOperationAction(ISD::ABS,  VT, Legal);
1811     }
1812 
1813     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1814       setOperationAction(ISD::ROTL,     VT, Custom);
1815       setOperationAction(ISD::ROTR,     VT, Custom);
1816     }
1817 
1818     // Custom legalize 2x32 to get a little better code.
1819     setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1820     setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1821 
1822     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1823                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1824       setOperationAction(ISD::MSCATTER, VT, Custom);
1825 
1826     if (Subtarget.hasDQI()) {
1827       for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1828         setOperationAction(ISD::SINT_TO_FP, VT,
1829                            Subtarget.hasVLX() ? Legal : Custom);
1830         setOperationAction(ISD::UINT_TO_FP, VT,
1831                            Subtarget.hasVLX() ? Legal : Custom);
1832         setOperationAction(ISD::STRICT_SINT_TO_FP, VT,
1833                            Subtarget.hasVLX() ? Legal : Custom);
1834         setOperationAction(ISD::STRICT_UINT_TO_FP, VT,
1835                            Subtarget.hasVLX() ? Legal : Custom);
1836         setOperationAction(ISD::FP_TO_SINT, VT,
1837                            Subtarget.hasVLX() ? Legal : Custom);
1838         setOperationAction(ISD::FP_TO_UINT, VT,
1839                            Subtarget.hasVLX() ? Legal : Custom);
1840         setOperationAction(ISD::STRICT_FP_TO_SINT, VT,
1841                            Subtarget.hasVLX() ? Legal : Custom);
1842         setOperationAction(ISD::STRICT_FP_TO_UINT, VT,
1843                            Subtarget.hasVLX() ? Legal : Custom);
1844         setOperationAction(ISD::MUL,               VT, Legal);
1845       }
1846     }
1847 
1848     if (Subtarget.hasCDI()) {
1849       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1850         setOperationAction(ISD::CTLZ,            VT, Legal);
1851       }
1852     } // Subtarget.hasCDI()
1853 
1854     if (Subtarget.hasVPOPCNTDQ()) {
1855       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1856         setOperationAction(ISD::CTPOP, VT, Legal);
1857     }
1858   }
1859 
1860   // This block control legalization of v32i1/v64i1 which are available with
1861   // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1862   // useBWIRegs.
1863   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1864     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1865     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1866 
1867     for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1868       setOperationAction(ISD::VSELECT,            VT, Expand);
1869       setOperationAction(ISD::TRUNCATE,           VT, Custom);
1870       setOperationAction(ISD::SETCC,              VT, Custom);
1871       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1872       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1873       setOperationAction(ISD::SELECT,             VT, Custom);
1874       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1875       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1876       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1877       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1878     }
1879 
1880     for (auto VT : { MVT::v16i1, MVT::v32i1 })
1881       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1882 
1883     // Extends from v32i1 masks to 256-bit vectors.
1884     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1885     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1886     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i8, Custom);
1887 
1888     for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1889       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1890       setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1891     }
1892 
1893     // These operations are handled on non-VLX by artificially widening in
1894     // isel patterns.
1895     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1896 
1897     if (Subtarget.hasBITALG()) {
1898       for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1899         setOperationAction(ISD::CTPOP, VT, Legal);
1900     }
1901   }
1902 
1903   if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
1904     auto setGroup = [&] (MVT VT) {
1905       setOperationAction(ISD::FADD,               VT, Legal);
1906       setOperationAction(ISD::STRICT_FADD,        VT, Legal);
1907       setOperationAction(ISD::FSUB,               VT, Legal);
1908       setOperationAction(ISD::STRICT_FSUB,        VT, Legal);
1909       setOperationAction(ISD::FMUL,               VT, Legal);
1910       setOperationAction(ISD::STRICT_FMUL,        VT, Legal);
1911       setOperationAction(ISD::FDIV,               VT, Legal);
1912       setOperationAction(ISD::STRICT_FDIV,        VT, Legal);
1913       setOperationAction(ISD::FSQRT,              VT, Legal);
1914       setOperationAction(ISD::STRICT_FSQRT,       VT, Legal);
1915 
1916       setOperationAction(ISD::FFLOOR,             VT, Legal);
1917       setOperationAction(ISD::STRICT_FFLOOR,      VT, Legal);
1918       setOperationAction(ISD::FCEIL,              VT, Legal);
1919       setOperationAction(ISD::STRICT_FCEIL,       VT, Legal);
1920       setOperationAction(ISD::FTRUNC,             VT, Legal);
1921       setOperationAction(ISD::STRICT_FTRUNC,      VT, Legal);
1922       setOperationAction(ISD::FRINT,              VT, Legal);
1923       setOperationAction(ISD::STRICT_FRINT,       VT, Legal);
1924       setOperationAction(ISD::FNEARBYINT,         VT, Legal);
1925       setOperationAction(ISD::STRICT_FNEARBYINT,  VT, Legal);
1926 
1927       setOperationAction(ISD::LOAD,               VT, Legal);
1928       setOperationAction(ISD::STORE,              VT, Legal);
1929 
1930       setOperationAction(ISD::FMA,                VT, Legal);
1931       setOperationAction(ISD::STRICT_FMA,         VT, Legal);
1932       setOperationAction(ISD::VSELECT,            VT, Legal);
1933       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1934       setOperationAction(ISD::SELECT,             VT, Custom);
1935 
1936       setOperationAction(ISD::FNEG,               VT, Custom);
1937       setOperationAction(ISD::FABS,               VT, Custom);
1938       setOperationAction(ISD::FCOPYSIGN,          VT, Custom);
1939       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1940       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1941     };
1942 
1943     // AVX512_FP16 scalar operations
1944     setGroup(MVT::f16);
1945     addRegisterClass(MVT::f16,    &X86::FR16XRegClass);
1946     setOperationAction(ISD::SELECT_CC,            MVT::f16, Expand);
1947     setOperationAction(ISD::BR_CC,                MVT::f16, Expand);
1948     setOperationAction(ISD::SETCC,                MVT::f16, Custom);
1949     setOperationAction(ISD::STRICT_FSETCC,        MVT::f16, Custom);
1950     setOperationAction(ISD::STRICT_FSETCCS,       MVT::f16, Custom);
1951     setOperationAction(ISD::FROUND,               MVT::f16, Custom);
1952     setOperationAction(ISD::STRICT_FROUND,        MVT::f16, Promote);
1953     setOperationAction(ISD::FROUNDEVEN,           MVT::f16, Legal);
1954     setOperationAction(ISD::STRICT_FROUNDEVEN,    MVT::f16, Legal);
1955     setOperationAction(ISD::FP_ROUND,             MVT::f16, Custom);
1956     setOperationAction(ISD::STRICT_FP_ROUND,      MVT::f16, Custom);
1957     setOperationAction(ISD::STRICT_FP_EXTEND,     MVT::f32, Legal);
1958     if (isTypeLegal(MVT::f80)) {
1959       setOperationAction(ISD::FP_EXTEND,          MVT::f80, Custom);
1960       setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::f80, Custom);
1961     }
1962 
1963     setCondCodeAction(ISD::SETOEQ, MVT::f16, Expand);
1964     setCondCodeAction(ISD::SETUNE, MVT::f16, Expand);
1965 
1966     if (Subtarget.useAVX512Regs()) {
1967       setGroup(MVT::v32f16);
1968       addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1969       setOperationAction(ISD::SCALAR_TO_VECTOR,       MVT::v32f16, Custom);
1970       setOperationAction(ISD::SINT_TO_FP,             MVT::v32i16, Legal);
1971       setOperationAction(ISD::STRICT_SINT_TO_FP,      MVT::v32i16, Legal);
1972       setOperationAction(ISD::UINT_TO_FP,             MVT::v32i16, Legal);
1973       setOperationAction(ISD::STRICT_UINT_TO_FP,      MVT::v32i16, Legal);
1974       setOperationAction(ISD::STRICT_FP_ROUND,        MVT::v16f16, Legal);
1975       setOperationAction(ISD::STRICT_FP_EXTEND,       MVT::v16f32, Legal);
1976       setOperationAction(ISD::INSERT_VECTOR_ELT,      MVT::v32f16, Custom);
1977 
1978       setOperationAction(ISD::FP_TO_SINT,             MVT::v32i16, Custom);
1979       setOperationAction(ISD::STRICT_FP_TO_SINT,      MVT::v32i16, Custom);
1980       setOperationAction(ISD::FP_TO_UINT,             MVT::v32i16, Custom);
1981       setOperationAction(ISD::STRICT_FP_TO_UINT,      MVT::v32i16, Custom);
1982       setOperationPromotedToType(ISD::FP_TO_SINT,     MVT::v32i8,  MVT::v32i16);
1983       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i8,
1984                                  MVT::v32i16);
1985       setOperationPromotedToType(ISD::FP_TO_UINT,     MVT::v32i8,  MVT::v32i16);
1986       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i8,
1987                                  MVT::v32i16);
1988       setOperationPromotedToType(ISD::FP_TO_SINT,     MVT::v32i1,  MVT::v32i16);
1989       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i1,
1990                                  MVT::v32i16);
1991       setOperationPromotedToType(ISD::FP_TO_UINT,     MVT::v32i1,  MVT::v32i16);
1992       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i1,
1993                                  MVT::v32i16);
1994 
1995       setOperationAction(ISD::EXTRACT_SUBVECTOR,      MVT::v16f16, Legal);
1996       setOperationAction(ISD::INSERT_SUBVECTOR,       MVT::v32f16, Legal);
1997       setOperationAction(ISD::CONCAT_VECTORS,         MVT::v32f16, Custom);
1998 
1999       setLoadExtAction(ISD::EXTLOAD, MVT::v8f64,  MVT::v8f16,  Legal);
2000       setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2001 
2002       setOperationAction(ISD::STRICT_FSETCC,      MVT::v32i1, Custom);
2003       setOperationAction(ISD::STRICT_FSETCCS,     MVT::v32i1, Custom);
2004     }
2005 
2006     if (Subtarget.hasVLX()) {
2007       addRegisterClass(MVT::v8f16,  &X86::VR128XRegClass);
2008       addRegisterClass(MVT::v16f16, &X86::VR256XRegClass);
2009       setGroup(MVT::v8f16);
2010       setGroup(MVT::v16f16);
2011 
2012       setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8f16,  Legal);
2013       setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16f16, Custom);
2014       setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Legal);
2015       setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v16i16, Legal);
2016       setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16,  Legal);
2017       setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i16,  Legal);
2018       setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Legal);
2019       setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v16i16, Legal);
2020       setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16,  Legal);
2021       setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v8i16,  Legal);
2022 
2023       setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
2024       setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v8i16, Custom);
2025       setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Custom);
2026       setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v8i16, Custom);
2027       setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v8f16, Legal);
2028       setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v8f32, Legal);
2029 
2030       // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2031       setOperationAction(ISD::INSERT_VECTOR_ELT,    MVT::v8f16,  Custom);
2032       setOperationAction(ISD::INSERT_VECTOR_ELT,    MVT::v16f16, Custom);
2033 
2034       setOperationAction(ISD::EXTRACT_SUBVECTOR,    MVT::v8f16, Legal);
2035       setOperationAction(ISD::INSERT_SUBVECTOR,     MVT::v16f16, Legal);
2036       setOperationAction(ISD::CONCAT_VECTORS,       MVT::v16f16, Custom);
2037 
2038       setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2039       setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2040       setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2041       setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2042 
2043       // Need to custom widen these to prevent scalarization.
2044       setOperationAction(ISD::LOAD,  MVT::v4f16, Custom);
2045       setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2046     }
2047 
2048     // Support fp16 0 immediate
2049     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
2050   }
2051 
2052   if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2053     setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
2054     setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2055     setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2056     setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
2057     setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2058 
2059     setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
2060     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2061     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2062     setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
2063     setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2064 
2065     if (Subtarget.hasBWI()) {
2066       setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
2067       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
2068     }
2069 
2070     if (Subtarget.hasFP16()) {
2071       // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2072       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f16, Custom);
2073       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f16, Custom);
2074       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f16, Custom);
2075       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f16, Custom);
2076       setOperationAction(ISD::FP_TO_SINT,        MVT::v4f16, Custom);
2077       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f16, Custom);
2078       setOperationAction(ISD::FP_TO_UINT,        MVT::v4f16, Custom);
2079       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f16, Custom);
2080       // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2081       setOperationAction(ISD::SINT_TO_FP,        MVT::v2f16, Custom);
2082       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f16, Custom);
2083       setOperationAction(ISD::UINT_TO_FP,        MVT::v2f16, Custom);
2084       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f16, Custom);
2085       setOperationAction(ISD::SINT_TO_FP,        MVT::v4f16, Custom);
2086       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f16, Custom);
2087       setOperationAction(ISD::UINT_TO_FP,        MVT::v4f16, Custom);
2088       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f16, Custom);
2089       // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2090       setOperationAction(ISD::FP_ROUND,          MVT::v2f16, Custom);
2091       setOperationAction(ISD::STRICT_FP_ROUND,   MVT::v2f16, Custom);
2092       setOperationAction(ISD::FP_ROUND,          MVT::v4f16, Custom);
2093       setOperationAction(ISD::STRICT_FP_ROUND,   MVT::v4f16, Custom);
2094       // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2095       setOperationAction(ISD::FP_EXTEND,         MVT::v2f16, Custom);
2096       setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v2f16, Custom);
2097       setOperationAction(ISD::FP_EXTEND,         MVT::v4f16, Custom);
2098       setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v4f16, Custom);
2099     }
2100 
2101     setOperationAction(ISD::TRUNCATE, MVT::v16i32, Custom);
2102     setOperationAction(ISD::TRUNCATE, MVT::v8i64, Custom);
2103     setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
2104   }
2105 
2106   if (Subtarget.hasAMXTILE()) {
2107     addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2108   }
2109 
2110   // We want to custom lower some of our intrinsics.
2111   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
2112   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
2113   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
2114   if (!Subtarget.is64Bit()) {
2115     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
2116   }
2117 
2118   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2119   // handle type legalization for these operations here.
2120   //
2121   // FIXME: We really should do custom legalization for addition and
2122   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
2123   // than generic legalization for 64-bit multiplication-with-overflow, though.
2124   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2125     if (VT == MVT::i64 && !Subtarget.is64Bit())
2126       continue;
2127     // Add/Sub/Mul with overflow operations are custom lowered.
2128     setOperationAction(ISD::SADDO, VT, Custom);
2129     setOperationAction(ISD::UADDO, VT, Custom);
2130     setOperationAction(ISD::SSUBO, VT, Custom);
2131     setOperationAction(ISD::USUBO, VT, Custom);
2132     setOperationAction(ISD::SMULO, VT, Custom);
2133     setOperationAction(ISD::UMULO, VT, Custom);
2134 
2135     // Support carry in as value rather than glue.
2136     setOperationAction(ISD::ADDCARRY, VT, Custom);
2137     setOperationAction(ISD::SUBCARRY, VT, Custom);
2138     setOperationAction(ISD::SETCCCARRY, VT, Custom);
2139     setOperationAction(ISD::SADDO_CARRY, VT, Custom);
2140     setOperationAction(ISD::SSUBO_CARRY, VT, Custom);
2141   }
2142 
2143   if (!Subtarget.is64Bit()) {
2144     // These libcalls are not available in 32-bit.
2145     setLibcallName(RTLIB::SHL_I128, nullptr);
2146     setLibcallName(RTLIB::SRL_I128, nullptr);
2147     setLibcallName(RTLIB::SRA_I128, nullptr);
2148     setLibcallName(RTLIB::MUL_I128, nullptr);
2149     // The MULO libcall is not part of libgcc, only compiler-rt.
2150     setLibcallName(RTLIB::MULO_I64, nullptr);
2151   }
2152   // The MULO libcall is not part of libgcc, only compiler-rt.
2153   setLibcallName(RTLIB::MULO_I128, nullptr);
2154 
2155   // Combine sin / cos into _sincos_stret if it is available.
2156   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
2157       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
2158     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
2159     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
2160   }
2161 
2162   if (Subtarget.isTargetWin64()) {
2163     setOperationAction(ISD::SDIV, MVT::i128, Custom);
2164     setOperationAction(ISD::UDIV, MVT::i128, Custom);
2165     setOperationAction(ISD::SREM, MVT::i128, Custom);
2166     setOperationAction(ISD::UREM, MVT::i128, Custom);
2167     setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
2168     setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
2169     setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
2170     setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
2171     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
2172     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
2173     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
2174     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
2175   }
2176 
2177   // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2178   // is. We should promote the value to 64-bits to solve this.
2179   // This is what the CRT headers do - `fmodf` is an inline header
2180   // function casting to f64 and calling `fmod`.
2181   if (Subtarget.is32Bit() &&
2182       (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2183     for (ISD::NodeType Op :
2184          {ISD::FCEIL,  ISD::STRICT_FCEIL,
2185           ISD::FCOS,   ISD::STRICT_FCOS,
2186           ISD::FEXP,   ISD::STRICT_FEXP,
2187           ISD::FFLOOR, ISD::STRICT_FFLOOR,
2188           ISD::FREM,   ISD::STRICT_FREM,
2189           ISD::FLOG,   ISD::STRICT_FLOG,
2190           ISD::FLOG10, ISD::STRICT_FLOG10,
2191           ISD::FPOW,   ISD::STRICT_FPOW,
2192           ISD::FSIN,   ISD::STRICT_FSIN})
2193       if (isOperationExpand(Op, MVT::f32))
2194         setOperationAction(Op, MVT::f32, Promote);
2195 
2196   // We have target-specific dag combine patterns for the following nodes:
2197   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
2198   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
2199   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
2200   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
2201   setTargetDAGCombine(ISD::CONCAT_VECTORS);
2202   setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
2203   setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
2204   setTargetDAGCombine(ISD::BITCAST);
2205   setTargetDAGCombine(ISD::VSELECT);
2206   setTargetDAGCombine(ISD::SELECT);
2207   setTargetDAGCombine(ISD::SHL);
2208   setTargetDAGCombine(ISD::SRA);
2209   setTargetDAGCombine(ISD::SRL);
2210   setTargetDAGCombine(ISD::OR);
2211   setTargetDAGCombine(ISD::AND);
2212   setTargetDAGCombine(ISD::ADD);
2213   setTargetDAGCombine(ISD::FADD);
2214   setTargetDAGCombine(ISD::FSUB);
2215   setTargetDAGCombine(ISD::FNEG);
2216   setTargetDAGCombine(ISD::FMA);
2217   setTargetDAGCombine(ISD::STRICT_FMA);
2218   setTargetDAGCombine(ISD::FMINNUM);
2219   setTargetDAGCombine(ISD::FMAXNUM);
2220   setTargetDAGCombine(ISD::SUB);
2221   setTargetDAGCombine(ISD::LOAD);
2222   setTargetDAGCombine(ISD::MLOAD);
2223   setTargetDAGCombine(ISD::STORE);
2224   setTargetDAGCombine(ISD::MSTORE);
2225   setTargetDAGCombine(ISD::TRUNCATE);
2226   setTargetDAGCombine(ISD::ZERO_EXTEND);
2227   setTargetDAGCombine(ISD::ANY_EXTEND);
2228   setTargetDAGCombine(ISD::SIGN_EXTEND);
2229   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
2230   setTargetDAGCombine(ISD::ANY_EXTEND_VECTOR_INREG);
2231   setTargetDAGCombine(ISD::SIGN_EXTEND_VECTOR_INREG);
2232   setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
2233   setTargetDAGCombine(ISD::SINT_TO_FP);
2234   setTargetDAGCombine(ISD::UINT_TO_FP);
2235   setTargetDAGCombine(ISD::STRICT_SINT_TO_FP);
2236   setTargetDAGCombine(ISD::STRICT_UINT_TO_FP);
2237   setTargetDAGCombine(ISD::SETCC);
2238   setTargetDAGCombine(ISD::MUL);
2239   setTargetDAGCombine(ISD::XOR);
2240   setTargetDAGCombine(ISD::MSCATTER);
2241   setTargetDAGCombine(ISD::MGATHER);
2242   setTargetDAGCombine(ISD::FP16_TO_FP);
2243   setTargetDAGCombine(ISD::FP_EXTEND);
2244   setTargetDAGCombine(ISD::STRICT_FP_EXTEND);
2245   setTargetDAGCombine(ISD::FP_ROUND);
2246 
2247   computeRegisterProperties(Subtarget.getRegisterInfo());
2248 
2249   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2250   MaxStoresPerMemsetOptSize = 8;
2251   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2252   MaxStoresPerMemcpyOptSize = 4;
2253   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2254   MaxStoresPerMemmoveOptSize = 4;
2255 
2256   // TODO: These control memcmp expansion in CGP and could be raised higher, but
2257   // that needs to benchmarked and balanced with the potential use of vector
2258   // load/store types (PR33329, PR33914).
2259   MaxLoadsPerMemcmp = 2;
2260   MaxLoadsPerMemcmpOptSize = 2;
2261 
2262   // Default loop alignment, which can be overridden by -align-loops.
2263   setPrefLoopAlignment(Align(16));
2264 
2265   // An out-of-order CPU can speculatively execute past a predictable branch,
2266   // but a conditional move could be stalled by an expensive earlier operation.
2267   PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2268   EnableExtLdPromotion = true;
2269   setPrefFunctionAlignment(Align(16));
2270 
2271   verifyIntrinsicTables();
2272 
2273   // Default to having -disable-strictnode-mutation on
2274   IsStrictFPEnabled = true;
2275 }
2276 
2277 // This has so far only been implemented for 64-bit MachO.
2278 bool X86TargetLowering::useLoadStackGuardNode() const {
2279   return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2280 }
2281 
2282 bool X86TargetLowering::useStackGuardXorFP() const {
2283   // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2284   return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2285 }
2286 
2287 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2288                                                const SDLoc &DL) const {
2289   EVT PtrTy = getPointerTy(DAG.getDataLayout());
2290   unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2291   MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2292   return SDValue(Node, 0);
2293 }
2294 
2295 TargetLoweringBase::LegalizeTypeAction
2296 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2297   if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2298       !Subtarget.hasBWI())
2299     return TypeSplitVector;
2300 
2301   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2302       VT.getVectorElementType() != MVT::i1)
2303     return TypeWidenVector;
2304 
2305   return TargetLoweringBase::getPreferredVectorAction(VT);
2306 }
2307 
2308 static std::pair<MVT, unsigned>
2309 handleMaskRegisterForCallingConv(unsigned NumElts, CallingConv::ID CC,
2310                                  const X86Subtarget &Subtarget) {
2311   // v2i1/v4i1/v8i1/v16i1 all pass in xmm registers unless the calling
2312   // convention is one that uses k registers.
2313   if (NumElts == 2)
2314     return {MVT::v2i64, 1};
2315   if (NumElts == 4)
2316     return {MVT::v4i32, 1};
2317   if (NumElts == 8 && CC != CallingConv::X86_RegCall &&
2318       CC != CallingConv::Intel_OCL_BI)
2319     return {MVT::v8i16, 1};
2320   if (NumElts == 16 && CC != CallingConv::X86_RegCall &&
2321       CC != CallingConv::Intel_OCL_BI)
2322     return {MVT::v16i8, 1};
2323   // v32i1 passes in ymm unless we have BWI and the calling convention is
2324   // regcall.
2325   if (NumElts == 32 && (!Subtarget.hasBWI() || CC != CallingConv::X86_RegCall))
2326     return {MVT::v32i8, 1};
2327   // Split v64i1 vectors if we don't have v64i8 available.
2328   if (NumElts == 64 && Subtarget.hasBWI() && CC != CallingConv::X86_RegCall) {
2329     if (Subtarget.useAVX512Regs())
2330       return {MVT::v64i8, 1};
2331     return {MVT::v32i8, 2};
2332   }
2333 
2334   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2335   if (!isPowerOf2_32(NumElts) || (NumElts == 64 && !Subtarget.hasBWI()) ||
2336       NumElts > 64)
2337     return {MVT::i8, NumElts};
2338 
2339   return {MVT::INVALID_SIMPLE_VALUE_TYPE, 0};
2340 }
2341 
2342 MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
2343                                                      CallingConv::ID CC,
2344                                                      EVT VT) const {
2345   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2346       Subtarget.hasAVX512()) {
2347     unsigned NumElts = VT.getVectorNumElements();
2348 
2349     MVT RegisterVT;
2350     unsigned NumRegisters;
2351     std::tie(RegisterVT, NumRegisters) =
2352         handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2353     if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2354       return RegisterVT;
2355   }
2356 
2357   // v3f16 will be widen to v4f16. But we don't assign register class for v4f16.
2358   // So its default register type is f16. We override the type to v8f16 here.
2359   if (VT == MVT::v3f16 && Subtarget.hasFP16())
2360     return MVT::v8f16;
2361 
2362   // We will use more GPRs for f64 and f80 on 32 bits when x87 is disabled.
2363   if ((VT == MVT::f64 || VT == MVT::f80) && !Subtarget.is64Bit() &&
2364       !Subtarget.hasX87())
2365     return MVT::i32;
2366 
2367   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
2368 }
2369 
2370 unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
2371                                                           CallingConv::ID CC,
2372                                                           EVT VT) const {
2373   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2374       Subtarget.hasAVX512()) {
2375     unsigned NumElts = VT.getVectorNumElements();
2376 
2377     MVT RegisterVT;
2378     unsigned NumRegisters;
2379     std::tie(RegisterVT, NumRegisters) =
2380         handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2381     if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2382       return NumRegisters;
2383   }
2384 
2385   // v3f16 will be widen to v4f16. But we don't assign register class for v4f16.
2386   // So its default register number is 3. We override the number to 1 here.
2387   if (VT == MVT::v3f16 && Subtarget.hasFP16())
2388     return 1;
2389 
2390   // We have to split f64 to 2 registers and f80 to 3 registers on 32 bits if
2391   // x87 is disabled.
2392   if (!Subtarget.is64Bit() && !Subtarget.hasX87()) {
2393     if (VT == MVT::f64)
2394       return 2;
2395     if (VT == MVT::f80)
2396       return 3;
2397   }
2398 
2399   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
2400 }
2401 
2402 unsigned X86TargetLowering::getVectorTypeBreakdownForCallingConv(
2403     LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
2404     unsigned &NumIntermediates, MVT &RegisterVT) const {
2405   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2406   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2407       Subtarget.hasAVX512() &&
2408       (!isPowerOf2_32(VT.getVectorNumElements()) ||
2409        (VT.getVectorNumElements() == 64 && !Subtarget.hasBWI()) ||
2410        VT.getVectorNumElements() > 64)) {
2411     RegisterVT = MVT::i8;
2412     IntermediateVT = MVT::i1;
2413     NumIntermediates = VT.getVectorNumElements();
2414     return NumIntermediates;
2415   }
2416 
2417   // Split v64i1 vectors if we don't have v64i8 available.
2418   if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2419       CC != CallingConv::X86_RegCall) {
2420     RegisterVT = MVT::v32i8;
2421     IntermediateVT = MVT::v32i1;
2422     NumIntermediates = 2;
2423     return 2;
2424   }
2425 
2426   return TargetLowering::getVectorTypeBreakdownForCallingConv(Context, CC, VT, IntermediateVT,
2427                                               NumIntermediates, RegisterVT);
2428 }
2429 
2430 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
2431                                           LLVMContext& Context,
2432                                           EVT VT) const {
2433   if (!VT.isVector())
2434     return MVT::i8;
2435 
2436   if (Subtarget.hasAVX512()) {
2437     // Figure out what this type will be legalized to.
2438     EVT LegalVT = VT;
2439     while (getTypeAction(Context, LegalVT) != TypeLegal)
2440       LegalVT = getTypeToTransformTo(Context, LegalVT);
2441 
2442     // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
2443     if (LegalVT.getSimpleVT().is512BitVector())
2444       return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2445 
2446     if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
2447       // If we legalized to less than a 512-bit vector, then we will use a vXi1
2448       // compare for vXi32/vXi64 for sure. If we have BWI we will also support
2449       // vXi16/vXi8.
2450       MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
2451       if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
2452         return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2453     }
2454   }
2455 
2456   return VT.changeVectorElementTypeToInteger();
2457 }
2458 
2459 /// Helper for getByValTypeAlignment to determine
2460 /// the desired ByVal argument alignment.
2461 static void getMaxByValAlign(Type *Ty, Align &MaxAlign) {
2462   if (MaxAlign == 16)
2463     return;
2464   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2465     if (VTy->getPrimitiveSizeInBits().getFixedSize() == 128)
2466       MaxAlign = Align(16);
2467   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2468     Align EltAlign;
2469     getMaxByValAlign(ATy->getElementType(), EltAlign);
2470     if (EltAlign > MaxAlign)
2471       MaxAlign = EltAlign;
2472   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2473     for (auto *EltTy : STy->elements()) {
2474       Align EltAlign;
2475       getMaxByValAlign(EltTy, EltAlign);
2476       if (EltAlign > MaxAlign)
2477         MaxAlign = EltAlign;
2478       if (MaxAlign == 16)
2479         break;
2480     }
2481   }
2482 }
2483 
2484 /// Return the desired alignment for ByVal aggregate
2485 /// function arguments in the caller parameter area. For X86, aggregates
2486 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2487 /// are at 4-byte boundaries.
2488 uint64_t X86TargetLowering::getByValTypeAlignment(Type *Ty,
2489                                                   const DataLayout &DL) const {
2490   if (Subtarget.is64Bit()) {
2491     // Max of 8 and alignment of type.
2492     Align TyAlign = DL.getABITypeAlign(Ty);
2493     if (TyAlign > 8)
2494       return TyAlign.value();
2495     return 8;
2496   }
2497 
2498   Align Alignment(4);
2499   if (Subtarget.hasSSE1())
2500     getMaxByValAlign(Ty, Alignment);
2501   return Alignment.value();
2502 }
2503 
2504 /// It returns EVT::Other if the type should be determined using generic
2505 /// target-independent logic.
2506 /// For vector ops we check that the overall size isn't larger than our
2507 /// preferred vector width.
2508 EVT X86TargetLowering::getOptimalMemOpType(
2509     const MemOp &Op, const AttributeList &FuncAttributes) const {
2510   if (!FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
2511     if (Op.size() >= 16 &&
2512         (!Subtarget.isUnalignedMem16Slow() || Op.isAligned(Align(16)))) {
2513       // FIXME: Check if unaligned 64-byte accesses are slow.
2514       if (Op.size() >= 64 && Subtarget.hasAVX512() &&
2515           (Subtarget.getPreferVectorWidth() >= 512)) {
2516         return Subtarget.hasBWI() ? MVT::v64i8 : MVT::v16i32;
2517       }
2518       // FIXME: Check if unaligned 32-byte accesses are slow.
2519       if (Op.size() >= 32 && Subtarget.hasAVX() &&
2520           (Subtarget.getPreferVectorWidth() >= 256)) {
2521         // Although this isn't a well-supported type for AVX1, we'll let
2522         // legalization and shuffle lowering produce the optimal codegen. If we
2523         // choose an optimal type with a vector element larger than a byte,
2524         // getMemsetStores() may create an intermediate splat (using an integer
2525         // multiply) before we splat as a vector.
2526         return MVT::v32i8;
2527       }
2528       if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2529         return MVT::v16i8;
2530       // TODO: Can SSE1 handle a byte vector?
2531       // If we have SSE1 registers we should be able to use them.
2532       if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2533           (Subtarget.getPreferVectorWidth() >= 128))
2534         return MVT::v4f32;
2535     } else if (((Op.isMemcpy() && !Op.isMemcpyStrSrc()) || Op.isZeroMemset()) &&
2536                Op.size() >= 8 && !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2537       // Do not use f64 to lower memcpy if source is string constant. It's
2538       // better to use i32 to avoid the loads.
2539       // Also, do not use f64 to lower memset unless this is a memset of zeros.
2540       // The gymnastics of splatting a byte value into an XMM register and then
2541       // only using 8-byte stores (because this is a CPU with slow unaligned
2542       // 16-byte accesses) makes that a loser.
2543       return MVT::f64;
2544     }
2545   }
2546   // This is a compromise. If we reach here, unaligned accesses may be slow on
2547   // this target. However, creating smaller, aligned accesses could be even
2548   // slower and would certainly be a lot more code.
2549   if (Subtarget.is64Bit() && Op.size() >= 8)
2550     return MVT::i64;
2551   return MVT::i32;
2552 }
2553 
2554 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2555   if (VT == MVT::f32)
2556     return X86ScalarSSEf32;
2557   if (VT == MVT::f64)
2558     return X86ScalarSSEf64;
2559   return true;
2560 }
2561 
2562 bool X86TargetLowering::allowsMisalignedMemoryAccesses(
2563     EVT VT, unsigned, Align Alignment, MachineMemOperand::Flags Flags,
2564     bool *Fast) const {
2565   if (Fast) {
2566     switch (VT.getSizeInBits()) {
2567     default:
2568       // 8-byte and under are always assumed to be fast.
2569       *Fast = true;
2570       break;
2571     case 128:
2572       *Fast = !Subtarget.isUnalignedMem16Slow();
2573       break;
2574     case 256:
2575       *Fast = !Subtarget.isUnalignedMem32Slow();
2576       break;
2577     // TODO: What about AVX-512 (512-bit) accesses?
2578     }
2579   }
2580   // NonTemporal vector memory ops must be aligned.
2581   if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2582     // NT loads can only be vector aligned, so if its less aligned than the
2583     // minimum vector size (which we can split the vector down to), we might as
2584     // well use a regular unaligned vector load.
2585     // We don't have any NT loads pre-SSE41.
2586     if (!!(Flags & MachineMemOperand::MOLoad))
2587       return (Alignment < 16 || !Subtarget.hasSSE41());
2588     return false;
2589   }
2590   // Misaligned accesses of any size are always allowed.
2591   return true;
2592 }
2593 
2594 /// Return the entry encoding for a jump table in the
2595 /// current function.  The returned value is a member of the
2596 /// MachineJumpTableInfo::JTEntryKind enum.
2597 unsigned X86TargetLowering::getJumpTableEncoding() const {
2598   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2599   // symbol.
2600   if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2601     return MachineJumpTableInfo::EK_Custom32;
2602 
2603   // Otherwise, use the normal jump table encoding heuristics.
2604   return TargetLowering::getJumpTableEncoding();
2605 }
2606 
2607 bool X86TargetLowering::useSoftFloat() const {
2608   return Subtarget.useSoftFloat();
2609 }
2610 
2611 void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2612                                               ArgListTy &Args) const {
2613 
2614   // Only relabel X86-32 for C / Stdcall CCs.
2615   if (Subtarget.is64Bit())
2616     return;
2617   if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2618     return;
2619   unsigned ParamRegs = 0;
2620   if (auto *M = MF->getFunction().getParent())
2621     ParamRegs = M->getNumberRegisterParameters();
2622 
2623   // Mark the first N int arguments as having reg
2624   for (auto &Arg : Args) {
2625     Type *T = Arg.Ty;
2626     if (T->isIntOrPtrTy())
2627       if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2628         unsigned numRegs = 1;
2629         if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2630           numRegs = 2;
2631         if (ParamRegs < numRegs)
2632           return;
2633         ParamRegs -= numRegs;
2634         Arg.IsInReg = true;
2635       }
2636   }
2637 }
2638 
2639 const MCExpr *
2640 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2641                                              const MachineBasicBlock *MBB,
2642                                              unsigned uid,MCContext &Ctx) const{
2643   assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2644   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2645   // entries.
2646   return MCSymbolRefExpr::create(MBB->getSymbol(),
2647                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2648 }
2649 
2650 /// Returns relocation base for the given PIC jumptable.
2651 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2652                                                     SelectionDAG &DAG) const {
2653   if (!Subtarget.is64Bit())
2654     // This doesn't have SDLoc associated with it, but is not really the
2655     // same as a Register.
2656     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2657                        getPointerTy(DAG.getDataLayout()));
2658   return Table;
2659 }
2660 
2661 /// This returns the relocation base for the given PIC jumptable,
2662 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2663 const MCExpr *X86TargetLowering::
2664 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2665                              MCContext &Ctx) const {
2666   // X86-64 uses RIP relative addressing based on the jump table label.
2667   if (Subtarget.isPICStyleRIPRel())
2668     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2669 
2670   // Otherwise, the reference is relative to the PIC base.
2671   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2672 }
2673 
2674 std::pair<const TargetRegisterClass *, uint8_t>
2675 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2676                                            MVT VT) const {
2677   const TargetRegisterClass *RRC = nullptr;
2678   uint8_t Cost = 1;
2679   switch (VT.SimpleTy) {
2680   default:
2681     return TargetLowering::findRepresentativeClass(TRI, VT);
2682   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2683     RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2684     break;
2685   case MVT::x86mmx:
2686     RRC = &X86::VR64RegClass;
2687     break;
2688   case MVT::f32: case MVT::f64:
2689   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2690   case MVT::v4f32: case MVT::v2f64:
2691   case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2692   case MVT::v8f32: case MVT::v4f64:
2693   case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2694   case MVT::v16f32: case MVT::v8f64:
2695     RRC = &X86::VR128XRegClass;
2696     break;
2697   }
2698   return std::make_pair(RRC, Cost);
2699 }
2700 
2701 unsigned X86TargetLowering::getAddressSpace() const {
2702   if (Subtarget.is64Bit())
2703     return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2704   return 256;
2705 }
2706 
2707 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2708   return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2709          (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2710 }
2711 
2712 static Constant* SegmentOffset(IRBuilderBase &IRB,
2713                                int Offset, unsigned AddressSpace) {
2714   return ConstantExpr::getIntToPtr(
2715       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2716       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2717 }
2718 
2719 Value *X86TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
2720   // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2721   // tcbhead_t; use it instead of the usual global variable (see
2722   // sysdeps/{i386,x86_64}/nptl/tls.h)
2723   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2724     if (Subtarget.isTargetFuchsia()) {
2725       // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2726       return SegmentOffset(IRB, 0x10, getAddressSpace());
2727     } else {
2728       unsigned AddressSpace = getAddressSpace();
2729       Module *M = IRB.GetInsertBlock()->getParent()->getParent();
2730       // Specially, some users may customize the base reg and offset.
2731       int Offset = M->getStackProtectorGuardOffset();
2732       // If we don't set -stack-protector-guard-offset value:
2733       // %fs:0x28, unless we're using a Kernel code model, in which case
2734       // it's %gs:0x28.  gs:0x14 on i386.
2735       if (Offset == INT_MAX)
2736         Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2737 
2738       StringRef GuardReg = M->getStackProtectorGuardReg();
2739       if (GuardReg == "fs")
2740         AddressSpace = X86AS::FS;
2741       else if (GuardReg == "gs")
2742         AddressSpace = X86AS::GS;
2743       return SegmentOffset(IRB, Offset, AddressSpace);
2744     }
2745   }
2746   return TargetLowering::getIRStackGuard(IRB);
2747 }
2748 
2749 void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2750   // MSVC CRT provides functionalities for stack protection.
2751   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2752       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2753     // MSVC CRT has a global variable holding security cookie.
2754     M.getOrInsertGlobal("__security_cookie",
2755                         Type::getInt8PtrTy(M.getContext()));
2756 
2757     // MSVC CRT has a function to validate security cookie.
2758     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2759         "__security_check_cookie", Type::getVoidTy(M.getContext()),
2760         Type::getInt8PtrTy(M.getContext()));
2761     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2762       F->setCallingConv(CallingConv::X86_FastCall);
2763       F->addParamAttr(0, Attribute::AttrKind::InReg);
2764     }
2765     return;
2766   }
2767 
2768   StringRef GuardMode = M.getStackProtectorGuard();
2769 
2770   // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2771   if ((GuardMode == "tls" || GuardMode.empty()) &&
2772       hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2773     return;
2774   TargetLowering::insertSSPDeclarations(M);
2775 }
2776 
2777 Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2778   // MSVC CRT has a global variable holding security cookie.
2779   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2780       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2781     return M.getGlobalVariable("__security_cookie");
2782   }
2783   return TargetLowering::getSDagStackGuard(M);
2784 }
2785 
2786 Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2787   // MSVC CRT has a function to validate security cookie.
2788   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2789       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2790     return M.getFunction("__security_check_cookie");
2791   }
2792   return TargetLowering::getSSPStackGuardCheck(M);
2793 }
2794 
2795 Value *
2796 X86TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
2797   if (Subtarget.getTargetTriple().isOSContiki())
2798     return getDefaultSafeStackPointerLocation(IRB, false);
2799 
2800   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2801   // definition of TLS_SLOT_SAFESTACK in
2802   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2803   if (Subtarget.isTargetAndroid()) {
2804     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2805     // %gs:0x24 on i386
2806     int Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2807     return SegmentOffset(IRB, Offset, getAddressSpace());
2808   }
2809 
2810   // Fuchsia is similar.
2811   if (Subtarget.isTargetFuchsia()) {
2812     // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2813     return SegmentOffset(IRB, 0x18, getAddressSpace());
2814   }
2815 
2816   return TargetLowering::getSafeStackPointerLocation(IRB);
2817 }
2818 
2819 //===----------------------------------------------------------------------===//
2820 //               Return Value Calling Convention Implementation
2821 //===----------------------------------------------------------------------===//
2822 
2823 bool X86TargetLowering::CanLowerReturn(
2824     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2825     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2826   SmallVector<CCValAssign, 16> RVLocs;
2827   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2828   return CCInfo.CheckReturn(Outs, RetCC_X86);
2829 }
2830 
2831 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2832   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2833   return ScratchRegs;
2834 }
2835 
2836 /// Lowers masks values (v*i1) to the local register values
2837 /// \returns DAG node after lowering to register type
2838 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2839                                const SDLoc &Dl, SelectionDAG &DAG) {
2840   EVT ValVT = ValArg.getValueType();
2841 
2842   if (ValVT == MVT::v1i1)
2843     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2844                        DAG.getIntPtrConstant(0, Dl));
2845 
2846   if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2847       (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2848     // Two stage lowering might be required
2849     // bitcast:   v8i1 -> i8 / v16i1 -> i16
2850     // anyextend: i8   -> i32 / i16   -> i32
2851     EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2852     SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2853     if (ValLoc == MVT::i32)
2854       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2855     return ValToCopy;
2856   }
2857 
2858   if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2859       (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2860     // One stage lowering is required
2861     // bitcast:   v32i1 -> i32 / v64i1 -> i64
2862     return DAG.getBitcast(ValLoc, ValArg);
2863   }
2864 
2865   return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2866 }
2867 
2868 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2869 static void Passv64i1ArgInRegs(
2870     const SDLoc &Dl, SelectionDAG &DAG, SDValue &Arg,
2871     SmallVectorImpl<std::pair<Register, SDValue>> &RegsToPass, CCValAssign &VA,
2872     CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2873   assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2874   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2875   assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2876   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2877          "The value should reside in two registers");
2878 
2879   // Before splitting the value we cast it to i64
2880   Arg = DAG.getBitcast(MVT::i64, Arg);
2881 
2882   // Splitting the value into two i32 types
2883   SDValue Lo, Hi;
2884   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2885                    DAG.getConstant(0, Dl, MVT::i32));
2886   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2887                    DAG.getConstant(1, Dl, MVT::i32));
2888 
2889   // Attach the two i32 types into corresponding registers
2890   RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2891   RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2892 }
2893 
2894 SDValue
2895 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2896                                bool isVarArg,
2897                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2898                                const SmallVectorImpl<SDValue> &OutVals,
2899                                const SDLoc &dl, SelectionDAG &DAG) const {
2900   MachineFunction &MF = DAG.getMachineFunction();
2901   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2902 
2903   // In some cases we need to disable registers from the default CSR list.
2904   // For example, when they are used for argument passing.
2905   bool ShouldDisableCalleeSavedRegister =
2906       CallConv == CallingConv::X86_RegCall ||
2907       MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2908 
2909   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2910     report_fatal_error("X86 interrupts may not return any value");
2911 
2912   SmallVector<CCValAssign, 16> RVLocs;
2913   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2914   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2915 
2916   SmallVector<std::pair<Register, SDValue>, 4> RetVals;
2917   for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2918        ++I, ++OutsIndex) {
2919     CCValAssign &VA = RVLocs[I];
2920     assert(VA.isRegLoc() && "Can only return in registers!");
2921 
2922     // Add the register to the CalleeSaveDisableRegs list.
2923     if (ShouldDisableCalleeSavedRegister)
2924       MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2925 
2926     SDValue ValToCopy = OutVals[OutsIndex];
2927     EVT ValVT = ValToCopy.getValueType();
2928 
2929     // Promote values to the appropriate types.
2930     if (VA.getLocInfo() == CCValAssign::SExt)
2931       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2932     else if (VA.getLocInfo() == CCValAssign::ZExt)
2933       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2934     else if (VA.getLocInfo() == CCValAssign::AExt) {
2935       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2936         ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2937       else
2938         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2939     }
2940     else if (VA.getLocInfo() == CCValAssign::BCvt)
2941       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2942 
2943     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2944            "Unexpected FP-extend for return value.");
2945 
2946     // Report an error if we have attempted to return a value via an XMM
2947     // register and SSE was disabled.
2948     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
2949       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2950       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2951     } else if (!Subtarget.hasSSE2() &&
2952                X86::FR64XRegClass.contains(VA.getLocReg()) &&
2953                ValVT == MVT::f64) {
2954       // When returning a double via an XMM register, report an error if SSE2 is
2955       // not enabled.
2956       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2957       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2958     }
2959 
2960     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2961     // the RET instruction and handled by the FP Stackifier.
2962     if (VA.getLocReg() == X86::FP0 ||
2963         VA.getLocReg() == X86::FP1) {
2964       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2965       // change the value to the FP stack register class.
2966       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2967         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2968       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2969       // Don't emit a copytoreg.
2970       continue;
2971     }
2972 
2973     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2974     // which is returned in RAX / RDX.
2975     if (Subtarget.is64Bit()) {
2976       if (ValVT == MVT::x86mmx) {
2977         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2978           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2979           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2980                                   ValToCopy);
2981           // If we don't have SSE2 available, convert to v4f32 so the generated
2982           // register is legal.
2983           if (!Subtarget.hasSSE2())
2984             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2985         }
2986       }
2987     }
2988 
2989     if (VA.needsCustom()) {
2990       assert(VA.getValVT() == MVT::v64i1 &&
2991              "Currently the only custom case is when we split v64i1 to 2 regs");
2992 
2993       Passv64i1ArgInRegs(dl, DAG, ValToCopy, RetVals, VA, RVLocs[++I],
2994                          Subtarget);
2995 
2996       // Add the second register to the CalleeSaveDisableRegs list.
2997       if (ShouldDisableCalleeSavedRegister)
2998         MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2999     } else {
3000       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
3001     }
3002   }
3003 
3004   SDValue Flag;
3005   SmallVector<SDValue, 6> RetOps;
3006   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3007   // Operand #1 = Bytes To Pop
3008   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
3009                    MVT::i32));
3010 
3011   // Copy the result values into the output registers.
3012   for (auto &RetVal : RetVals) {
3013     if (RetVal.first == X86::FP0 || RetVal.first == X86::FP1) {
3014       RetOps.push_back(RetVal.second);
3015       continue; // Don't emit a copytoreg.
3016     }
3017 
3018     Chain = DAG.getCopyToReg(Chain, dl, RetVal.first, RetVal.second, Flag);
3019     Flag = Chain.getValue(1);
3020     RetOps.push_back(
3021         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
3022   }
3023 
3024   // Swift calling convention does not require we copy the sret argument
3025   // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
3026 
3027   // All x86 ABIs require that for returning structs by value we copy
3028   // the sret argument into %rax/%eax (depending on ABI) for the return.
3029   // We saved the argument into a virtual register in the entry block,
3030   // so now we copy the value out and into %rax/%eax.
3031   //
3032   // Checking Function.hasStructRetAttr() here is insufficient because the IR
3033   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
3034   // false, then an sret argument may be implicitly inserted in the SelDAG. In
3035   // either case FuncInfo->setSRetReturnReg() will have been called.
3036   if (Register SRetReg = FuncInfo->getSRetReturnReg()) {
3037     // When we have both sret and another return value, we should use the
3038     // original Chain stored in RetOps[0], instead of the current Chain updated
3039     // in the above loop. If we only have sret, RetOps[0] equals to Chain.
3040 
3041     // For the case of sret and another return value, we have
3042     //   Chain_0 at the function entry
3043     //   Chain_1 = getCopyToReg(Chain_0) in the above loop
3044     // If we use Chain_1 in getCopyFromReg, we will have
3045     //   Val = getCopyFromReg(Chain_1)
3046     //   Chain_2 = getCopyToReg(Chain_1, Val) from below
3047 
3048     // getCopyToReg(Chain_0) will be glued together with
3049     // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
3050     // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
3051     //   Data dependency from Unit B to Unit A due to usage of Val in
3052     //     getCopyToReg(Chain_1, Val)
3053     //   Chain dependency from Unit A to Unit B
3054 
3055     // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
3056     SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
3057                                      getPointerTy(MF.getDataLayout()));
3058 
3059     Register RetValReg
3060         = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
3061           X86::RAX : X86::EAX;
3062     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
3063     Flag = Chain.getValue(1);
3064 
3065     // RAX/EAX now acts like a return value.
3066     RetOps.push_back(
3067         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
3068 
3069     // Add the returned register to the CalleeSaveDisableRegs list.
3070     if (ShouldDisableCalleeSavedRegister)
3071       MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
3072   }
3073 
3074   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
3075   const MCPhysReg *I =
3076       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3077   if (I) {
3078     for (; *I; ++I) {
3079       if (X86::GR64RegClass.contains(*I))
3080         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3081       else
3082         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3083     }
3084   }
3085 
3086   RetOps[0] = Chain;  // Update chain.
3087 
3088   // Add the flag if we have it.
3089   if (Flag.getNode())
3090     RetOps.push_back(Flag);
3091 
3092   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
3093   if (CallConv == CallingConv::X86_INTR)
3094     opcode = X86ISD::IRET;
3095   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
3096 }
3097 
3098 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3099   if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
3100     return false;
3101 
3102   SDValue TCChain = Chain;
3103   SDNode *Copy = *N->use_begin();
3104   if (Copy->getOpcode() == ISD::CopyToReg) {
3105     // If the copy has a glue operand, we conservatively assume it isn't safe to
3106     // perform a tail call.
3107     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3108       return false;
3109     TCChain = Copy->getOperand(0);
3110   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
3111     return false;
3112 
3113   bool HasRet = false;
3114   for (const SDNode *U : Copy->uses()) {
3115     if (U->getOpcode() != X86ISD::RET_FLAG)
3116       return false;
3117     // If we are returning more than one value, we can definitely
3118     // not make a tail call see PR19530
3119     if (U->getNumOperands() > 4)
3120       return false;
3121     if (U->getNumOperands() == 4 &&
3122         U->getOperand(U->getNumOperands() - 1).getValueType() != MVT::Glue)
3123       return false;
3124     HasRet = true;
3125   }
3126 
3127   if (!HasRet)
3128     return false;
3129 
3130   Chain = TCChain;
3131   return true;
3132 }
3133 
3134 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
3135                                            ISD::NodeType ExtendKind) const {
3136   MVT ReturnMVT = MVT::i32;
3137 
3138   bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
3139   if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
3140     // The ABI does not require i1, i8 or i16 to be extended.
3141     //
3142     // On Darwin, there is code in the wild relying on Clang's old behaviour of
3143     // always extending i8/i16 return values, so keep doing that for now.
3144     // (PR26665).
3145     ReturnMVT = MVT::i8;
3146   }
3147 
3148   EVT MinVT = getRegisterType(Context, ReturnMVT);
3149   return VT.bitsLT(MinVT) ? MinVT : VT;
3150 }
3151 
3152 /// Reads two 32 bit registers and creates a 64 bit mask value.
3153 /// \param VA The current 32 bit value that need to be assigned.
3154 /// \param NextVA The next 32 bit value that need to be assigned.
3155 /// \param Root The parent DAG node.
3156 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
3157 ///                        glue purposes. In the case the DAG is already using
3158 ///                        physical register instead of virtual, we should glue
3159 ///                        our new SDValue to InFlag SDvalue.
3160 /// \return a new SDvalue of size 64bit.
3161 static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
3162                                 SDValue &Root, SelectionDAG &DAG,
3163                                 const SDLoc &Dl, const X86Subtarget &Subtarget,
3164                                 SDValue *InFlag = nullptr) {
3165   assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
3166   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
3167   assert(VA.getValVT() == MVT::v64i1 &&
3168          "Expecting first location of 64 bit width type");
3169   assert(NextVA.getValVT() == VA.getValVT() &&
3170          "The locations should have the same type");
3171   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
3172          "The values should reside in two registers");
3173 
3174   SDValue Lo, Hi;
3175   SDValue ArgValueLo, ArgValueHi;
3176 
3177   MachineFunction &MF = DAG.getMachineFunction();
3178   const TargetRegisterClass *RC = &X86::GR32RegClass;
3179 
3180   // Read a 32 bit value from the registers.
3181   if (nullptr == InFlag) {
3182     // When no physical register is present,
3183     // create an intermediate virtual register.
3184     Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
3185     ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
3186     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3187     ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
3188   } else {
3189     // When a physical register is available read the value from it and glue
3190     // the reads together.
3191     ArgValueLo =
3192       DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
3193     *InFlag = ArgValueLo.getValue(2);
3194     ArgValueHi =
3195       DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
3196     *InFlag = ArgValueHi.getValue(2);
3197   }
3198 
3199   // Convert the i32 type into v32i1 type.
3200   Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
3201 
3202   // Convert the i32 type into v32i1 type.
3203   Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
3204 
3205   // Concatenate the two values together.
3206   return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
3207 }
3208 
3209 /// The function will lower a register of various sizes (8/16/32/64)
3210 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
3211 /// \returns a DAG node contains the operand after lowering to mask type.
3212 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
3213                                const EVT &ValLoc, const SDLoc &Dl,
3214                                SelectionDAG &DAG) {
3215   SDValue ValReturned = ValArg;
3216 
3217   if (ValVT == MVT::v1i1)
3218     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
3219 
3220   if (ValVT == MVT::v64i1) {
3221     // In 32 bit machine, this case is handled by getv64i1Argument
3222     assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
3223     // In 64 bit machine, There is no need to truncate the value only bitcast
3224   } else {
3225     MVT maskLen;
3226     switch (ValVT.getSimpleVT().SimpleTy) {
3227     case MVT::v8i1:
3228       maskLen = MVT::i8;
3229       break;
3230     case MVT::v16i1:
3231       maskLen = MVT::i16;
3232       break;
3233     case MVT::v32i1:
3234       maskLen = MVT::i32;
3235       break;
3236     default:
3237       llvm_unreachable("Expecting a vector of i1 types");
3238     }
3239 
3240     ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
3241   }
3242   return DAG.getBitcast(ValVT, ValReturned);
3243 }
3244 
3245 /// Lower the result values of a call into the
3246 /// appropriate copies out of appropriate physical registers.
3247 ///
3248 SDValue X86TargetLowering::LowerCallResult(
3249     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3250     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3251     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3252     uint32_t *RegMask) const {
3253 
3254   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3255   // Assign locations to each value returned by this call.
3256   SmallVector<CCValAssign, 16> RVLocs;
3257   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3258                  *DAG.getContext());
3259   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3260 
3261   // Copy all of the result registers out of their specified physreg.
3262   for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
3263        ++I, ++InsIndex) {
3264     CCValAssign &VA = RVLocs[I];
3265     EVT CopyVT = VA.getLocVT();
3266 
3267     // In some calling conventions we need to remove the used registers
3268     // from the register mask.
3269     if (RegMask) {
3270       for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
3271            SubRegs.isValid(); ++SubRegs)
3272         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
3273     }
3274 
3275     // Report an error if there was an attempt to return FP values via XMM
3276     // registers.
3277     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3278       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3279       if (VA.getLocReg() == X86::XMM1)
3280         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3281       else
3282         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3283     } else if (!Subtarget.hasSSE2() &&
3284                X86::FR64XRegClass.contains(VA.getLocReg()) &&
3285                CopyVT == MVT::f64) {
3286       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3287       if (VA.getLocReg() == X86::XMM1)
3288         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3289       else
3290         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3291     }
3292 
3293     // If we prefer to use the value in xmm registers, copy it out as f80 and
3294     // use a truncate to move it from fp stack reg to xmm reg.
3295     bool RoundAfterCopy = false;
3296     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3297         isScalarFPTypeInSSEReg(VA.getValVT())) {
3298       if (!Subtarget.hasX87())
3299         report_fatal_error("X87 register return with X87 disabled");
3300       CopyVT = MVT::f80;
3301       RoundAfterCopy = (CopyVT != VA.getLocVT());
3302     }
3303 
3304     SDValue Val;
3305     if (VA.needsCustom()) {
3306       assert(VA.getValVT() == MVT::v64i1 &&
3307              "Currently the only custom case is when we split v64i1 to 2 regs");
3308       Val =
3309           getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
3310     } else {
3311       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
3312                   .getValue(1);
3313       Val = Chain.getValue(0);
3314       InFlag = Chain.getValue(2);
3315     }
3316 
3317     if (RoundAfterCopy)
3318       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
3319                         // This truncation won't change the value.
3320                         DAG.getIntPtrConstant(1, dl));
3321 
3322     if (VA.isExtInLoc()) {
3323       if (VA.getValVT().isVector() &&
3324           VA.getValVT().getScalarType() == MVT::i1 &&
3325           ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3326            (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3327         // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3328         Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
3329       } else
3330         Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3331     }
3332 
3333     if (VA.getLocInfo() == CCValAssign::BCvt)
3334       Val = DAG.getBitcast(VA.getValVT(), Val);
3335 
3336     InVals.push_back(Val);
3337   }
3338 
3339   return Chain;
3340 }
3341 
3342 //===----------------------------------------------------------------------===//
3343 //                C & StdCall & Fast Calling Convention implementation
3344 //===----------------------------------------------------------------------===//
3345 //  StdCall calling convention seems to be standard for many Windows' API
3346 //  routines and around. It differs from C calling convention just a little:
3347 //  callee should clean up the stack, not caller. Symbols should be also
3348 //  decorated in some fancy way :) It doesn't support any vector arguments.
3349 //  For info on fast calling convention see Fast Calling Convention (tail call)
3350 //  implementation LowerX86_32FastCCCallTo.
3351 
3352 /// Determines whether Args, either a set of outgoing arguments to a call, or a
3353 /// set of incoming args of a call, contains an sret pointer that the callee
3354 /// pops
3355 template <typename T>
3356 static bool hasCalleePopSRet(const SmallVectorImpl<T> &Args,
3357                              const X86Subtarget &Subtarget) {
3358   // Not C++20 (yet), so no concepts available.
3359   static_assert(std::is_same<T, ISD::OutputArg>::value ||
3360                     std::is_same<T, ISD::InputArg>::value,
3361                 "requires ISD::OutputArg or ISD::InputArg");
3362 
3363   // Only 32-bit pops the sret.  It's a 64-bit world these days, so early-out
3364   // for most compilations.
3365   if (!Subtarget.is32Bit())
3366     return false;
3367 
3368   if (Args.empty())
3369     return false;
3370 
3371   // Most calls do not have an sret argument, check the arg next.
3372   const ISD::ArgFlagsTy &Flags = Args[0].Flags;
3373   if (!Flags.isSRet() || Flags.isInReg())
3374     return false;
3375 
3376   // The MSVCabi does not pop the sret.
3377   if (Subtarget.getTargetTriple().isOSMSVCRT())
3378     return false;
3379 
3380   // MCUs don't pop the sret
3381   if (Subtarget.isTargetMCU())
3382     return false;
3383 
3384   // Callee pops argument
3385   return true;
3386 }
3387 
3388 /// Make a copy of an aggregate at address specified by "Src" to address
3389 /// "Dst" with size and alignment information specified by the specific
3390 /// parameter attribute. The copy will be passed as a byval function parameter.
3391 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
3392                                          SDValue Chain, ISD::ArgFlagsTy Flags,
3393                                          SelectionDAG &DAG, const SDLoc &dl) {
3394   SDValue SizeNode = DAG.getIntPtrConstant(Flags.getByValSize(), dl);
3395 
3396   return DAG.getMemcpy(
3397       Chain, dl, Dst, Src, SizeNode, Flags.getNonZeroByValAlign(),
3398       /*isVolatile*/ false, /*AlwaysInline=*/true,
3399       /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
3400 }
3401 
3402 /// Return true if the calling convention is one that we can guarantee TCO for.
3403 static bool canGuaranteeTCO(CallingConv::ID CC) {
3404   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3405           CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
3406           CC == CallingConv::HHVM || CC == CallingConv::Tail ||
3407           CC == CallingConv::SwiftTail);
3408 }
3409 
3410 /// Return true if we might ever do TCO for calls with this calling convention.
3411 static bool mayTailCallThisCC(CallingConv::ID CC) {
3412   switch (CC) {
3413   // C calling conventions:
3414   case CallingConv::C:
3415   case CallingConv::Win64:
3416   case CallingConv::X86_64_SysV:
3417   // Callee pop conventions:
3418   case CallingConv::X86_ThisCall:
3419   case CallingConv::X86_StdCall:
3420   case CallingConv::X86_VectorCall:
3421   case CallingConv::X86_FastCall:
3422   // Swift:
3423   case CallingConv::Swift:
3424     return true;
3425   default:
3426     return canGuaranteeTCO(CC);
3427   }
3428 }
3429 
3430 /// Return true if the function is being made into a tailcall target by
3431 /// changing its ABI.
3432 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
3433   return (GuaranteedTailCallOpt && canGuaranteeTCO(CC)) ||
3434          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
3435 }
3436 
3437 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3438   if (!CI->isTailCall())
3439     return false;
3440 
3441   CallingConv::ID CalleeCC = CI->getCallingConv();
3442   if (!mayTailCallThisCC(CalleeCC))
3443     return false;
3444 
3445   return true;
3446 }
3447 
3448 SDValue
3449 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
3450                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3451                                     const SDLoc &dl, SelectionDAG &DAG,
3452                                     const CCValAssign &VA,
3453                                     MachineFrameInfo &MFI, unsigned i) const {
3454   // Create the nodes corresponding to a load from this parameter slot.
3455   ISD::ArgFlagsTy Flags = Ins[i].Flags;
3456   bool AlwaysUseMutable = shouldGuaranteeTCO(
3457       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
3458   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
3459   EVT ValVT;
3460   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3461 
3462   // If value is passed by pointer we have address passed instead of the value
3463   // itself. No need to extend if the mask value and location share the same
3464   // absolute size.
3465   bool ExtendedInMem =
3466       VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
3467       VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
3468 
3469   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
3470     ValVT = VA.getLocVT();
3471   else
3472     ValVT = VA.getValVT();
3473 
3474   // FIXME: For now, all byval parameter objects are marked mutable. This can be
3475   // changed with more analysis.
3476   // In case of tail call optimization mark all arguments mutable. Since they
3477   // could be overwritten by lowering of arguments in case of a tail call.
3478   if (Flags.isByVal()) {
3479     unsigned Bytes = Flags.getByValSize();
3480     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3481 
3482     // FIXME: For now, all byval parameter objects are marked as aliasing. This
3483     // can be improved with deeper analysis.
3484     int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3485                                    /*isAliased=*/true);
3486     return DAG.getFrameIndex(FI, PtrVT);
3487   }
3488 
3489   EVT ArgVT = Ins[i].ArgVT;
3490 
3491   // If this is a vector that has been split into multiple parts, and the
3492   // scalar size of the parts don't match the vector element size, then we can't
3493   // elide the copy. The parts will have padding between them instead of being
3494   // packed like a vector.
3495   bool ScalarizedAndExtendedVector =
3496       ArgVT.isVector() && !VA.getLocVT().isVector() &&
3497       VA.getLocVT().getSizeInBits() != ArgVT.getScalarSizeInBits();
3498 
3499   // This is an argument in memory. We might be able to perform copy elision.
3500   // If the argument is passed directly in memory without any extension, then we
3501   // can perform copy elision. Large vector types, for example, may be passed
3502   // indirectly by pointer.
3503   if (Flags.isCopyElisionCandidate() &&
3504       VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem &&
3505       !ScalarizedAndExtendedVector) {
3506     SDValue PartAddr;
3507     if (Ins[i].PartOffset == 0) {
3508       // If this is a one-part value or the first part of a multi-part value,
3509       // create a stack object for the entire argument value type and return a
3510       // load from our portion of it. This assumes that if the first part of an
3511       // argument is in memory, the rest will also be in memory.
3512       int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3513                                      /*IsImmutable=*/false);
3514       PartAddr = DAG.getFrameIndex(FI, PtrVT);
3515       return DAG.getLoad(
3516           ValVT, dl, Chain, PartAddr,
3517           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3518     } else {
3519       // This is not the first piece of an argument in memory. See if there is
3520       // already a fixed stack object including this offset. If so, assume it
3521       // was created by the PartOffset == 0 branch above and create a load from
3522       // the appropriate offset into it.
3523       int64_t PartBegin = VA.getLocMemOffset();
3524       int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3525       int FI = MFI.getObjectIndexBegin();
3526       for (; MFI.isFixedObjectIndex(FI); ++FI) {
3527         int64_t ObjBegin = MFI.getObjectOffset(FI);
3528         int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3529         if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3530           break;
3531       }
3532       if (MFI.isFixedObjectIndex(FI)) {
3533         SDValue Addr =
3534             DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3535                         DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3536         return DAG.getLoad(
3537             ValVT, dl, Chain, Addr,
3538             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3539                                               Ins[i].PartOffset));
3540       }
3541     }
3542   }
3543 
3544   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3545                                  VA.getLocMemOffset(), isImmutable);
3546 
3547   // Set SExt or ZExt flag.
3548   if (VA.getLocInfo() == CCValAssign::ZExt) {
3549     MFI.setObjectZExt(FI, true);
3550   } else if (VA.getLocInfo() == CCValAssign::SExt) {
3551     MFI.setObjectSExt(FI, true);
3552   }
3553 
3554   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3555   SDValue Val = DAG.getLoad(
3556       ValVT, dl, Chain, FIN,
3557       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3558   return ExtendedInMem
3559              ? (VA.getValVT().isVector()
3560                     ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3561                     : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3562              : Val;
3563 }
3564 
3565 // FIXME: Get this from tablegen.
3566 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3567                                                 const X86Subtarget &Subtarget) {
3568   assert(Subtarget.is64Bit());
3569 
3570   if (Subtarget.isCallingConvWin64(CallConv)) {
3571     static const MCPhysReg GPR64ArgRegsWin64[] = {
3572       X86::RCX, X86::RDX, X86::R8,  X86::R9
3573     };
3574     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3575   }
3576 
3577   static const MCPhysReg GPR64ArgRegs64Bit[] = {
3578     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3579   };
3580   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3581 }
3582 
3583 // FIXME: Get this from tablegen.
3584 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3585                                                 CallingConv::ID CallConv,
3586                                                 const X86Subtarget &Subtarget) {
3587   assert(Subtarget.is64Bit());
3588   if (Subtarget.isCallingConvWin64(CallConv)) {
3589     // The XMM registers which might contain var arg parameters are shadowed
3590     // in their paired GPR.  So we only need to save the GPR to their home
3591     // slots.
3592     // TODO: __vectorcall will change this.
3593     return None;
3594   }
3595 
3596   bool isSoftFloat = Subtarget.useSoftFloat();
3597   if (isSoftFloat || !Subtarget.hasSSE1())
3598     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3599     // registers.
3600     return None;
3601 
3602   static const MCPhysReg XMMArgRegs64Bit[] = {
3603     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3604     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3605   };
3606   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3607 }
3608 
3609 #ifndef NDEBUG
3610 static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3611   return llvm::is_sorted(
3612       ArgLocs, [](const CCValAssign &A, const CCValAssign &B) -> bool {
3613         return A.getValNo() < B.getValNo();
3614       });
3615 }
3616 #endif
3617 
3618 namespace {
3619 /// This is a helper class for lowering variable arguments parameters.
3620 class VarArgsLoweringHelper {
3621 public:
3622   VarArgsLoweringHelper(X86MachineFunctionInfo *FuncInfo, const SDLoc &Loc,
3623                         SelectionDAG &DAG, const X86Subtarget &Subtarget,
3624                         CallingConv::ID CallConv, CCState &CCInfo)
3625       : FuncInfo(FuncInfo), DL(Loc), DAG(DAG), Subtarget(Subtarget),
3626         TheMachineFunction(DAG.getMachineFunction()),
3627         TheFunction(TheMachineFunction.getFunction()),
3628         FrameInfo(TheMachineFunction.getFrameInfo()),
3629         FrameLowering(*Subtarget.getFrameLowering()),
3630         TargLowering(DAG.getTargetLoweringInfo()), CallConv(CallConv),
3631         CCInfo(CCInfo) {}
3632 
3633   // Lower variable arguments parameters.
3634   void lowerVarArgsParameters(SDValue &Chain, unsigned StackSize);
3635 
3636 private:
3637   void createVarArgAreaAndStoreRegisters(SDValue &Chain, unsigned StackSize);
3638 
3639   void forwardMustTailParameters(SDValue &Chain);
3640 
3641   bool is64Bit() const { return Subtarget.is64Bit(); }
3642   bool isWin64() const { return Subtarget.isCallingConvWin64(CallConv); }
3643 
3644   X86MachineFunctionInfo *FuncInfo;
3645   const SDLoc &DL;
3646   SelectionDAG &DAG;
3647   const X86Subtarget &Subtarget;
3648   MachineFunction &TheMachineFunction;
3649   const Function &TheFunction;
3650   MachineFrameInfo &FrameInfo;
3651   const TargetFrameLowering &FrameLowering;
3652   const TargetLowering &TargLowering;
3653   CallingConv::ID CallConv;
3654   CCState &CCInfo;
3655 };
3656 } // namespace
3657 
3658 void VarArgsLoweringHelper::createVarArgAreaAndStoreRegisters(
3659     SDValue &Chain, unsigned StackSize) {
3660   // If the function takes variable number of arguments, make a frame index for
3661   // the start of the first vararg value... for expansion of llvm.va_start. We
3662   // can skip this if there are no va_start calls.
3663   if (is64Bit() || (CallConv != CallingConv::X86_FastCall &&
3664                     CallConv != CallingConv::X86_ThisCall)) {
3665     FuncInfo->setVarArgsFrameIndex(
3666         FrameInfo.CreateFixedObject(1, StackSize, true));
3667   }
3668 
3669   // 64-bit calling conventions support varargs and register parameters, so we
3670   // have to do extra work to spill them in the prologue.
3671   if (is64Bit()) {
3672     // Find the first unallocated argument registers.
3673     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3674     ArrayRef<MCPhysReg> ArgXMMs =
3675         get64BitArgumentXMMs(TheMachineFunction, CallConv, Subtarget);
3676     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3677     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3678 
3679     assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3680            "SSE register cannot be used when SSE is disabled!");
3681 
3682     if (isWin64()) {
3683       // Get to the caller-allocated home save location.  Add 8 to account
3684       // for the return address.
3685       int HomeOffset = FrameLowering.getOffsetOfLocalArea() + 8;
3686       FuncInfo->setRegSaveFrameIndex(
3687           FrameInfo.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3688       // Fixup to set vararg frame on shadow area (4 x i64).
3689       if (NumIntRegs < 4)
3690         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3691     } else {
3692       // For X86-64, if there are vararg parameters that are passed via
3693       // registers, then we must store them to their spots on the stack so
3694       // they may be loaded by dereferencing the result of va_next.
3695       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3696       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3697       FuncInfo->setRegSaveFrameIndex(FrameInfo.CreateStackObject(
3698           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, Align(16), false));
3699     }
3700 
3701     SmallVector<SDValue, 6>
3702         LiveGPRs; // list of SDValue for GPR registers keeping live input value
3703     SmallVector<SDValue, 8> LiveXMMRegs; // list of SDValue for XMM registers
3704                                          // keeping live input value
3705     SDValue ALVal; // if applicable keeps SDValue for %al register
3706 
3707     // Gather all the live in physical registers.
3708     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3709       Register GPR = TheMachineFunction.addLiveIn(Reg, &X86::GR64RegClass);
3710       LiveGPRs.push_back(DAG.getCopyFromReg(Chain, DL, GPR, MVT::i64));
3711     }
3712     const auto &AvailableXmms = ArgXMMs.slice(NumXMMRegs);
3713     if (!AvailableXmms.empty()) {
3714       Register AL = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3715       ALVal = DAG.getCopyFromReg(Chain, DL, AL, MVT::i8);
3716       for (MCPhysReg Reg : AvailableXmms) {
3717         // FastRegisterAllocator spills virtual registers at basic
3718         // block boundary. That leads to usages of xmm registers
3719         // outside of check for %al. Pass physical registers to
3720         // VASTART_SAVE_XMM_REGS to avoid unneccessary spilling.
3721         TheMachineFunction.getRegInfo().addLiveIn(Reg);
3722         LiveXMMRegs.push_back(DAG.getRegister(Reg, MVT::v4f32));
3723       }
3724     }
3725 
3726     // Store the integer parameter registers.
3727     SmallVector<SDValue, 8> MemOps;
3728     SDValue RSFIN =
3729         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3730                           TargLowering.getPointerTy(DAG.getDataLayout()));
3731     unsigned Offset = FuncInfo->getVarArgsGPOffset();
3732     for (SDValue Val : LiveGPRs) {
3733       SDValue FIN = DAG.getNode(ISD::ADD, DL,
3734                                 TargLowering.getPointerTy(DAG.getDataLayout()),
3735                                 RSFIN, DAG.getIntPtrConstant(Offset, DL));
3736       SDValue Store =
3737           DAG.getStore(Val.getValue(1), DL, Val, FIN,
3738                        MachinePointerInfo::getFixedStack(
3739                            DAG.getMachineFunction(),
3740                            FuncInfo->getRegSaveFrameIndex(), Offset));
3741       MemOps.push_back(Store);
3742       Offset += 8;
3743     }
3744 
3745     // Now store the XMM (fp + vector) parameter registers.
3746     if (!LiveXMMRegs.empty()) {
3747       SmallVector<SDValue, 12> SaveXMMOps;
3748       SaveXMMOps.push_back(Chain);
3749       SaveXMMOps.push_back(ALVal);
3750       SaveXMMOps.push_back(RSFIN);
3751       SaveXMMOps.push_back(
3752           DAG.getTargetConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32));
3753       llvm::append_range(SaveXMMOps, LiveXMMRegs);
3754       MachineMemOperand *StoreMMO =
3755           DAG.getMachineFunction().getMachineMemOperand(
3756               MachinePointerInfo::getFixedStack(
3757                   DAG.getMachineFunction(), FuncInfo->getRegSaveFrameIndex(),
3758                   Offset),
3759               MachineMemOperand::MOStore, 128, Align(16));
3760       MemOps.push_back(DAG.getMemIntrinsicNode(X86ISD::VASTART_SAVE_XMM_REGS,
3761                                                DL, DAG.getVTList(MVT::Other),
3762                                                SaveXMMOps, MVT::i8, StoreMMO));
3763     }
3764 
3765     if (!MemOps.empty())
3766       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3767   }
3768 }
3769 
3770 void VarArgsLoweringHelper::forwardMustTailParameters(SDValue &Chain) {
3771   // Find the largest legal vector type.
3772   MVT VecVT = MVT::Other;
3773   // FIXME: Only some x86_32 calling conventions support AVX512.
3774   if (Subtarget.useAVX512Regs() &&
3775       (is64Bit() || (CallConv == CallingConv::X86_VectorCall ||
3776                      CallConv == CallingConv::Intel_OCL_BI)))
3777     VecVT = MVT::v16f32;
3778   else if (Subtarget.hasAVX())
3779     VecVT = MVT::v8f32;
3780   else if (Subtarget.hasSSE2())
3781     VecVT = MVT::v4f32;
3782 
3783   // We forward some GPRs and some vector types.
3784   SmallVector<MVT, 2> RegParmTypes;
3785   MVT IntVT = is64Bit() ? MVT::i64 : MVT::i32;
3786   RegParmTypes.push_back(IntVT);
3787   if (VecVT != MVT::Other)
3788     RegParmTypes.push_back(VecVT);
3789 
3790   // Compute the set of forwarded registers. The rest are scratch.
3791   SmallVectorImpl<ForwardedRegister> &Forwards =
3792       FuncInfo->getForwardedMustTailRegParms();
3793   CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3794 
3795   // Forward AL for SysV x86_64 targets, since it is used for varargs.
3796   if (is64Bit() && !isWin64() && !CCInfo.isAllocated(X86::AL)) {
3797     Register ALVReg = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3798     Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3799   }
3800 
3801   // Copy all forwards from physical to virtual registers.
3802   for (ForwardedRegister &FR : Forwards) {
3803     // FIXME: Can we use a less constrained schedule?
3804     SDValue RegVal = DAG.getCopyFromReg(Chain, DL, FR.VReg, FR.VT);
3805     FR.VReg = TheMachineFunction.getRegInfo().createVirtualRegister(
3806         TargLowering.getRegClassFor(FR.VT));
3807     Chain = DAG.getCopyToReg(Chain, DL, FR.VReg, RegVal);
3808   }
3809 }
3810 
3811 void VarArgsLoweringHelper::lowerVarArgsParameters(SDValue &Chain,
3812                                                    unsigned StackSize) {
3813   // Set FrameIndex to the 0xAAAAAAA value to mark unset state.
3814   // If necessary, it would be set into the correct value later.
3815   FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3816   FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3817 
3818   if (FrameInfo.hasVAStart())
3819     createVarArgAreaAndStoreRegisters(Chain, StackSize);
3820 
3821   if (FrameInfo.hasMustTailInVarArgFunc())
3822     forwardMustTailParameters(Chain);
3823 }
3824 
3825 SDValue X86TargetLowering::LowerFormalArguments(
3826     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3827     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3828     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3829   MachineFunction &MF = DAG.getMachineFunction();
3830   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3831 
3832   const Function &F = MF.getFunction();
3833   if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3834       F.getName() == "main")
3835     FuncInfo->setForceFramePointer(true);
3836 
3837   MachineFrameInfo &MFI = MF.getFrameInfo();
3838   bool Is64Bit = Subtarget.is64Bit();
3839   bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3840 
3841   assert(
3842       !(IsVarArg && canGuaranteeTCO(CallConv)) &&
3843       "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3844 
3845   // Assign locations to all of the incoming arguments.
3846   SmallVector<CCValAssign, 16> ArgLocs;
3847   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3848 
3849   // Allocate shadow area for Win64.
3850   if (IsWin64)
3851     CCInfo.AllocateStack(32, Align(8));
3852 
3853   CCInfo.AnalyzeArguments(Ins, CC_X86);
3854 
3855   // In vectorcall calling convention a second pass is required for the HVA
3856   // types.
3857   if (CallingConv::X86_VectorCall == CallConv) {
3858     CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3859   }
3860 
3861   // The next loop assumes that the locations are in the same order of the
3862   // input arguments.
3863   assert(isSortedByValueNo(ArgLocs) &&
3864          "Argument Location list must be sorted before lowering");
3865 
3866   SDValue ArgValue;
3867   for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3868        ++I, ++InsIndex) {
3869     assert(InsIndex < Ins.size() && "Invalid Ins index");
3870     CCValAssign &VA = ArgLocs[I];
3871 
3872     if (VA.isRegLoc()) {
3873       EVT RegVT = VA.getLocVT();
3874       if (VA.needsCustom()) {
3875         assert(
3876             VA.getValVT() == MVT::v64i1 &&
3877             "Currently the only custom case is when we split v64i1 to 2 regs");
3878 
3879         // v64i1 values, in regcall calling convention, that are
3880         // compiled to 32 bit arch, are split up into two registers.
3881         ArgValue =
3882             getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3883       } else {
3884         const TargetRegisterClass *RC;
3885         if (RegVT == MVT::i8)
3886           RC = &X86::GR8RegClass;
3887         else if (RegVT == MVT::i16)
3888           RC = &X86::GR16RegClass;
3889         else if (RegVT == MVT::i32)
3890           RC = &X86::GR32RegClass;
3891         else if (Is64Bit && RegVT == MVT::i64)
3892           RC = &X86::GR64RegClass;
3893         else if (RegVT == MVT::f16)
3894           RC = &X86::FR16XRegClass;
3895         else if (RegVT == MVT::f32)
3896           RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3897         else if (RegVT == MVT::f64)
3898           RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3899         else if (RegVT == MVT::f80)
3900           RC = &X86::RFP80RegClass;
3901         else if (RegVT == MVT::f128)
3902           RC = &X86::VR128RegClass;
3903         else if (RegVT.is512BitVector())
3904           RC = &X86::VR512RegClass;
3905         else if (RegVT.is256BitVector())
3906           RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3907         else if (RegVT.is128BitVector())
3908           RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3909         else if (RegVT == MVT::x86mmx)
3910           RC = &X86::VR64RegClass;
3911         else if (RegVT == MVT::v1i1)
3912           RC = &X86::VK1RegClass;
3913         else if (RegVT == MVT::v8i1)
3914           RC = &X86::VK8RegClass;
3915         else if (RegVT == MVT::v16i1)
3916           RC = &X86::VK16RegClass;
3917         else if (RegVT == MVT::v32i1)
3918           RC = &X86::VK32RegClass;
3919         else if (RegVT == MVT::v64i1)
3920           RC = &X86::VK64RegClass;
3921         else
3922           llvm_unreachable("Unknown argument type!");
3923 
3924         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
3925         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3926       }
3927 
3928       // If this is an 8 or 16-bit value, it is really passed promoted to 32
3929       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
3930       // right size.
3931       if (VA.getLocInfo() == CCValAssign::SExt)
3932         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3933                                DAG.getValueType(VA.getValVT()));
3934       else if (VA.getLocInfo() == CCValAssign::ZExt)
3935         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3936                                DAG.getValueType(VA.getValVT()));
3937       else if (VA.getLocInfo() == CCValAssign::BCvt)
3938         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3939 
3940       if (VA.isExtInLoc()) {
3941         // Handle MMX values passed in XMM regs.
3942         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3943           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3944         else if (VA.getValVT().isVector() &&
3945                  VA.getValVT().getScalarType() == MVT::i1 &&
3946                  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3947                   (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3948           // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3949           ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3950         } else
3951           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3952       }
3953     } else {
3954       assert(VA.isMemLoc());
3955       ArgValue =
3956           LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3957     }
3958 
3959     // If value is passed via pointer - do a load.
3960     if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3961       ArgValue =
3962           DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3963 
3964     InVals.push_back(ArgValue);
3965   }
3966 
3967   for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3968     if (Ins[I].Flags.isSwiftAsync()) {
3969       auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
3970       if (Subtarget.is64Bit())
3971         X86FI->setHasSwiftAsyncContext(true);
3972       else {
3973         int FI = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
3974         X86FI->setSwiftAsyncContextFrameIdx(FI);
3975         SDValue St = DAG.getStore(DAG.getEntryNode(), dl, InVals[I],
3976                                   DAG.getFrameIndex(FI, MVT::i32),
3977                                   MachinePointerInfo::getFixedStack(MF, FI));
3978         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, St, Chain);
3979       }
3980     }
3981 
3982     // Swift calling convention does not require we copy the sret argument
3983     // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3984     if (CallConv == CallingConv::Swift || CallConv == CallingConv::SwiftTail)
3985       continue;
3986 
3987     // All x86 ABIs require that for returning structs by value we copy the
3988     // sret argument into %rax/%eax (depending on ABI) for the return. Save
3989     // the argument into a virtual register so that we can access it from the
3990     // return points.
3991     if (Ins[I].Flags.isSRet()) {
3992       assert(!FuncInfo->getSRetReturnReg() &&
3993              "SRet return has already been set");
3994       MVT PtrTy = getPointerTy(DAG.getDataLayout());
3995       Register Reg =
3996           MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3997       FuncInfo->setSRetReturnReg(Reg);
3998       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3999       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
4000       break;
4001     }
4002   }
4003 
4004   unsigned StackSize = CCInfo.getNextStackOffset();
4005   // Align stack specially for tail calls.
4006   if (shouldGuaranteeTCO(CallConv,
4007                          MF.getTarget().Options.GuaranteedTailCallOpt))
4008     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
4009 
4010   if (IsVarArg)
4011     VarArgsLoweringHelper(FuncInfo, dl, DAG, Subtarget, CallConv, CCInfo)
4012         .lowerVarArgsParameters(Chain, StackSize);
4013 
4014   // Some CCs need callee pop.
4015   if (X86::isCalleePop(CallConv, Is64Bit, IsVarArg,
4016                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
4017     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
4018   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
4019     // X86 interrupts must pop the error code (and the alignment padding) if
4020     // present.
4021     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
4022   } else {
4023     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
4024     // If this is an sret function, the return should pop the hidden pointer.
4025     if (!canGuaranteeTCO(CallConv) && hasCalleePopSRet(Ins, Subtarget))
4026       FuncInfo->setBytesToPopOnReturn(4);
4027   }
4028 
4029   if (!Is64Bit) {
4030     // RegSaveFrameIndex is X86-64 only.
4031     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
4032   }
4033 
4034   FuncInfo->setArgumentStackSize(StackSize);
4035 
4036   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
4037     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
4038     if (Personality == EHPersonality::CoreCLR) {
4039       assert(Is64Bit);
4040       // TODO: Add a mechanism to frame lowering that will allow us to indicate
4041       // that we'd prefer this slot be allocated towards the bottom of the frame
4042       // (i.e. near the stack pointer after allocating the frame).  Every
4043       // funclet needs a copy of this slot in its (mostly empty) frame, and the
4044       // offset from the bottom of this and each funclet's frame must be the
4045       // same, so the size of funclets' (mostly empty) frames is dictated by
4046       // how far this slot is from the bottom (since they allocate just enough
4047       // space to accommodate holding this slot at the correct offset).
4048       int PSPSymFI = MFI.CreateStackObject(8, Align(8), /*isSpillSlot=*/false);
4049       EHInfo->PSPSymFrameIdx = PSPSymFI;
4050     }
4051   }
4052 
4053   if (CallConv == CallingConv::X86_RegCall ||
4054       F.hasFnAttribute("no_caller_saved_registers")) {
4055     MachineRegisterInfo &MRI = MF.getRegInfo();
4056     for (std::pair<Register, Register> Pair : MRI.liveins())
4057       MRI.disableCalleeSavedRegister(Pair.first);
4058   }
4059 
4060   return Chain;
4061 }
4062 
4063 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
4064                                             SDValue Arg, const SDLoc &dl,
4065                                             SelectionDAG &DAG,
4066                                             const CCValAssign &VA,
4067                                             ISD::ArgFlagsTy Flags,
4068                                             bool isByVal) const {
4069   unsigned LocMemOffset = VA.getLocMemOffset();
4070   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4071   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4072                        StackPtr, PtrOff);
4073   if (isByVal)
4074     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
4075 
4076   return DAG.getStore(
4077       Chain, dl, Arg, PtrOff,
4078       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
4079 }
4080 
4081 /// Emit a load of return address if tail call
4082 /// optimization is performed and it is required.
4083 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
4084     SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
4085     bool Is64Bit, int FPDiff, const SDLoc &dl) const {
4086   // Adjust the Return address stack slot.
4087   EVT VT = getPointerTy(DAG.getDataLayout());
4088   OutRetAddr = getReturnAddressFrameIndex(DAG);
4089 
4090   // Load the "old" Return address.
4091   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
4092   return SDValue(OutRetAddr.getNode(), 1);
4093 }
4094 
4095 /// Emit a store of the return address if tail call
4096 /// optimization is performed and it is required (FPDiff!=0).
4097 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
4098                                         SDValue Chain, SDValue RetAddrFrIdx,
4099                                         EVT PtrVT, unsigned SlotSize,
4100                                         int FPDiff, const SDLoc &dl) {
4101   // Store the return address to the appropriate stack slot.
4102   if (!FPDiff) return Chain;
4103   // Calculate the new stack slot for the return address.
4104   int NewReturnAddrFI =
4105     MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
4106                                          false);
4107   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
4108   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
4109                        MachinePointerInfo::getFixedStack(
4110                            DAG.getMachineFunction(), NewReturnAddrFI));
4111   return Chain;
4112 }
4113 
4114 /// Returns a vector_shuffle mask for an movs{s|d}, movd
4115 /// operation of specified width.
4116 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
4117                        SDValue V2) {
4118   unsigned NumElems = VT.getVectorNumElements();
4119   SmallVector<int, 8> Mask;
4120   Mask.push_back(NumElems);
4121   for (unsigned i = 1; i != NumElems; ++i)
4122     Mask.push_back(i);
4123   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
4124 }
4125 
4126 SDValue
4127 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4128                              SmallVectorImpl<SDValue> &InVals) const {
4129   SelectionDAG &DAG                     = CLI.DAG;
4130   SDLoc &dl                             = CLI.DL;
4131   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4132   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4133   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4134   SDValue Chain                         = CLI.Chain;
4135   SDValue Callee                        = CLI.Callee;
4136   CallingConv::ID CallConv              = CLI.CallConv;
4137   bool &isTailCall                      = CLI.IsTailCall;
4138   bool isVarArg                         = CLI.IsVarArg;
4139   const auto *CB                        = CLI.CB;
4140 
4141   MachineFunction &MF = DAG.getMachineFunction();
4142   bool Is64Bit        = Subtarget.is64Bit();
4143   bool IsWin64        = Subtarget.isCallingConvWin64(CallConv);
4144   bool IsSibcall      = false;
4145   bool IsGuaranteeTCO = MF.getTarget().Options.GuaranteedTailCallOpt ||
4146       CallConv == CallingConv::Tail || CallConv == CallingConv::SwiftTail;
4147   bool IsCalleePopSRet = !IsGuaranteeTCO && hasCalleePopSRet(Outs, Subtarget);
4148   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
4149   bool HasNCSR = (CB && isa<CallInst>(CB) &&
4150                   CB->hasFnAttr("no_caller_saved_registers"));
4151   bool HasNoCfCheck = (CB && CB->doesNoCfCheck());
4152   bool IsIndirectCall = (CB && isa<CallInst>(CB) && CB->isIndirectCall());
4153   const Module *M = MF.getMMI().getModule();
4154   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
4155 
4156   MachineFunction::CallSiteInfo CSInfo;
4157   if (CallConv == CallingConv::X86_INTR)
4158     report_fatal_error("X86 interrupts may not be called directly");
4159 
4160   bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
4161   if (Subtarget.isPICStyleGOT() && !IsGuaranteeTCO && !IsMustTail) {
4162     // If we are using a GOT, disable tail calls to external symbols with
4163     // default visibility. Tail calling such a symbol requires using a GOT
4164     // relocation, which forces early binding of the symbol. This breaks code
4165     // that require lazy function symbol resolution. Using musttail or
4166     // GuaranteedTailCallOpt will override this.
4167     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4168     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
4169                G->getGlobal()->hasDefaultVisibility()))
4170       isTailCall = false;
4171   }
4172 
4173   if (isTailCall && !IsMustTail) {
4174     // Check if it's really possible to do a tail call.
4175     isTailCall = IsEligibleForTailCallOptimization(
4176         Callee, CallConv, IsCalleePopSRet, isVarArg, CLI.RetTy, Outs, OutVals,
4177         Ins, DAG);
4178 
4179     // Sibcalls are automatically detected tailcalls which do not require
4180     // ABI changes.
4181     if (!IsGuaranteeTCO && isTailCall)
4182       IsSibcall = true;
4183 
4184     if (isTailCall)
4185       ++NumTailCalls;
4186   }
4187 
4188   if (IsMustTail && !isTailCall)
4189     report_fatal_error("failed to perform tail call elimination on a call "
4190                        "site marked musttail");
4191 
4192   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
4193          "Var args not supported with calling convention fastcc, ghc or hipe");
4194 
4195   // Analyze operands of the call, assigning locations to each operand.
4196   SmallVector<CCValAssign, 16> ArgLocs;
4197   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4198 
4199   // Allocate shadow area for Win64.
4200   if (IsWin64)
4201     CCInfo.AllocateStack(32, Align(8));
4202 
4203   CCInfo.AnalyzeArguments(Outs, CC_X86);
4204 
4205   // In vectorcall calling convention a second pass is required for the HVA
4206   // types.
4207   if (CallingConv::X86_VectorCall == CallConv) {
4208     CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
4209   }
4210 
4211   // Get a count of how many bytes are to be pushed on the stack.
4212   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
4213   if (IsSibcall)
4214     // This is a sibcall. The memory operands are available in caller's
4215     // own caller's stack.
4216     NumBytes = 0;
4217   else if (IsGuaranteeTCO && canGuaranteeTCO(CallConv))
4218     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
4219 
4220   int FPDiff = 0;
4221   if (isTailCall &&
4222       shouldGuaranteeTCO(CallConv,
4223                          MF.getTarget().Options.GuaranteedTailCallOpt)) {
4224     // Lower arguments at fp - stackoffset + fpdiff.
4225     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
4226 
4227     FPDiff = NumBytesCallerPushed - NumBytes;
4228 
4229     // Set the delta of movement of the returnaddr stackslot.
4230     // But only set if delta is greater than previous delta.
4231     if (FPDiff < X86Info->getTCReturnAddrDelta())
4232       X86Info->setTCReturnAddrDelta(FPDiff);
4233   }
4234 
4235   unsigned NumBytesToPush = NumBytes;
4236   unsigned NumBytesToPop = NumBytes;
4237 
4238   // If we have an inalloca argument, all stack space has already been allocated
4239   // for us and be right at the top of the stack.  We don't support multiple
4240   // arguments passed in memory when using inalloca.
4241   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
4242     NumBytesToPush = 0;
4243     if (!ArgLocs.back().isMemLoc())
4244       report_fatal_error("cannot use inalloca attribute on a register "
4245                          "parameter");
4246     if (ArgLocs.back().getLocMemOffset() != 0)
4247       report_fatal_error("any parameter with the inalloca attribute must be "
4248                          "the only memory argument");
4249   } else if (CLI.IsPreallocated) {
4250     assert(ArgLocs.back().isMemLoc() &&
4251            "cannot use preallocated attribute on a register "
4252            "parameter");
4253     SmallVector<size_t, 4> PreallocatedOffsets;
4254     for (size_t i = 0; i < CLI.OutVals.size(); ++i) {
4255       if (CLI.CB->paramHasAttr(i, Attribute::Preallocated)) {
4256         PreallocatedOffsets.push_back(ArgLocs[i].getLocMemOffset());
4257       }
4258     }
4259     auto *MFI = DAG.getMachineFunction().getInfo<X86MachineFunctionInfo>();
4260     size_t PreallocatedId = MFI->getPreallocatedIdForCallSite(CLI.CB);
4261     MFI->setPreallocatedStackSize(PreallocatedId, NumBytes);
4262     MFI->setPreallocatedArgOffsets(PreallocatedId, PreallocatedOffsets);
4263     NumBytesToPush = 0;
4264   }
4265 
4266   if (!IsSibcall && !IsMustTail)
4267     Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
4268                                  NumBytes - NumBytesToPush, dl);
4269 
4270   SDValue RetAddrFrIdx;
4271   // Load return address for tail calls.
4272   if (isTailCall && FPDiff)
4273     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
4274                                     Is64Bit, FPDiff, dl);
4275 
4276   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
4277   SmallVector<SDValue, 8> MemOpChains;
4278   SDValue StackPtr;
4279 
4280   // The next loop assumes that the locations are in the same order of the
4281   // input arguments.
4282   assert(isSortedByValueNo(ArgLocs) &&
4283          "Argument Location list must be sorted before lowering");
4284 
4285   // Walk the register/memloc assignments, inserting copies/loads.  In the case
4286   // of tail call optimization arguments are handle later.
4287   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4288   for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
4289        ++I, ++OutIndex) {
4290     assert(OutIndex < Outs.size() && "Invalid Out index");
4291     // Skip inalloca/preallocated arguments, they have already been written.
4292     ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
4293     if (Flags.isInAlloca() || Flags.isPreallocated())
4294       continue;
4295 
4296     CCValAssign &VA = ArgLocs[I];
4297     EVT RegVT = VA.getLocVT();
4298     SDValue Arg = OutVals[OutIndex];
4299     bool isByVal = Flags.isByVal();
4300 
4301     // Promote the value if needed.
4302     switch (VA.getLocInfo()) {
4303     default: llvm_unreachable("Unknown loc info!");
4304     case CCValAssign::Full: break;
4305     case CCValAssign::SExt:
4306       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
4307       break;
4308     case CCValAssign::ZExt:
4309       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
4310       break;
4311     case CCValAssign::AExt:
4312       if (Arg.getValueType().isVector() &&
4313           Arg.getValueType().getVectorElementType() == MVT::i1)
4314         Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
4315       else if (RegVT.is128BitVector()) {
4316         // Special case: passing MMX values in XMM registers.
4317         Arg = DAG.getBitcast(MVT::i64, Arg);
4318         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
4319         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
4320       } else
4321         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
4322       break;
4323     case CCValAssign::BCvt:
4324       Arg = DAG.getBitcast(RegVT, Arg);
4325       break;
4326     case CCValAssign::Indirect: {
4327       if (isByVal) {
4328         // Memcpy the argument to a temporary stack slot to prevent
4329         // the caller from seeing any modifications the callee may make
4330         // as guaranteed by the `byval` attribute.
4331         int FrameIdx = MF.getFrameInfo().CreateStackObject(
4332             Flags.getByValSize(),
4333             std::max(Align(16), Flags.getNonZeroByValAlign()), false);
4334         SDValue StackSlot =
4335             DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
4336         Chain =
4337             CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
4338         // From now on treat this as a regular pointer
4339         Arg = StackSlot;
4340         isByVal = false;
4341       } else {
4342         // Store the argument.
4343         SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
4344         int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
4345         Chain = DAG.getStore(
4346             Chain, dl, Arg, SpillSlot,
4347             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4348         Arg = SpillSlot;
4349       }
4350       break;
4351     }
4352     }
4353 
4354     if (VA.needsCustom()) {
4355       assert(VA.getValVT() == MVT::v64i1 &&
4356              "Currently the only custom case is when we split v64i1 to 2 regs");
4357       // Split v64i1 value into two registers
4358       Passv64i1ArgInRegs(dl, DAG, Arg, RegsToPass, VA, ArgLocs[++I], Subtarget);
4359     } else if (VA.isRegLoc()) {
4360       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4361       const TargetOptions &Options = DAG.getTarget().Options;
4362       if (Options.EmitCallSiteInfo)
4363         CSInfo.emplace_back(VA.getLocReg(), I);
4364       if (isVarArg && IsWin64) {
4365         // Win64 ABI requires argument XMM reg to be copied to the corresponding
4366         // shadow reg if callee is a varargs function.
4367         Register ShadowReg;
4368         switch (VA.getLocReg()) {
4369         case X86::XMM0: ShadowReg = X86::RCX; break;
4370         case X86::XMM1: ShadowReg = X86::RDX; break;
4371         case X86::XMM2: ShadowReg = X86::R8; break;
4372         case X86::XMM3: ShadowReg = X86::R9; break;
4373         }
4374         if (ShadowReg)
4375           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
4376       }
4377     } else if (!IsSibcall && (!isTailCall || isByVal)) {
4378       assert(VA.isMemLoc());
4379       if (!StackPtr.getNode())
4380         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4381                                       getPointerTy(DAG.getDataLayout()));
4382       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
4383                                              dl, DAG, VA, Flags, isByVal));
4384     }
4385   }
4386 
4387   if (!MemOpChains.empty())
4388     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4389 
4390   if (Subtarget.isPICStyleGOT()) {
4391     // ELF / PIC requires GOT in the EBX register before function calls via PLT
4392     // GOT pointer (except regcall).
4393     if (!isTailCall) {
4394       // Indirect call with RegCall calling convertion may use up all the
4395       // general registers, so it is not suitable to bind EBX reister for
4396       // GOT address, just let register allocator handle it.
4397       if (CallConv != CallingConv::X86_RegCall)
4398         RegsToPass.push_back(std::make_pair(
4399           Register(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
4400                                           getPointerTy(DAG.getDataLayout()))));
4401     } else {
4402       // If we are tail calling and generating PIC/GOT style code load the
4403       // address of the callee into ECX. The value in ecx is used as target of
4404       // the tail jump. This is done to circumvent the ebx/callee-saved problem
4405       // for tail calls on PIC/GOT architectures. Normally we would just put the
4406       // address of GOT into ebx and then call target@PLT. But for tail calls
4407       // ebx would be restored (since ebx is callee saved) before jumping to the
4408       // target@PLT.
4409 
4410       // Note: The actual moving to ECX is done further down.
4411       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4412       if (G && !G->getGlobal()->hasLocalLinkage() &&
4413           G->getGlobal()->hasDefaultVisibility())
4414         Callee = LowerGlobalAddress(Callee, DAG);
4415       else if (isa<ExternalSymbolSDNode>(Callee))
4416         Callee = LowerExternalSymbol(Callee, DAG);
4417     }
4418   }
4419 
4420   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail &&
4421       (Subtarget.hasSSE1() || !M->getModuleFlag("SkipRaxSetup"))) {
4422     // From AMD64 ABI document:
4423     // For calls that may call functions that use varargs or stdargs
4424     // (prototype-less calls or calls to functions containing ellipsis (...) in
4425     // the declaration) %al is used as hidden argument to specify the number
4426     // of SSE registers used. The contents of %al do not need to match exactly
4427     // the number of registers, but must be an ubound on the number of SSE
4428     // registers used and is in the range 0 - 8 inclusive.
4429 
4430     // Count the number of XMM registers allocated.
4431     static const MCPhysReg XMMArgRegs[] = {
4432       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4433       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
4434     };
4435     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
4436     assert((Subtarget.hasSSE1() || !NumXMMRegs)
4437            && "SSE registers cannot be used when SSE is disabled");
4438     RegsToPass.push_back(std::make_pair(Register(X86::AL),
4439                                         DAG.getConstant(NumXMMRegs, dl,
4440                                                         MVT::i8)));
4441   }
4442 
4443   if (isVarArg && IsMustTail) {
4444     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
4445     for (const auto &F : Forwards) {
4446       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
4447       RegsToPass.push_back(std::make_pair(F.PReg, Val));
4448     }
4449   }
4450 
4451   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
4452   // don't need this because the eligibility check rejects calls that require
4453   // shuffling arguments passed in memory.
4454   if (!IsSibcall && isTailCall) {
4455     // Force all the incoming stack arguments to be loaded from the stack
4456     // before any new outgoing arguments are stored to the stack, because the
4457     // outgoing stack slots may alias the incoming argument stack slots, and
4458     // the alias isn't otherwise explicit. This is slightly more conservative
4459     // than necessary, because it means that each store effectively depends
4460     // on every argument instead of just those arguments it would clobber.
4461     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
4462 
4463     SmallVector<SDValue, 8> MemOpChains2;
4464     SDValue FIN;
4465     int FI = 0;
4466     for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
4467          ++I, ++OutsIndex) {
4468       CCValAssign &VA = ArgLocs[I];
4469 
4470       if (VA.isRegLoc()) {
4471         if (VA.needsCustom()) {
4472           assert((CallConv == CallingConv::X86_RegCall) &&
4473                  "Expecting custom case only in regcall calling convention");
4474           // This means that we are in special case where one argument was
4475           // passed through two register locations - Skip the next location
4476           ++I;
4477         }
4478 
4479         continue;
4480       }
4481 
4482       assert(VA.isMemLoc());
4483       SDValue Arg = OutVals[OutsIndex];
4484       ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
4485       // Skip inalloca/preallocated arguments.  They don't require any work.
4486       if (Flags.isInAlloca() || Flags.isPreallocated())
4487         continue;
4488       // Create frame index.
4489       int32_t Offset = VA.getLocMemOffset()+FPDiff;
4490       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
4491       FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4492       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4493 
4494       if (Flags.isByVal()) {
4495         // Copy relative to framepointer.
4496         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
4497         if (!StackPtr.getNode())
4498           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4499                                         getPointerTy(DAG.getDataLayout()));
4500         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4501                              StackPtr, Source);
4502 
4503         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
4504                                                          ArgChain,
4505                                                          Flags, DAG, dl));
4506       } else {
4507         // Store relative to framepointer.
4508         MemOpChains2.push_back(DAG.getStore(
4509             ArgChain, dl, Arg, FIN,
4510             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4511       }
4512     }
4513 
4514     if (!MemOpChains2.empty())
4515       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4516 
4517     // Store the return address to the appropriate stack slot.
4518     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
4519                                      getPointerTy(DAG.getDataLayout()),
4520                                      RegInfo->getSlotSize(), FPDiff, dl);
4521   }
4522 
4523   // Build a sequence of copy-to-reg nodes chained together with token chain
4524   // and flag operands which copy the outgoing args into registers.
4525   SDValue InFlag;
4526   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4527     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4528                              RegsToPass[i].second, InFlag);
4529     InFlag = Chain.getValue(1);
4530   }
4531 
4532   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
4533     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
4534     // In the 64-bit large code model, we have to make all calls
4535     // through a register, since the call instruction's 32-bit
4536     // pc-relative offset may not be large enough to hold the whole
4537     // address.
4538   } else if (Callee->getOpcode() == ISD::GlobalAddress ||
4539              Callee->getOpcode() == ISD::ExternalSymbol) {
4540     // Lower direct calls to global addresses and external symbols. Setting
4541     // ForCall to true here has the effect of removing WrapperRIP when possible
4542     // to allow direct calls to be selected without first materializing the
4543     // address into a register.
4544     Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
4545   } else if (Subtarget.isTarget64BitILP32() &&
4546              Callee.getValueType() == MVT::i32) {
4547     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4548     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4549   }
4550 
4551   // Returns a chain & a flag for retval copy to use.
4552   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4553   SmallVector<SDValue, 8> Ops;
4554 
4555   if (!IsSibcall && isTailCall && !IsMustTail) {
4556     Chain = DAG.getCALLSEQ_END(Chain,
4557                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4558                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4559     InFlag = Chain.getValue(1);
4560   }
4561 
4562   Ops.push_back(Chain);
4563   Ops.push_back(Callee);
4564 
4565   if (isTailCall)
4566     Ops.push_back(DAG.getTargetConstant(FPDiff, dl, MVT::i32));
4567 
4568   // Add argument registers to the end of the list so that they are known live
4569   // into the call.
4570   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4571     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4572                                   RegsToPass[i].second.getValueType()));
4573 
4574   // Add a register mask operand representing the call-preserved registers.
4575   const uint32_t *Mask = [&]() {
4576     auto AdaptedCC = CallConv;
4577     // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists),
4578     // use X86_INTR calling convention because it has the same CSR mask
4579     // (same preserved registers).
4580     if (HasNCSR)
4581       AdaptedCC = (CallingConv::ID)CallingConv::X86_INTR;
4582     // If NoCalleeSavedRegisters is requested, than use GHC since it happens
4583     // to use the CSR_NoRegs_RegMask.
4584     if (CB && CB->hasFnAttr("no_callee_saved_registers"))
4585       AdaptedCC = (CallingConv::ID)CallingConv::GHC;
4586     return RegInfo->getCallPreservedMask(MF, AdaptedCC);
4587   }();
4588   assert(Mask && "Missing call preserved mask for calling convention");
4589 
4590   // If this is an invoke in a 32-bit function using a funclet-based
4591   // personality, assume the function clobbers all registers. If an exception
4592   // is thrown, the runtime will not restore CSRs.
4593   // FIXME: Model this more precisely so that we can register allocate across
4594   // the normal edge and spill and fill across the exceptional edge.
4595   if (!Is64Bit && CLI.CB && isa<InvokeInst>(CLI.CB)) {
4596     const Function &CallerFn = MF.getFunction();
4597     EHPersonality Pers =
4598         CallerFn.hasPersonalityFn()
4599             ? classifyEHPersonality(CallerFn.getPersonalityFn())
4600             : EHPersonality::Unknown;
4601     if (isFuncletEHPersonality(Pers))
4602       Mask = RegInfo->getNoPreservedMask();
4603   }
4604 
4605   // Define a new register mask from the existing mask.
4606   uint32_t *RegMask = nullptr;
4607 
4608   // In some calling conventions we need to remove the used physical registers
4609   // from the reg mask.
4610   if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4611     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4612 
4613     // Allocate a new Reg Mask and copy Mask.
4614     RegMask = MF.allocateRegMask();
4615     unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4616     memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4617 
4618     // Make sure all sub registers of the argument registers are reset
4619     // in the RegMask.
4620     for (auto const &RegPair : RegsToPass)
4621       for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4622            SubRegs.isValid(); ++SubRegs)
4623         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4624 
4625     // Create the RegMask Operand according to our updated mask.
4626     Ops.push_back(DAG.getRegisterMask(RegMask));
4627   } else {
4628     // Create the RegMask Operand according to the static mask.
4629     Ops.push_back(DAG.getRegisterMask(Mask));
4630   }
4631 
4632   if (InFlag.getNode())
4633     Ops.push_back(InFlag);
4634 
4635   if (isTailCall) {
4636     // We used to do:
4637     //// If this is the first return lowered for this function, add the regs
4638     //// to the liveout set for the function.
4639     // This isn't right, although it's probably harmless on x86; liveouts
4640     // should be computed from returns not tail calls.  Consider a void
4641     // function making a tail call to a function returning int.
4642     MF.getFrameInfo().setHasTailCall();
4643     SDValue Ret = DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4644     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4645     return Ret;
4646   }
4647 
4648   if (HasNoCfCheck && IsCFProtectionSupported && IsIndirectCall) {
4649     Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4650   } else if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
4651     // Calls with a "clang.arc.attachedcall" bundle are special. They should be
4652     // expanded to the call, directly followed by a special marker sequence and
4653     // a call to a ObjC library function. Use the CALL_RVMARKER to do that.
4654     assert(!isTailCall &&
4655            "tail calls cannot be marked with clang.arc.attachedcall");
4656     assert(Is64Bit && "clang.arc.attachedcall is only supported in 64bit mode");
4657 
4658     // Add a target global address for the retainRV/claimRV runtime function
4659     // just before the call target.
4660     Function *ARCFn = *objcarc::getAttachedARCFunction(CLI.CB);
4661     auto PtrVT = getPointerTy(DAG.getDataLayout());
4662     auto GA = DAG.getTargetGlobalAddress(ARCFn, dl, PtrVT);
4663     Ops.insert(Ops.begin() + 1, GA);
4664     Chain = DAG.getNode(X86ISD::CALL_RVMARKER, dl, NodeTys, Ops);
4665   } else {
4666     Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4667   }
4668 
4669   InFlag = Chain.getValue(1);
4670   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4671   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4672 
4673   // Save heapallocsite metadata.
4674   if (CLI.CB)
4675     if (MDNode *HeapAlloc = CLI.CB->getMetadata("heapallocsite"))
4676       DAG.addHeapAllocSite(Chain.getNode(), HeapAlloc);
4677 
4678   // Create the CALLSEQ_END node.
4679   unsigned NumBytesForCalleeToPop = 0; // Callee pops nothing.
4680   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4681                        DAG.getTarget().Options.GuaranteedTailCallOpt))
4682     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
4683   else if (!canGuaranteeTCO(CallConv) && IsCalleePopSRet)
4684     // If this call passes a struct-return pointer, the callee
4685     // pops that struct pointer.
4686     NumBytesForCalleeToPop = 4;
4687 
4688   // Returns a flag for retval copy to use.
4689   if (!IsSibcall) {
4690     Chain = DAG.getCALLSEQ_END(Chain,
4691                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4692                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4693                                                      true),
4694                                InFlag, dl);
4695     InFlag = Chain.getValue(1);
4696   }
4697 
4698   // Handle result values, copying them out of physregs into vregs that we
4699   // return.
4700   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4701                          InVals, RegMask);
4702 }
4703 
4704 //===----------------------------------------------------------------------===//
4705 //                Fast Calling Convention (tail call) implementation
4706 //===----------------------------------------------------------------------===//
4707 
4708 //  Like std call, callee cleans arguments, convention except that ECX is
4709 //  reserved for storing the tail called function address. Only 2 registers are
4710 //  free for argument passing (inreg). Tail call optimization is performed
4711 //  provided:
4712 //                * tailcallopt is enabled
4713 //                * caller/callee are fastcc
4714 //  On X86_64 architecture with GOT-style position independent code only local
4715 //  (within module) calls are supported at the moment.
4716 //  To keep the stack aligned according to platform abi the function
4717 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
4718 //  of stack alignment. (Dynamic linkers need this - Darwin's dyld for example)
4719 //  If a tail called function callee has more arguments than the caller the
4720 //  caller needs to make sure that there is room to move the RETADDR to. This is
4721 //  achieved by reserving an area the size of the argument delta right after the
4722 //  original RETADDR, but before the saved framepointer or the spilled registers
4723 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4724 //  stack layout:
4725 //    arg1
4726 //    arg2
4727 //    RETADDR
4728 //    [ new RETADDR
4729 //      move area ]
4730 //    (possible EBP)
4731 //    ESI
4732 //    EDI
4733 //    local1 ..
4734 
4735 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4736 /// requirement.
4737 unsigned
4738 X86TargetLowering::GetAlignedArgumentStackSize(const unsigned StackSize,
4739                                                SelectionDAG &DAG) const {
4740   const Align StackAlignment = Subtarget.getFrameLowering()->getStackAlign();
4741   const uint64_t SlotSize = Subtarget.getRegisterInfo()->getSlotSize();
4742   assert(StackSize % SlotSize == 0 &&
4743          "StackSize must be a multiple of SlotSize");
4744   return alignTo(StackSize + SlotSize, StackAlignment) - SlotSize;
4745 }
4746 
4747 /// Return true if the given stack call argument is already available in the
4748 /// same position (relatively) of the caller's incoming argument stack.
4749 static
4750 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4751                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4752                          const X86InstrInfo *TII, const CCValAssign &VA) {
4753   unsigned Bytes = Arg.getValueSizeInBits() / 8;
4754 
4755   for (;;) {
4756     // Look through nodes that don't alter the bits of the incoming value.
4757     unsigned Op = Arg.getOpcode();
4758     if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4759       Arg = Arg.getOperand(0);
4760       continue;
4761     }
4762     if (Op == ISD::TRUNCATE) {
4763       const SDValue &TruncInput = Arg.getOperand(0);
4764       if (TruncInput.getOpcode() == ISD::AssertZext &&
4765           cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4766               Arg.getValueType()) {
4767         Arg = TruncInput.getOperand(0);
4768         continue;
4769       }
4770     }
4771     break;
4772   }
4773 
4774   int FI = INT_MAX;
4775   if (Arg.getOpcode() == ISD::CopyFromReg) {
4776     Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4777     if (!VR.isVirtual())
4778       return false;
4779     MachineInstr *Def = MRI->getVRegDef(VR);
4780     if (!Def)
4781       return false;
4782     if (!Flags.isByVal()) {
4783       if (!TII->isLoadFromStackSlot(*Def, FI))
4784         return false;
4785     } else {
4786       unsigned Opcode = Def->getOpcode();
4787       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4788            Opcode == X86::LEA64_32r) &&
4789           Def->getOperand(1).isFI()) {
4790         FI = Def->getOperand(1).getIndex();
4791         Bytes = Flags.getByValSize();
4792       } else
4793         return false;
4794     }
4795   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4796     if (Flags.isByVal())
4797       // ByVal argument is passed in as a pointer but it's now being
4798       // dereferenced. e.g.
4799       // define @foo(%struct.X* %A) {
4800       //   tail call @bar(%struct.X* byval %A)
4801       // }
4802       return false;
4803     SDValue Ptr = Ld->getBasePtr();
4804     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4805     if (!FINode)
4806       return false;
4807     FI = FINode->getIndex();
4808   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4809     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4810     FI = FINode->getIndex();
4811     Bytes = Flags.getByValSize();
4812   } else
4813     return false;
4814 
4815   assert(FI != INT_MAX);
4816   if (!MFI.isFixedObjectIndex(FI))
4817     return false;
4818 
4819   if (Offset != MFI.getObjectOffset(FI))
4820     return false;
4821 
4822   // If this is not byval, check that the argument stack object is immutable.
4823   // inalloca and argument copy elision can create mutable argument stack
4824   // objects. Byval objects can be mutated, but a byval call intends to pass the
4825   // mutated memory.
4826   if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4827     return false;
4828 
4829   if (VA.getLocVT().getFixedSizeInBits() >
4830       Arg.getValueSizeInBits().getFixedSize()) {
4831     // If the argument location is wider than the argument type, check that any
4832     // extension flags match.
4833     if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4834         Flags.isSExt() != MFI.isObjectSExt(FI)) {
4835       return false;
4836     }
4837   }
4838 
4839   return Bytes == MFI.getObjectSize(FI);
4840 }
4841 
4842 /// Check whether the call is eligible for tail call optimization. Targets
4843 /// that want to do tail call optimization should implement this function.
4844 bool X86TargetLowering::IsEligibleForTailCallOptimization(
4845     SDValue Callee, CallingConv::ID CalleeCC, bool IsCalleePopSRet,
4846     bool isVarArg, Type *RetTy, const SmallVectorImpl<ISD::OutputArg> &Outs,
4847     const SmallVectorImpl<SDValue> &OutVals,
4848     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4849   if (!mayTailCallThisCC(CalleeCC))
4850     return false;
4851 
4852   // If -tailcallopt is specified, make fastcc functions tail-callable.
4853   MachineFunction &MF = DAG.getMachineFunction();
4854   const Function &CallerF = MF.getFunction();
4855 
4856   // If the function return type is x86_fp80 and the callee return type is not,
4857   // then the FP_EXTEND of the call result is not a nop. It's not safe to
4858   // perform a tailcall optimization here.
4859   if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4860     return false;
4861 
4862   CallingConv::ID CallerCC = CallerF.getCallingConv();
4863   bool CCMatch = CallerCC == CalleeCC;
4864   bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4865   bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4866   bool IsGuaranteeTCO = DAG.getTarget().Options.GuaranteedTailCallOpt ||
4867       CalleeCC == CallingConv::Tail || CalleeCC == CallingConv::SwiftTail;
4868 
4869   // Win64 functions have extra shadow space for argument homing. Don't do the
4870   // sibcall if the caller and callee have mismatched expectations for this
4871   // space.
4872   if (IsCalleeWin64 != IsCallerWin64)
4873     return false;
4874 
4875   if (IsGuaranteeTCO) {
4876     if (canGuaranteeTCO(CalleeCC) && CCMatch)
4877       return true;
4878     return false;
4879   }
4880 
4881   // Look for obvious safe cases to perform tail call optimization that do not
4882   // require ABI changes. This is what gcc calls sibcall.
4883 
4884   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4885   // emit a special epilogue.
4886   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4887   if (RegInfo->hasStackRealignment(MF))
4888     return false;
4889 
4890   // Also avoid sibcall optimization if we're an sret return fn and the callee
4891   // is incompatible. See comment in LowerReturn about why hasStructRetAttr is
4892   // insufficient.
4893   if (MF.getInfo<X86MachineFunctionInfo>()->getSRetReturnReg()) {
4894     // For a compatible tail call the callee must return our sret pointer. So it
4895     // needs to be (a) an sret function itself and (b) we pass our sret as its
4896     // sret. Condition #b is harder to determine.
4897     return false;
4898   } else if (IsCalleePopSRet)
4899     // The callee pops an sret, so we cannot tail-call, as our caller doesn't
4900     // expect that.
4901     return false;
4902 
4903   // Do not sibcall optimize vararg calls unless all arguments are passed via
4904   // registers.
4905   LLVMContext &C = *DAG.getContext();
4906   if (isVarArg && !Outs.empty()) {
4907     // Optimizing for varargs on Win64 is unlikely to be safe without
4908     // additional testing.
4909     if (IsCalleeWin64 || IsCallerWin64)
4910       return false;
4911 
4912     SmallVector<CCValAssign, 16> ArgLocs;
4913     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4914 
4915     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4916     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4917       if (!ArgLocs[i].isRegLoc())
4918         return false;
4919   }
4920 
4921   // If the call result is in ST0 / ST1, it needs to be popped off the x87
4922   // stack.  Therefore, if it's not used by the call it is not safe to optimize
4923   // this into a sibcall.
4924   bool Unused = false;
4925   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4926     if (!Ins[i].Used) {
4927       Unused = true;
4928       break;
4929     }
4930   }
4931   if (Unused) {
4932     SmallVector<CCValAssign, 16> RVLocs;
4933     CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4934     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4935     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4936       CCValAssign &VA = RVLocs[i];
4937       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4938         return false;
4939     }
4940   }
4941 
4942   // Check that the call results are passed in the same way.
4943   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4944                                   RetCC_X86, RetCC_X86))
4945     return false;
4946   // The callee has to preserve all registers the caller needs to preserve.
4947   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4948   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4949   if (!CCMatch) {
4950     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4951     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4952       return false;
4953   }
4954 
4955   unsigned StackArgsSize = 0;
4956 
4957   // If the callee takes no arguments then go on to check the results of the
4958   // call.
4959   if (!Outs.empty()) {
4960     // Check if stack adjustment is needed. For now, do not do this if any
4961     // argument is passed on the stack.
4962     SmallVector<CCValAssign, 16> ArgLocs;
4963     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4964 
4965     // Allocate shadow area for Win64
4966     if (IsCalleeWin64)
4967       CCInfo.AllocateStack(32, Align(8));
4968 
4969     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4970     StackArgsSize = CCInfo.getNextStackOffset();
4971 
4972     if (CCInfo.getNextStackOffset()) {
4973       // Check if the arguments are already laid out in the right way as
4974       // the caller's fixed stack objects.
4975       MachineFrameInfo &MFI = MF.getFrameInfo();
4976       const MachineRegisterInfo *MRI = &MF.getRegInfo();
4977       const X86InstrInfo *TII = Subtarget.getInstrInfo();
4978       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4979         CCValAssign &VA = ArgLocs[i];
4980         SDValue Arg = OutVals[i];
4981         ISD::ArgFlagsTy Flags = Outs[i].Flags;
4982         if (VA.getLocInfo() == CCValAssign::Indirect)
4983           return false;
4984         if (!VA.isRegLoc()) {
4985           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4986                                    MFI, MRI, TII, VA))
4987             return false;
4988         }
4989       }
4990     }
4991 
4992     bool PositionIndependent = isPositionIndependent();
4993     // If the tailcall address may be in a register, then make sure it's
4994     // possible to register allocate for it. In 32-bit, the call address can
4995     // only target EAX, EDX, or ECX since the tail call must be scheduled after
4996     // callee-saved registers are restored. These happen to be the same
4997     // registers used to pass 'inreg' arguments so watch out for those.
4998     if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4999                                   !isa<ExternalSymbolSDNode>(Callee)) ||
5000                                  PositionIndependent)) {
5001       unsigned NumInRegs = 0;
5002       // In PIC we need an extra register to formulate the address computation
5003       // for the callee.
5004       unsigned MaxInRegs = PositionIndependent ? 2 : 3;
5005 
5006       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
5007         CCValAssign &VA = ArgLocs[i];
5008         if (!VA.isRegLoc())
5009           continue;
5010         Register Reg = VA.getLocReg();
5011         switch (Reg) {
5012         default: break;
5013         case X86::EAX: case X86::EDX: case X86::ECX:
5014           if (++NumInRegs == MaxInRegs)
5015             return false;
5016           break;
5017         }
5018       }
5019     }
5020 
5021     const MachineRegisterInfo &MRI = MF.getRegInfo();
5022     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
5023       return false;
5024   }
5025 
5026   bool CalleeWillPop =
5027       X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
5028                        MF.getTarget().Options.GuaranteedTailCallOpt);
5029 
5030   if (unsigned BytesToPop =
5031           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
5032     // If we have bytes to pop, the callee must pop them.
5033     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
5034     if (!CalleePopMatches)
5035       return false;
5036   } else if (CalleeWillPop && StackArgsSize > 0) {
5037     // If we don't have bytes to pop, make sure the callee doesn't pop any.
5038     return false;
5039   }
5040 
5041   return true;
5042 }
5043 
5044 FastISel *
5045 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
5046                                   const TargetLibraryInfo *libInfo) const {
5047   return X86::createFastISel(funcInfo, libInfo);
5048 }
5049 
5050 //===----------------------------------------------------------------------===//
5051 //                           Other Lowering Hooks
5052 //===----------------------------------------------------------------------===//
5053 
5054 bool X86::mayFoldLoad(SDValue Op, const X86Subtarget &Subtarget,
5055                       bool AssumeSingleUse) {
5056   if (!AssumeSingleUse && !Op.hasOneUse())
5057     return false;
5058   if (!ISD::isNormalLoad(Op.getNode()))
5059     return false;
5060 
5061   // If this is an unaligned vector, make sure the target supports folding it.
5062   auto *Ld = cast<LoadSDNode>(Op.getNode());
5063   if (!Subtarget.hasAVX() && !Subtarget.hasSSEUnalignedMem() &&
5064       Ld->getValueSizeInBits(0) == 128 && Ld->getAlignment() < 16)
5065     return false;
5066 
5067   // TODO: If this is a non-temporal load and the target has an instruction
5068   //       for it, it should not be folded. See "useNonTemporalLoad()".
5069 
5070   return true;
5071 }
5072 
5073 bool X86::mayFoldLoadIntoBroadcastFromMem(SDValue Op, MVT EltVT,
5074                                           const X86Subtarget &Subtarget,
5075                                           bool AssumeSingleUse) {
5076   assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
5077   if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
5078     return false;
5079 
5080   // We can not replace a wide volatile load with a broadcast-from-memory,
5081   // because that would narrow the load, which isn't legal for volatiles.
5082   auto *Ld = cast<LoadSDNode>(Op.getNode());
5083   return !Ld->isVolatile() ||
5084          Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
5085 }
5086 
5087 bool X86::mayFoldIntoStore(SDValue Op) {
5088   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
5089 }
5090 
5091 bool X86::mayFoldIntoZeroExtend(SDValue Op) {
5092   if (Op.hasOneUse()) {
5093     unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
5094     return (ISD::ZERO_EXTEND == Opcode);
5095   }
5096   return false;
5097 }
5098 
5099 static bool isTargetShuffle(unsigned Opcode) {
5100   switch(Opcode) {
5101   default: return false;
5102   case X86ISD::BLENDI:
5103   case X86ISD::PSHUFB:
5104   case X86ISD::PSHUFD:
5105   case X86ISD::PSHUFHW:
5106   case X86ISD::PSHUFLW:
5107   case X86ISD::SHUFP:
5108   case X86ISD::INSERTPS:
5109   case X86ISD::EXTRQI:
5110   case X86ISD::INSERTQI:
5111   case X86ISD::VALIGN:
5112   case X86ISD::PALIGNR:
5113   case X86ISD::VSHLDQ:
5114   case X86ISD::VSRLDQ:
5115   case X86ISD::MOVLHPS:
5116   case X86ISD::MOVHLPS:
5117   case X86ISD::MOVSHDUP:
5118   case X86ISD::MOVSLDUP:
5119   case X86ISD::MOVDDUP:
5120   case X86ISD::MOVSS:
5121   case X86ISD::MOVSD:
5122   case X86ISD::MOVSH:
5123   case X86ISD::UNPCKL:
5124   case X86ISD::UNPCKH:
5125   case X86ISD::VBROADCAST:
5126   case X86ISD::VPERMILPI:
5127   case X86ISD::VPERMILPV:
5128   case X86ISD::VPERM2X128:
5129   case X86ISD::SHUF128:
5130   case X86ISD::VPERMIL2:
5131   case X86ISD::VPERMI:
5132   case X86ISD::VPPERM:
5133   case X86ISD::VPERMV:
5134   case X86ISD::VPERMV3:
5135   case X86ISD::VZEXT_MOVL:
5136     return true;
5137   }
5138 }
5139 
5140 static bool isTargetShuffleVariableMask(unsigned Opcode) {
5141   switch (Opcode) {
5142   default: return false;
5143   // Target Shuffles.
5144   case X86ISD::PSHUFB:
5145   case X86ISD::VPERMILPV:
5146   case X86ISD::VPERMIL2:
5147   case X86ISD::VPPERM:
5148   case X86ISD::VPERMV:
5149   case X86ISD::VPERMV3:
5150     return true;
5151   // 'Faux' Target Shuffles.
5152   case ISD::OR:
5153   case ISD::AND:
5154   case X86ISD::ANDNP:
5155     return true;
5156   }
5157 }
5158 
5159 static bool isTargetShuffleSplat(SDValue Op) {
5160   unsigned Opcode = Op.getOpcode();
5161   if (Opcode == ISD::EXTRACT_SUBVECTOR)
5162     return isTargetShuffleSplat(Op.getOperand(0));
5163   return Opcode == X86ISD::VBROADCAST || Opcode == X86ISD::VBROADCAST_LOAD;
5164 }
5165 
5166 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
5167   MachineFunction &MF = DAG.getMachineFunction();
5168   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
5169   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
5170   int ReturnAddrIndex = FuncInfo->getRAIndex();
5171 
5172   if (ReturnAddrIndex == 0) {
5173     // Set up a frame object for the return address.
5174     unsigned SlotSize = RegInfo->getSlotSize();
5175     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
5176                                                           -(int64_t)SlotSize,
5177                                                           false);
5178     FuncInfo->setRAIndex(ReturnAddrIndex);
5179   }
5180 
5181   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
5182 }
5183 
5184 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
5185                                        bool hasSymbolicDisplacement) {
5186   // Offset should fit into 32 bit immediate field.
5187   if (!isInt<32>(Offset))
5188     return false;
5189 
5190   // If we don't have a symbolic displacement - we don't have any extra
5191   // restrictions.
5192   if (!hasSymbolicDisplacement)
5193     return true;
5194 
5195   // FIXME: Some tweaks might be needed for medium code model.
5196   if (M != CodeModel::Small && M != CodeModel::Kernel)
5197     return false;
5198 
5199   // For small code model we assume that latest object is 16MB before end of 31
5200   // bits boundary. We may also accept pretty large negative constants knowing
5201   // that all objects are in the positive half of address space.
5202   if (M == CodeModel::Small && Offset < 16*1024*1024)
5203     return true;
5204 
5205   // For kernel code model we know that all object resist in the negative half
5206   // of 32bits address space. We may not accept negative offsets, since they may
5207   // be just off and we may accept pretty large positive ones.
5208   if (M == CodeModel::Kernel && Offset >= 0)
5209     return true;
5210 
5211   return false;
5212 }
5213 
5214 /// Determines whether the callee is required to pop its own arguments.
5215 /// Callee pop is necessary to support tail calls.
5216 bool X86::isCalleePop(CallingConv::ID CallingConv,
5217                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
5218   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
5219   // can guarantee TCO.
5220   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
5221     return true;
5222 
5223   switch (CallingConv) {
5224   default:
5225     return false;
5226   case CallingConv::X86_StdCall:
5227   case CallingConv::X86_FastCall:
5228   case CallingConv::X86_ThisCall:
5229   case CallingConv::X86_VectorCall:
5230     return !is64Bit;
5231   }
5232 }
5233 
5234 /// Return true if the condition is an signed comparison operation.
5235 static bool isX86CCSigned(unsigned X86CC) {
5236   switch (X86CC) {
5237   default:
5238     llvm_unreachable("Invalid integer condition!");
5239   case X86::COND_E:
5240   case X86::COND_NE:
5241   case X86::COND_B:
5242   case X86::COND_A:
5243   case X86::COND_BE:
5244   case X86::COND_AE:
5245     return false;
5246   case X86::COND_G:
5247   case X86::COND_GE:
5248   case X86::COND_L:
5249   case X86::COND_LE:
5250     return true;
5251   }
5252 }
5253 
5254 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
5255   switch (SetCCOpcode) {
5256   default: llvm_unreachable("Invalid integer condition!");
5257   case ISD::SETEQ:  return X86::COND_E;
5258   case ISD::SETGT:  return X86::COND_G;
5259   case ISD::SETGE:  return X86::COND_GE;
5260   case ISD::SETLT:  return X86::COND_L;
5261   case ISD::SETLE:  return X86::COND_LE;
5262   case ISD::SETNE:  return X86::COND_NE;
5263   case ISD::SETULT: return X86::COND_B;
5264   case ISD::SETUGT: return X86::COND_A;
5265   case ISD::SETULE: return X86::COND_BE;
5266   case ISD::SETUGE: return X86::COND_AE;
5267   }
5268 }
5269 
5270 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
5271 /// condition code, returning the condition code and the LHS/RHS of the
5272 /// comparison to make.
5273 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
5274                                     bool isFP, SDValue &LHS, SDValue &RHS,
5275                                     SelectionDAG &DAG) {
5276   if (!isFP) {
5277     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5278       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
5279         // X > -1   -> X == 0, jump !sign.
5280         RHS = DAG.getConstant(0, DL, RHS.getValueType());
5281         return X86::COND_NS;
5282       }
5283       if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
5284         // X < 0   -> X == 0, jump on sign.
5285         return X86::COND_S;
5286       }
5287       if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
5288         // X >= 0   -> X == 0, jump on !sign.
5289         return X86::COND_NS;
5290       }
5291       if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
5292         // X < 1   -> X <= 0
5293         RHS = DAG.getConstant(0, DL, RHS.getValueType());
5294         return X86::COND_LE;
5295       }
5296     }
5297 
5298     return TranslateIntegerX86CC(SetCCOpcode);
5299   }
5300 
5301   // First determine if it is required or is profitable to flip the operands.
5302 
5303   // If LHS is a foldable load, but RHS is not, flip the condition.
5304   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
5305       !ISD::isNON_EXTLoad(RHS.getNode())) {
5306     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
5307     std::swap(LHS, RHS);
5308   }
5309 
5310   switch (SetCCOpcode) {
5311   default: break;
5312   case ISD::SETOLT:
5313   case ISD::SETOLE:
5314   case ISD::SETUGT:
5315   case ISD::SETUGE:
5316     std::swap(LHS, RHS);
5317     break;
5318   }
5319 
5320   // On a floating point condition, the flags are set as follows:
5321   // ZF  PF  CF   op
5322   //  0 | 0 | 0 | X > Y
5323   //  0 | 0 | 1 | X < Y
5324   //  1 | 0 | 0 | X == Y
5325   //  1 | 1 | 1 | unordered
5326   switch (SetCCOpcode) {
5327   default: llvm_unreachable("Condcode should be pre-legalized away");
5328   case ISD::SETUEQ:
5329   case ISD::SETEQ:   return X86::COND_E;
5330   case ISD::SETOLT:              // flipped
5331   case ISD::SETOGT:
5332   case ISD::SETGT:   return X86::COND_A;
5333   case ISD::SETOLE:              // flipped
5334   case ISD::SETOGE:
5335   case ISD::SETGE:   return X86::COND_AE;
5336   case ISD::SETUGT:              // flipped
5337   case ISD::SETULT:
5338   case ISD::SETLT:   return X86::COND_B;
5339   case ISD::SETUGE:              // flipped
5340   case ISD::SETULE:
5341   case ISD::SETLE:   return X86::COND_BE;
5342   case ISD::SETONE:
5343   case ISD::SETNE:   return X86::COND_NE;
5344   case ISD::SETUO:   return X86::COND_P;
5345   case ISD::SETO:    return X86::COND_NP;
5346   case ISD::SETOEQ:
5347   case ISD::SETUNE:  return X86::COND_INVALID;
5348   }
5349 }
5350 
5351 /// Is there a floating point cmov for the specific X86 condition code?
5352 /// Current x86 isa includes the following FP cmov instructions:
5353 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
5354 static bool hasFPCMov(unsigned X86CC) {
5355   switch (X86CC) {
5356   default:
5357     return false;
5358   case X86::COND_B:
5359   case X86::COND_BE:
5360   case X86::COND_E:
5361   case X86::COND_P:
5362   case X86::COND_A:
5363   case X86::COND_AE:
5364   case X86::COND_NE:
5365   case X86::COND_NP:
5366     return true;
5367   }
5368 }
5369 
5370 static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
5371   return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
5372          VT.is512BitVector();
5373 }
5374 
5375 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5376                                            const CallInst &I,
5377                                            MachineFunction &MF,
5378                                            unsigned Intrinsic) const {
5379   Info.flags = MachineMemOperand::MONone;
5380   Info.offset = 0;
5381 
5382   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
5383   if (!IntrData) {
5384     switch (Intrinsic) {
5385     case Intrinsic::x86_aesenc128kl:
5386     case Intrinsic::x86_aesdec128kl:
5387       Info.opc = ISD::INTRINSIC_W_CHAIN;
5388       Info.ptrVal = I.getArgOperand(1);
5389       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5390       Info.align = Align(1);
5391       Info.flags |= MachineMemOperand::MOLoad;
5392       return true;
5393     case Intrinsic::x86_aesenc256kl:
5394     case Intrinsic::x86_aesdec256kl:
5395       Info.opc = ISD::INTRINSIC_W_CHAIN;
5396       Info.ptrVal = I.getArgOperand(1);
5397       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5398       Info.align = Align(1);
5399       Info.flags |= MachineMemOperand::MOLoad;
5400       return true;
5401     case Intrinsic::x86_aesencwide128kl:
5402     case Intrinsic::x86_aesdecwide128kl:
5403       Info.opc = ISD::INTRINSIC_W_CHAIN;
5404       Info.ptrVal = I.getArgOperand(0);
5405       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5406       Info.align = Align(1);
5407       Info.flags |= MachineMemOperand::MOLoad;
5408       return true;
5409     case Intrinsic::x86_aesencwide256kl:
5410     case Intrinsic::x86_aesdecwide256kl:
5411       Info.opc = ISD::INTRINSIC_W_CHAIN;
5412       Info.ptrVal = I.getArgOperand(0);
5413       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5414       Info.align = Align(1);
5415       Info.flags |= MachineMemOperand::MOLoad;
5416       return true;
5417     }
5418     return false;
5419   }
5420 
5421   switch (IntrData->Type) {
5422   case TRUNCATE_TO_MEM_VI8:
5423   case TRUNCATE_TO_MEM_VI16:
5424   case TRUNCATE_TO_MEM_VI32: {
5425     Info.opc = ISD::INTRINSIC_VOID;
5426     Info.ptrVal = I.getArgOperand(0);
5427     MVT VT  = MVT::getVT(I.getArgOperand(1)->getType());
5428     MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
5429     if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
5430       ScalarVT = MVT::i8;
5431     else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
5432       ScalarVT = MVT::i16;
5433     else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
5434       ScalarVT = MVT::i32;
5435 
5436     Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
5437     Info.align = Align(1);
5438     Info.flags |= MachineMemOperand::MOStore;
5439     break;
5440   }
5441   case GATHER:
5442   case GATHER_AVX2: {
5443     Info.opc = ISD::INTRINSIC_W_CHAIN;
5444     Info.ptrVal = nullptr;
5445     MVT DataVT = MVT::getVT(I.getType());
5446     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5447     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5448                                 IndexVT.getVectorNumElements());
5449     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5450     Info.align = Align(1);
5451     Info.flags |= MachineMemOperand::MOLoad;
5452     break;
5453   }
5454   case SCATTER: {
5455     Info.opc = ISD::INTRINSIC_VOID;
5456     Info.ptrVal = nullptr;
5457     MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
5458     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5459     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5460                                 IndexVT.getVectorNumElements());
5461     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5462     Info.align = Align(1);
5463     Info.flags |= MachineMemOperand::MOStore;
5464     break;
5465   }
5466   default:
5467     return false;
5468   }
5469 
5470   return true;
5471 }
5472 
5473 /// Returns true if the target can instruction select the
5474 /// specified FP immediate natively. If false, the legalizer will
5475 /// materialize the FP immediate as a load from a constant pool.
5476 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5477                                      bool ForCodeSize) const {
5478   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
5479     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
5480       return true;
5481   }
5482   return false;
5483 }
5484 
5485 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
5486                                               ISD::LoadExtType ExtTy,
5487                                               EVT NewVT) const {
5488   assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
5489 
5490   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
5491   // relocation target a movq or addq instruction: don't let the load shrink.
5492   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
5493   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
5494     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
5495       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
5496 
5497   // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
5498   // those uses are extracted directly into a store, then the extract + store
5499   // can be store-folded. Therefore, it's probably not worth splitting the load.
5500   EVT VT = Load->getValueType(0);
5501   if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
5502     for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
5503       // Skip uses of the chain value. Result 0 of the node is the load value.
5504       if (UI.getUse().getResNo() != 0)
5505         continue;
5506 
5507       // If this use is not an extract + store, it's probably worth splitting.
5508       if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
5509           UI->use_begin()->getOpcode() != ISD::STORE)
5510         return true;
5511     }
5512     // All non-chain uses are extract + store.
5513     return false;
5514   }
5515 
5516   return true;
5517 }
5518 
5519 /// Returns true if it is beneficial to convert a load of a constant
5520 /// to just the constant itself.
5521 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5522                                                           Type *Ty) const {
5523   assert(Ty->isIntegerTy());
5524 
5525   unsigned BitSize = Ty->getPrimitiveSizeInBits();
5526   if (BitSize == 0 || BitSize > 64)
5527     return false;
5528   return true;
5529 }
5530 
5531 bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
5532   // If we are using XMM registers in the ABI and the condition of the select is
5533   // a floating-point compare and we have blendv or conditional move, then it is
5534   // cheaper to select instead of doing a cross-register move and creating a
5535   // load that depends on the compare result.
5536   bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
5537   return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
5538 }
5539 
5540 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
5541   // TODO: It might be a win to ease or lift this restriction, but the generic
5542   // folds in DAGCombiner conflict with vector folds for an AVX512 target.
5543   if (VT.isVector() && Subtarget.hasAVX512())
5544     return false;
5545 
5546   return true;
5547 }
5548 
5549 bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
5550                                                SDValue C) const {
5551   // TODO: We handle scalars using custom code, but generic combining could make
5552   // that unnecessary.
5553   APInt MulC;
5554   if (!ISD::isConstantSplatVector(C.getNode(), MulC))
5555     return false;
5556 
5557   // Find the type this will be legalized too. Otherwise we might prematurely
5558   // convert this to shl+add/sub and then still have to type legalize those ops.
5559   // Another choice would be to defer the decision for illegal types until
5560   // after type legalization. But constant splat vectors of i64 can't make it
5561   // through type legalization on 32-bit targets so we would need to special
5562   // case vXi64.
5563   while (getTypeAction(Context, VT) != TypeLegal)
5564     VT = getTypeToTransformTo(Context, VT);
5565 
5566   // If vector multiply is legal, assume that's faster than shl + add/sub.
5567   // Multiply is a complex op with higher latency and lower throughput in
5568   // most implementations, sub-vXi32 vector multiplies are always fast,
5569   // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
5570   // is always going to be slow.
5571   unsigned EltSizeInBits = VT.getScalarSizeInBits();
5572   if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
5573       (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
5574     return false;
5575 
5576   // shl+add, shl+sub, shl+add+neg
5577   return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
5578          (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
5579 }
5580 
5581 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
5582                                                 unsigned Index) const {
5583   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
5584     return false;
5585 
5586   // Mask vectors support all subregister combinations and operations that
5587   // extract half of vector.
5588   if (ResVT.getVectorElementType() == MVT::i1)
5589     return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
5590                           (Index == ResVT.getVectorNumElements()));
5591 
5592   return (Index % ResVT.getVectorNumElements()) == 0;
5593 }
5594 
5595 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
5596   unsigned Opc = VecOp.getOpcode();
5597 
5598   // Assume target opcodes can't be scalarized.
5599   // TODO - do we have any exceptions?
5600   if (Opc >= ISD::BUILTIN_OP_END)
5601     return false;
5602 
5603   // If the vector op is not supported, try to convert to scalar.
5604   EVT VecVT = VecOp.getValueType();
5605   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
5606     return true;
5607 
5608   // If the vector op is supported, but the scalar op is not, the transform may
5609   // not be worthwhile.
5610   EVT ScalarVT = VecVT.getScalarType();
5611   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
5612 }
5613 
5614 bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT,
5615                                              bool) const {
5616   // TODO: Allow vectors?
5617   if (VT.isVector())
5618     return false;
5619   return VT.isSimple() || !isOperationExpand(Opcode, VT);
5620 }
5621 
5622 bool X86TargetLowering::isCheapToSpeculateCttz() const {
5623   // Speculate cttz only if we can directly use TZCNT.
5624   return Subtarget.hasBMI();
5625 }
5626 
5627 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
5628   // Speculate ctlz only if we can directly use LZCNT.
5629   return Subtarget.hasLZCNT();
5630 }
5631 
5632 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
5633                                                 const SelectionDAG &DAG,
5634                                                 const MachineMemOperand &MMO) const {
5635   if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
5636       BitcastVT.getVectorElementType() == MVT::i1)
5637     return false;
5638 
5639   if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
5640     return false;
5641 
5642   // If both types are legal vectors, it's always ok to convert them.
5643   if (LoadVT.isVector() && BitcastVT.isVector() &&
5644       isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
5645     return true;
5646 
5647   return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
5648 }
5649 
5650 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
5651                                          const MachineFunction &MF) const {
5652   // Do not merge to float value size (128 bytes) if no implicit
5653   // float attribute is set.
5654   bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
5655 
5656   if (NoFloat) {
5657     unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
5658     return (MemVT.getSizeInBits() <= MaxIntSize);
5659   }
5660   // Make sure we don't merge greater than our preferred vector
5661   // width.
5662   if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
5663     return false;
5664 
5665   return true;
5666 }
5667 
5668 bool X86TargetLowering::isCtlzFast() const {
5669   return Subtarget.hasFastLZCNT();
5670 }
5671 
5672 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
5673     const Instruction &AndI) const {
5674   return true;
5675 }
5676 
5677 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
5678   EVT VT = Y.getValueType();
5679 
5680   if (VT.isVector())
5681     return false;
5682 
5683   if (!Subtarget.hasBMI())
5684     return false;
5685 
5686   // There are only 32-bit and 64-bit forms for 'andn'.
5687   if (VT != MVT::i32 && VT != MVT::i64)
5688     return false;
5689 
5690   return !isa<ConstantSDNode>(Y);
5691 }
5692 
5693 bool X86TargetLowering::hasAndNot(SDValue Y) const {
5694   EVT VT = Y.getValueType();
5695 
5696   if (!VT.isVector())
5697     return hasAndNotCompare(Y);
5698 
5699   // Vector.
5700 
5701   if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
5702     return false;
5703 
5704   if (VT == MVT::v4i32)
5705     return true;
5706 
5707   return Subtarget.hasSSE2();
5708 }
5709 
5710 bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
5711   return X.getValueType().isScalarInteger(); // 'bt'
5712 }
5713 
5714 bool X86TargetLowering::
5715     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5716         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
5717         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
5718         SelectionDAG &DAG) const {
5719   // Does baseline recommend not to perform the fold by default?
5720   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5721           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
5722     return false;
5723   // For scalars this transform is always beneficial.
5724   if (X.getValueType().isScalarInteger())
5725     return true;
5726   // If all the shift amounts are identical, then transform is beneficial even
5727   // with rudimentary SSE2 shifts.
5728   if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
5729     return true;
5730   // If we have AVX2 with it's powerful shift operations, then it's also good.
5731   if (Subtarget.hasAVX2())
5732     return true;
5733   // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
5734   return NewShiftOpcode == ISD::SHL;
5735 }
5736 
5737 bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
5738     const SDNode *N, CombineLevel Level) const {
5739   assert(((N->getOpcode() == ISD::SHL &&
5740            N->getOperand(0).getOpcode() == ISD::SRL) ||
5741           (N->getOpcode() == ISD::SRL &&
5742            N->getOperand(0).getOpcode() == ISD::SHL)) &&
5743          "Expected shift-shift mask");
5744   EVT VT = N->getValueType(0);
5745   if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
5746       (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
5747     // Only fold if the shift values are equal - so it folds to AND.
5748     // TODO - we should fold if either is a non-uniform vector but we don't do
5749     // the fold for non-splats yet.
5750     return N->getOperand(1) == N->getOperand(0).getOperand(1);
5751   }
5752   return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
5753 }
5754 
5755 bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
5756   EVT VT = Y.getValueType();
5757 
5758   // For vectors, we don't have a preference, but we probably want a mask.
5759   if (VT.isVector())
5760     return false;
5761 
5762   // 64-bit shifts on 32-bit targets produce really bad bloated code.
5763   if (VT == MVT::i64 && !Subtarget.is64Bit())
5764     return false;
5765 
5766   return true;
5767 }
5768 
5769 bool X86TargetLowering::shouldExpandShift(SelectionDAG &DAG,
5770                                           SDNode *N) const {
5771   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
5772       !Subtarget.isOSWindows())
5773     return false;
5774   return true;
5775 }
5776 
5777 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5778   // Any legal vector type can be splatted more efficiently than
5779   // loading/spilling from memory.
5780   return isTypeLegal(VT);
5781 }
5782 
5783 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
5784   MVT VT = MVT::getIntegerVT(NumBits);
5785   if (isTypeLegal(VT))
5786     return VT;
5787 
5788   // PMOVMSKB can handle this.
5789   if (NumBits == 128 && isTypeLegal(MVT::v16i8))
5790     return MVT::v16i8;
5791 
5792   // VPMOVMSKB can handle this.
5793   if (NumBits == 256 && isTypeLegal(MVT::v32i8))
5794     return MVT::v32i8;
5795 
5796   // TODO: Allow 64-bit type for 32-bit target.
5797   // TODO: 512-bit types should be allowed, but make sure that those
5798   // cases are handled in combineVectorSizedSetCCEquality().
5799 
5800   return MVT::INVALID_SIMPLE_VALUE_TYPE;
5801 }
5802 
5803 /// Val is the undef sentinel value or equal to the specified value.
5804 static bool isUndefOrEqual(int Val, int CmpVal) {
5805   return ((Val == SM_SentinelUndef) || (Val == CmpVal));
5806 }
5807 
5808 /// Return true if every element in Mask is the undef sentinel value or equal to
5809 /// the specified value..
5810 static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
5811   return llvm::all_of(Mask, [CmpVal](int M) {
5812     return (M == SM_SentinelUndef) || (M == CmpVal);
5813   });
5814 }
5815 
5816 /// Val is either the undef or zero sentinel value.
5817 static bool isUndefOrZero(int Val) {
5818   return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
5819 }
5820 
5821 /// Return true if every element in Mask, beginning from position Pos and ending
5822 /// in Pos+Size is the undef sentinel value.
5823 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
5824   return llvm::all_of(Mask.slice(Pos, Size),
5825                       [](int M) { return M == SM_SentinelUndef; });
5826 }
5827 
5828 /// Return true if the mask creates a vector whose lower half is undefined.
5829 static bool isUndefLowerHalf(ArrayRef<int> Mask) {
5830   unsigned NumElts = Mask.size();
5831   return isUndefInRange(Mask, 0, NumElts / 2);
5832 }
5833 
5834 /// Return true if the mask creates a vector whose upper half is undefined.
5835 static bool isUndefUpperHalf(ArrayRef<int> Mask) {
5836   unsigned NumElts = Mask.size();
5837   return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
5838 }
5839 
5840 /// Return true if Val falls within the specified range (L, H].
5841 static bool isInRange(int Val, int Low, int Hi) {
5842   return (Val >= Low && Val < Hi);
5843 }
5844 
5845 /// Return true if the value of any element in Mask falls within the specified
5846 /// range (L, H].
5847 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
5848   return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
5849 }
5850 
5851 /// Return true if the value of any element in Mask is the zero sentinel value.
5852 static bool isAnyZero(ArrayRef<int> Mask) {
5853   return llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
5854 }
5855 
5856 /// Return true if the value of any element in Mask is the zero or undef
5857 /// sentinel values.
5858 static bool isAnyZeroOrUndef(ArrayRef<int> Mask) {
5859   return llvm::any_of(Mask, [](int M) {
5860     return M == SM_SentinelZero || M == SM_SentinelUndef;
5861   });
5862 }
5863 
5864 /// Return true if Val is undef or if its value falls within the
5865 /// specified range (L, H].
5866 static bool isUndefOrInRange(int Val, int Low, int Hi) {
5867   return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
5868 }
5869 
5870 /// Return true if every element in Mask is undef or if its value
5871 /// falls within the specified range (L, H].
5872 static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5873   return llvm::all_of(
5874       Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
5875 }
5876 
5877 /// Return true if Val is undef, zero or if its value falls within the
5878 /// specified range (L, H].
5879 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
5880   return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
5881 }
5882 
5883 /// Return true if every element in Mask is undef, zero or if its value
5884 /// falls within the specified range (L, H].
5885 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5886   return llvm::all_of(
5887       Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
5888 }
5889 
5890 /// Return true if every element in Mask, beginning
5891 /// from position Pos and ending in Pos + Size, falls within the specified
5892 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
5893 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
5894                                        unsigned Size, int Low, int Step = 1) {
5895   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5896     if (!isUndefOrEqual(Mask[i], Low))
5897       return false;
5898   return true;
5899 }
5900 
5901 /// Return true if every element in Mask, beginning
5902 /// from position Pos and ending in Pos+Size, falls within the specified
5903 /// sequential range (Low, Low+Size], or is undef or is zero.
5904 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5905                                              unsigned Size, int Low,
5906                                              int Step = 1) {
5907   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5908     if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
5909       return false;
5910   return true;
5911 }
5912 
5913 /// Return true if every element in Mask, beginning
5914 /// from position Pos and ending in Pos+Size is undef or is zero.
5915 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5916                                  unsigned Size) {
5917   return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
5918 }
5919 
5920 /// Helper function to test whether a shuffle mask could be
5921 /// simplified by widening the elements being shuffled.
5922 ///
5923 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
5924 /// leaves it in an unspecified state.
5925 ///
5926 /// NOTE: This must handle normal vector shuffle masks and *target* vector
5927 /// shuffle masks. The latter have the special property of a '-2' representing
5928 /// a zero-ed lane of a vector.
5929 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5930                                     SmallVectorImpl<int> &WidenedMask) {
5931   WidenedMask.assign(Mask.size() / 2, 0);
5932   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
5933     int M0 = Mask[i];
5934     int M1 = Mask[i + 1];
5935 
5936     // If both elements are undef, its trivial.
5937     if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
5938       WidenedMask[i / 2] = SM_SentinelUndef;
5939       continue;
5940     }
5941 
5942     // Check for an undef mask and a mask value properly aligned to fit with
5943     // a pair of values. If we find such a case, use the non-undef mask's value.
5944     if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
5945       WidenedMask[i / 2] = M1 / 2;
5946       continue;
5947     }
5948     if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
5949       WidenedMask[i / 2] = M0 / 2;
5950       continue;
5951     }
5952 
5953     // When zeroing, we need to spread the zeroing across both lanes to widen.
5954     if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
5955       if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
5956           (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
5957         WidenedMask[i / 2] = SM_SentinelZero;
5958         continue;
5959       }
5960       return false;
5961     }
5962 
5963     // Finally check if the two mask values are adjacent and aligned with
5964     // a pair.
5965     if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
5966       WidenedMask[i / 2] = M0 / 2;
5967       continue;
5968     }
5969 
5970     // Otherwise we can't safely widen the elements used in this shuffle.
5971     return false;
5972   }
5973   assert(WidenedMask.size() == Mask.size() / 2 &&
5974          "Incorrect size of mask after widening the elements!");
5975 
5976   return true;
5977 }
5978 
5979 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5980                                     const APInt &Zeroable,
5981                                     bool V2IsZero,
5982                                     SmallVectorImpl<int> &WidenedMask) {
5983   // Create an alternative mask with info about zeroable elements.
5984   // Here we do not set undef elements as zeroable.
5985   SmallVector<int, 64> ZeroableMask(Mask.begin(), Mask.end());
5986   if (V2IsZero) {
5987     assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
5988     for (int i = 0, Size = Mask.size(); i != Size; ++i)
5989       if (Mask[i] != SM_SentinelUndef && Zeroable[i])
5990         ZeroableMask[i] = SM_SentinelZero;
5991   }
5992   return canWidenShuffleElements(ZeroableMask, WidenedMask);
5993 }
5994 
5995 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
5996   SmallVector<int, 32> WidenedMask;
5997   return canWidenShuffleElements(Mask, WidenedMask);
5998 }
5999 
6000 // Attempt to narrow/widen shuffle mask until it matches the target number of
6001 // elements.
6002 static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
6003                                  SmallVectorImpl<int> &ScaledMask) {
6004   unsigned NumSrcElts = Mask.size();
6005   assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
6006          "Illegal shuffle scale factor");
6007 
6008   // Narrowing is guaranteed to work.
6009   if (NumDstElts >= NumSrcElts) {
6010     int Scale = NumDstElts / NumSrcElts;
6011     llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
6012     return true;
6013   }
6014 
6015   // We have to repeat the widening until we reach the target size, but we can
6016   // split out the first widening as it sets up ScaledMask for us.
6017   if (canWidenShuffleElements(Mask, ScaledMask)) {
6018     while (ScaledMask.size() > NumDstElts) {
6019       SmallVector<int, 16> WidenedMask;
6020       if (!canWidenShuffleElements(ScaledMask, WidenedMask))
6021         return false;
6022       ScaledMask = std::move(WidenedMask);
6023     }
6024     return true;
6025   }
6026 
6027   return false;
6028 }
6029 
6030 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
6031 bool X86::isZeroNode(SDValue Elt) {
6032   return isNullConstant(Elt) || isNullFPConstant(Elt);
6033 }
6034 
6035 // Build a vector of constants.
6036 // Use an UNDEF node if MaskElt == -1.
6037 // Split 64-bit constants in the 32-bit mode.
6038 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
6039                               const SDLoc &dl, bool IsMask = false) {
6040 
6041   SmallVector<SDValue, 32>  Ops;
6042   bool Split = false;
6043 
6044   MVT ConstVecVT = VT;
6045   unsigned NumElts = VT.getVectorNumElements();
6046   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
6047   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
6048     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
6049     Split = true;
6050   }
6051 
6052   MVT EltVT = ConstVecVT.getVectorElementType();
6053   for (unsigned i = 0; i < NumElts; ++i) {
6054     bool IsUndef = Values[i] < 0 && IsMask;
6055     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
6056       DAG.getConstant(Values[i], dl, EltVT);
6057     Ops.push_back(OpNode);
6058     if (Split)
6059       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
6060                     DAG.getConstant(0, dl, EltVT));
6061   }
6062   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
6063   if (Split)
6064     ConstsNode = DAG.getBitcast(VT, ConstsNode);
6065   return ConstsNode;
6066 }
6067 
6068 static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
6069                               MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6070   assert(Bits.size() == Undefs.getBitWidth() &&
6071          "Unequal constant and undef arrays");
6072   SmallVector<SDValue, 32> Ops;
6073   bool Split = false;
6074 
6075   MVT ConstVecVT = VT;
6076   unsigned NumElts = VT.getVectorNumElements();
6077   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
6078   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
6079     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
6080     Split = true;
6081   }
6082 
6083   MVT EltVT = ConstVecVT.getVectorElementType();
6084   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
6085     if (Undefs[i]) {
6086       Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
6087       continue;
6088     }
6089     const APInt &V = Bits[i];
6090     assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
6091     if (Split) {
6092       Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
6093       Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
6094     } else if (EltVT == MVT::f32) {
6095       APFloat FV(APFloat::IEEEsingle(), V);
6096       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
6097     } else if (EltVT == MVT::f64) {
6098       APFloat FV(APFloat::IEEEdouble(), V);
6099       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
6100     } else {
6101       Ops.push_back(DAG.getConstant(V, dl, EltVT));
6102     }
6103   }
6104 
6105   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
6106   return DAG.getBitcast(VT, ConstsNode);
6107 }
6108 
6109 /// Returns a vector of specified type with all zero elements.
6110 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
6111                              SelectionDAG &DAG, const SDLoc &dl) {
6112   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
6113           VT.getVectorElementType() == MVT::i1) &&
6114          "Unexpected vector type");
6115 
6116   // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
6117   // type. This ensures they get CSE'd. But if the integer type is not
6118   // available, use a floating-point +0.0 instead.
6119   SDValue Vec;
6120   if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
6121     Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
6122   } else if (VT.isFloatingPoint()) {
6123     Vec = DAG.getConstantFP(+0.0, dl, VT);
6124   } else if (VT.getVectorElementType() == MVT::i1) {
6125     assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
6126            "Unexpected vector type");
6127     Vec = DAG.getConstant(0, dl, VT);
6128   } else {
6129     unsigned Num32BitElts = VT.getSizeInBits() / 32;
6130     Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
6131   }
6132   return DAG.getBitcast(VT, Vec);
6133 }
6134 
6135 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
6136                                 const SDLoc &dl, unsigned vectorWidth) {
6137   EVT VT = Vec.getValueType();
6138   EVT ElVT = VT.getVectorElementType();
6139   unsigned Factor = VT.getSizeInBits() / vectorWidth;
6140   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
6141                                   VT.getVectorNumElements() / Factor);
6142 
6143   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
6144   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
6145   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
6146 
6147   // This is the index of the first element of the vectorWidth-bit chunk
6148   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
6149   IdxVal &= ~(ElemsPerChunk - 1);
6150 
6151   // If the input is a buildvector just emit a smaller one.
6152   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
6153     return DAG.getBuildVector(ResultVT, dl,
6154                               Vec->ops().slice(IdxVal, ElemsPerChunk));
6155 
6156   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
6157   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
6158 }
6159 
6160 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
6161 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
6162 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
6163 /// instructions or a simple subregister reference. Idx is an index in the
6164 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
6165 /// lowering EXTRACT_VECTOR_ELT operations easier.
6166 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
6167                                    SelectionDAG &DAG, const SDLoc &dl) {
6168   assert((Vec.getValueType().is256BitVector() ||
6169           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
6170   return extractSubVector(Vec, IdxVal, DAG, dl, 128);
6171 }
6172 
6173 /// Generate a DAG to grab 256-bits from a 512-bit vector.
6174 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
6175                                    SelectionDAG &DAG, const SDLoc &dl) {
6176   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
6177   return extractSubVector(Vec, IdxVal, DAG, dl, 256);
6178 }
6179 
6180 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
6181                                SelectionDAG &DAG, const SDLoc &dl,
6182                                unsigned vectorWidth) {
6183   assert((vectorWidth == 128 || vectorWidth == 256) &&
6184          "Unsupported vector width");
6185   // Inserting UNDEF is Result
6186   if (Vec.isUndef())
6187     return Result;
6188   EVT VT = Vec.getValueType();
6189   EVT ElVT = VT.getVectorElementType();
6190   EVT ResultVT = Result.getValueType();
6191 
6192   // Insert the relevant vectorWidth bits.
6193   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
6194   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
6195 
6196   // This is the index of the first element of the vectorWidth-bit chunk
6197   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
6198   IdxVal &= ~(ElemsPerChunk - 1);
6199 
6200   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
6201   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
6202 }
6203 
6204 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
6205 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
6206 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
6207 /// simple superregister reference.  Idx is an index in the 128 bits
6208 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
6209 /// lowering INSERT_VECTOR_ELT operations easier.
6210 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
6211                                   SelectionDAG &DAG, const SDLoc &dl) {
6212   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
6213   return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
6214 }
6215 
6216 /// Widen a vector to a larger size with the same scalar type, with the new
6217 /// elements either zero or undef.
6218 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
6219                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
6220                               const SDLoc &dl) {
6221   assert(Vec.getValueSizeInBits().getFixedSize() < VT.getFixedSizeInBits() &&
6222          Vec.getValueType().getScalarType() == VT.getScalarType() &&
6223          "Unsupported vector widening type");
6224   SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
6225                                 : DAG.getUNDEF(VT);
6226   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
6227                      DAG.getIntPtrConstant(0, dl));
6228 }
6229 
6230 /// Widen a vector to a larger size with the same scalar type, with the new
6231 /// elements either zero or undef.
6232 static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
6233                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
6234                               const SDLoc &dl, unsigned WideSizeInBits) {
6235   assert(Vec.getValueSizeInBits() < WideSizeInBits &&
6236          (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
6237          "Unsupported vector widening type");
6238   unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
6239   MVT SVT = Vec.getSimpleValueType().getScalarType();
6240   MVT VT = MVT::getVectorVT(SVT, WideNumElts);
6241   return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
6242 }
6243 
6244 // Helper function to collect subvector ops that are concatenated together,
6245 // either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
6246 // The subvectors in Ops are guaranteed to be the same type.
6247 static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops) {
6248   assert(Ops.empty() && "Expected an empty ops vector");
6249 
6250   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
6251     Ops.append(N->op_begin(), N->op_end());
6252     return true;
6253   }
6254 
6255   if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
6256     SDValue Src = N->getOperand(0);
6257     SDValue Sub = N->getOperand(1);
6258     const APInt &Idx = N->getConstantOperandAPInt(2);
6259     EVT VT = Src.getValueType();
6260     EVT SubVT = Sub.getValueType();
6261 
6262     // TODO - Handle more general insert_subvector chains.
6263     if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2) &&
6264         Idx == (VT.getVectorNumElements() / 2)) {
6265       // insert_subvector(insert_subvector(undef, x, lo), y, hi)
6266       if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6267           Src.getOperand(1).getValueType() == SubVT &&
6268           isNullConstant(Src.getOperand(2))) {
6269         Ops.push_back(Src.getOperand(1));
6270         Ops.push_back(Sub);
6271         return true;
6272       }
6273       // insert_subvector(x, extract_subvector(x, lo), hi)
6274       if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6275           Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
6276         Ops.append(2, Sub);
6277         return true;
6278       }
6279     }
6280   }
6281 
6282   return false;
6283 }
6284 
6285 static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
6286                                                const SDLoc &dl) {
6287   EVT VT = Op.getValueType();
6288   unsigned NumElems = VT.getVectorNumElements();
6289   unsigned SizeInBits = VT.getSizeInBits();
6290   assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
6291          "Can't split odd sized vector");
6292 
6293   // If this is a splat value (with no-undefs) then use the lower subvector,
6294   // which should be a free extraction.
6295   SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
6296   if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
6297     return std::make_pair(Lo, Lo);
6298 
6299   SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
6300   return std::make_pair(Lo, Hi);
6301 }
6302 
6303 /// Break an operation into 2 half sized ops and then concatenate the results.
6304 static SDValue splitVectorOp(SDValue Op, SelectionDAG &DAG) {
6305   unsigned NumOps = Op.getNumOperands();
6306   EVT VT = Op.getValueType();
6307   SDLoc dl(Op);
6308 
6309   // Extract the LHS Lo/Hi vectors
6310   SmallVector<SDValue> LoOps(NumOps, SDValue());
6311   SmallVector<SDValue> HiOps(NumOps, SDValue());
6312   for (unsigned I = 0; I != NumOps; ++I) {
6313     SDValue SrcOp = Op.getOperand(I);
6314     if (!SrcOp.getValueType().isVector()) {
6315       LoOps[I] = HiOps[I] = SrcOp;
6316       continue;
6317     }
6318     std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
6319   }
6320 
6321   EVT LoVT, HiVT;
6322   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6323   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
6324                      DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
6325                      DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
6326 }
6327 
6328 /// Break an unary integer operation into 2 half sized ops and then
6329 /// concatenate the result back.
6330 static SDValue splitVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
6331   // Make sure we only try to split 256/512-bit types to avoid creating
6332   // narrow vectors.
6333   EVT VT = Op.getValueType();
6334   (void)VT;
6335   assert((Op.getOperand(0).getValueType().is256BitVector() ||
6336           Op.getOperand(0).getValueType().is512BitVector()) &&
6337          (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
6338   assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
6339              VT.getVectorNumElements() &&
6340          "Unexpected VTs!");
6341   return splitVectorOp(Op, DAG);
6342 }
6343 
6344 /// Break a binary integer operation into 2 half sized ops and then
6345 /// concatenate the result back.
6346 static SDValue splitVectorIntBinary(SDValue Op, SelectionDAG &DAG) {
6347   // Assert that all the types match.
6348   EVT VT = Op.getValueType();
6349   (void)VT;
6350   assert(Op.getOperand(0).getValueType() == VT &&
6351          Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
6352   assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
6353   return splitVectorOp(Op, DAG);
6354 }
6355 
6356 // Helper for splitting operands of an operation to legal target size and
6357 // apply a function on each part.
6358 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
6359 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
6360 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
6361 // The argument Builder is a function that will be applied on each split part:
6362 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
6363 template <typename F>
6364 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
6365                          const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
6366                          F Builder, bool CheckBWI = true) {
6367   assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
6368   unsigned NumSubs = 1;
6369   if ((CheckBWI && Subtarget.useBWIRegs()) ||
6370       (!CheckBWI && Subtarget.useAVX512Regs())) {
6371     if (VT.getSizeInBits() > 512) {
6372       NumSubs = VT.getSizeInBits() / 512;
6373       assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
6374     }
6375   } else if (Subtarget.hasAVX2()) {
6376     if (VT.getSizeInBits() > 256) {
6377       NumSubs = VT.getSizeInBits() / 256;
6378       assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
6379     }
6380   } else {
6381     if (VT.getSizeInBits() > 128) {
6382       NumSubs = VT.getSizeInBits() / 128;
6383       assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
6384     }
6385   }
6386 
6387   if (NumSubs == 1)
6388     return Builder(DAG, DL, Ops);
6389 
6390   SmallVector<SDValue, 4> Subs;
6391   for (unsigned i = 0; i != NumSubs; ++i) {
6392     SmallVector<SDValue, 2> SubOps;
6393     for (SDValue Op : Ops) {
6394       EVT OpVT = Op.getValueType();
6395       unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
6396       unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
6397       SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
6398     }
6399     Subs.push_back(Builder(DAG, DL, SubOps));
6400   }
6401   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
6402 }
6403 
6404 // Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
6405 // targets.
6406 static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
6407                              ArrayRef<SDValue> Ops, SelectionDAG &DAG,
6408                              const X86Subtarget &Subtarget) {
6409   assert(Subtarget.hasAVX512() && "AVX512 target expected");
6410   MVT SVT = VT.getScalarType();
6411 
6412   // If we have a 32/64 splatted constant, splat it to DstTy to
6413   // encourage a foldable broadcast'd operand.
6414   auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
6415     unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
6416     // AVX512 broadcasts 32/64-bit operands.
6417     // TODO: Support float once getAVX512Node is used by fp-ops.
6418     if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
6419         !DAG.getTargetLoweringInfo().isTypeLegal(SVT))
6420       return SDValue();
6421     // If we're not widening, don't bother if we're not bitcasting.
6422     if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
6423       return SDValue();
6424     if (auto *BV = dyn_cast<BuildVectorSDNode>(peekThroughBitcasts(Op))) {
6425       APInt SplatValue, SplatUndef;
6426       unsigned SplatBitSize;
6427       bool HasAnyUndefs;
6428       if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6429                               HasAnyUndefs, OpEltSizeInBits) &&
6430           !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
6431         return DAG.getConstant(SplatValue, DL, DstVT);
6432     }
6433     return SDValue();
6434   };
6435 
6436   bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
6437 
6438   MVT DstVT = VT;
6439   if (Widen)
6440     DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
6441 
6442   // Canonicalize src operands.
6443   SmallVector<SDValue> SrcOps(Ops.begin(), Ops.end());
6444   for (SDValue &Op : SrcOps) {
6445     MVT OpVT = Op.getSimpleValueType();
6446     // Just pass through scalar operands.
6447     if (!OpVT.isVector())
6448       continue;
6449     assert(OpVT == VT && "Vector type mismatch");
6450 
6451     if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
6452       Op = BroadcastOp;
6453       continue;
6454     }
6455 
6456     // Just widen the subvector by inserting into an undef wide vector.
6457     if (Widen)
6458       Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
6459   }
6460 
6461   SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
6462 
6463   // Perform the 512-bit op then extract the bottom subvector.
6464   if (Widen)
6465     Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
6466   return Res;
6467 }
6468 
6469 /// Insert i1-subvector to i1-vector.
6470 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
6471                                 const X86Subtarget &Subtarget) {
6472 
6473   SDLoc dl(Op);
6474   SDValue Vec = Op.getOperand(0);
6475   SDValue SubVec = Op.getOperand(1);
6476   SDValue Idx = Op.getOperand(2);
6477   unsigned IdxVal = Op.getConstantOperandVal(2);
6478 
6479   // Inserting undef is a nop. We can just return the original vector.
6480   if (SubVec.isUndef())
6481     return Vec;
6482 
6483   if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
6484     return Op;
6485 
6486   MVT OpVT = Op.getSimpleValueType();
6487   unsigned NumElems = OpVT.getVectorNumElements();
6488   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6489 
6490   // Extend to natively supported kshift.
6491   MVT WideOpVT = OpVT;
6492   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
6493     WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
6494 
6495   // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
6496   // if necessary.
6497   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
6498     // May need to promote to a legal type.
6499     Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6500                      DAG.getConstant(0, dl, WideOpVT),
6501                      SubVec, Idx);
6502     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6503   }
6504 
6505   MVT SubVecVT = SubVec.getSimpleValueType();
6506   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
6507   assert(IdxVal + SubVecNumElems <= NumElems &&
6508          IdxVal % SubVecVT.getSizeInBits() == 0 &&
6509          "Unexpected index value in INSERT_SUBVECTOR");
6510 
6511   SDValue Undef = DAG.getUNDEF(WideOpVT);
6512 
6513   if (IdxVal == 0) {
6514     // Zero lower bits of the Vec
6515     SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
6516     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
6517                       ZeroIdx);
6518     Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6519     Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6520     // Merge them together, SubVec should be zero extended.
6521     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6522                          DAG.getConstant(0, dl, WideOpVT),
6523                          SubVec, ZeroIdx);
6524     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6525     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6526   }
6527 
6528   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6529                        Undef, SubVec, ZeroIdx);
6530 
6531   if (Vec.isUndef()) {
6532     assert(IdxVal != 0 && "Unexpected index");
6533     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6534                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6535     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6536   }
6537 
6538   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
6539     assert(IdxVal != 0 && "Unexpected index");
6540     // If upper elements of Vec are known undef, then just shift into place.
6541     if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
6542                      [](SDValue V) { return V.isUndef(); })) {
6543       SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6544                            DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6545     } else {
6546       NumElems = WideOpVT.getVectorNumElements();
6547       unsigned ShiftLeft = NumElems - SubVecNumElems;
6548       unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6549       SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6550                            DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6551       if (ShiftRight != 0)
6552         SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6553                              DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6554     }
6555     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6556   }
6557 
6558   // Simple case when we put subvector in the upper part
6559   if (IdxVal + SubVecNumElems == NumElems) {
6560     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6561                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6562     if (SubVecNumElems * 2 == NumElems) {
6563       // Special case, use legal zero extending insert_subvector. This allows
6564       // isel to optimize when bits are known zero.
6565       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
6566       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6567                         DAG.getConstant(0, dl, WideOpVT),
6568                         Vec, ZeroIdx);
6569     } else {
6570       // Otherwise use explicit shifts to zero the bits.
6571       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6572                         Undef, Vec, ZeroIdx);
6573       NumElems = WideOpVT.getVectorNumElements();
6574       SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
6575       Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6576       Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6577     }
6578     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6579     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6580   }
6581 
6582   // Inserting into the middle is more complicated.
6583 
6584   NumElems = WideOpVT.getVectorNumElements();
6585 
6586   // Widen the vector if needed.
6587   Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
6588 
6589   unsigned ShiftLeft = NumElems - SubVecNumElems;
6590   unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6591 
6592   // Do an optimization for the the most frequently used types.
6593   if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
6594     APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
6595     Mask0.flipAllBits();
6596     SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
6597     SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
6598     Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
6599     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6600                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6601     SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6602                          DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6603     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6604 
6605     // Reduce to original width if needed.
6606     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6607   }
6608 
6609   // Clear the upper bits of the subvector and move it to its insert position.
6610   SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6611                        DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6612   SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6613                        DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6614 
6615   // Isolate the bits below the insertion point.
6616   unsigned LowShift = NumElems - IdxVal;
6617   SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
6618                             DAG.getTargetConstant(LowShift, dl, MVT::i8));
6619   Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
6620                     DAG.getTargetConstant(LowShift, dl, MVT::i8));
6621 
6622   // Isolate the bits after the last inserted bit.
6623   unsigned HighShift = IdxVal + SubVecNumElems;
6624   SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
6625                             DAG.getTargetConstant(HighShift, dl, MVT::i8));
6626   High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
6627                     DAG.getTargetConstant(HighShift, dl, MVT::i8));
6628 
6629   // Now OR all 3 pieces together.
6630   Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
6631   SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
6632 
6633   // Reduce to original width if needed.
6634   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6635 }
6636 
6637 static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
6638                                 const SDLoc &dl) {
6639   assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
6640   EVT SubVT = V1.getValueType();
6641   EVT SubSVT = SubVT.getScalarType();
6642   unsigned SubNumElts = SubVT.getVectorNumElements();
6643   unsigned SubVectorWidth = SubVT.getSizeInBits();
6644   EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
6645   SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
6646   return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
6647 }
6648 
6649 /// Returns a vector of specified type with all bits set.
6650 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
6651 /// Then bitcast to their original type, ensuring they get CSE'd.
6652 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6653   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6654          "Expected a 128/256/512-bit vector type");
6655 
6656   APInt Ones = APInt::getAllOnes(32);
6657   unsigned NumElts = VT.getSizeInBits() / 32;
6658   SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
6659   return DAG.getBitcast(VT, Vec);
6660 }
6661 
6662 // Convert *_EXTEND_VECTOR_INREG to *_EXTEND opcode.
6663 static unsigned getOpcode_EXTEND(unsigned Opcode) {
6664   switch (Opcode) {
6665   case ISD::ANY_EXTEND:
6666   case ISD::ANY_EXTEND_VECTOR_INREG:
6667     return ISD::ANY_EXTEND;
6668   case ISD::ZERO_EXTEND:
6669   case ISD::ZERO_EXTEND_VECTOR_INREG:
6670     return ISD::ZERO_EXTEND;
6671   case ISD::SIGN_EXTEND:
6672   case ISD::SIGN_EXTEND_VECTOR_INREG:
6673     return ISD::SIGN_EXTEND;
6674   }
6675   llvm_unreachable("Unknown opcode");
6676 }
6677 
6678 // Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
6679 static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
6680   switch (Opcode) {
6681   case ISD::ANY_EXTEND:
6682   case ISD::ANY_EXTEND_VECTOR_INREG:
6683     return ISD::ANY_EXTEND_VECTOR_INREG;
6684   case ISD::ZERO_EXTEND:
6685   case ISD::ZERO_EXTEND_VECTOR_INREG:
6686     return ISD::ZERO_EXTEND_VECTOR_INREG;
6687   case ISD::SIGN_EXTEND:
6688   case ISD::SIGN_EXTEND_VECTOR_INREG:
6689     return ISD::SIGN_EXTEND_VECTOR_INREG;
6690   }
6691   llvm_unreachable("Unknown opcode");
6692 }
6693 
6694 static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
6695                                       SDValue In, SelectionDAG &DAG) {
6696   EVT InVT = In.getValueType();
6697   assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
6698   assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
6699           ISD::ZERO_EXTEND == Opcode) &&
6700          "Unknown extension opcode");
6701 
6702   // For 256-bit vectors, we only need the lower (128-bit) input half.
6703   // For 512-bit vectors, we only need the lower input half or quarter.
6704   if (InVT.getSizeInBits() > 128) {
6705     assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
6706            "Expected VTs to be the same size!");
6707     unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
6708     In = extractSubVector(In, 0, DAG, DL,
6709                           std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
6710     InVT = In.getValueType();
6711   }
6712 
6713   if (VT.getVectorNumElements() != InVT.getVectorNumElements())
6714     Opcode = getOpcode_EXTEND_VECTOR_INREG(Opcode);
6715 
6716   return DAG.getNode(Opcode, DL, VT, In);
6717 }
6718 
6719 // Match (xor X, -1) -> X.
6720 // Match extract_subvector(xor X, -1) -> extract_subvector(X).
6721 // Match concat_vectors(xor X, -1, xor Y, -1) -> concat_vectors(X, Y).
6722 static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
6723   V = peekThroughBitcasts(V);
6724   if (V.getOpcode() == ISD::XOR &&
6725       ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()))
6726     return V.getOperand(0);
6727   if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6728       (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
6729     if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
6730       Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
6731       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
6732                          Not, V.getOperand(1));
6733     }
6734   }
6735   SmallVector<SDValue, 2> CatOps;
6736   if (collectConcatOps(V.getNode(), CatOps)) {
6737     for (SDValue &CatOp : CatOps) {
6738       SDValue NotCat = IsNOT(CatOp, DAG);
6739       if (!NotCat) return SDValue();
6740       CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
6741     }
6742     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), V.getValueType(), CatOps);
6743   }
6744   return SDValue();
6745 }
6746 
6747 void llvm::createUnpackShuffleMask(EVT VT, SmallVectorImpl<int> &Mask,
6748                                    bool Lo, bool Unary) {
6749   assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
6750          "Illegal vector type to unpack");
6751   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6752   int NumElts = VT.getVectorNumElements();
6753   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6754   for (int i = 0; i < NumElts; ++i) {
6755     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6756     int Pos = (i % NumEltsInLane) / 2 + LaneStart;
6757     Pos += (Unary ? 0 : NumElts * (i % 2));
6758     Pos += (Lo ? 0 : NumEltsInLane / 2);
6759     Mask.push_back(Pos);
6760   }
6761 }
6762 
6763 /// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
6764 /// imposed by AVX and specific to the unary pattern. Example:
6765 /// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
6766 /// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
6767 void llvm::createSplat2ShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6768                                    bool Lo) {
6769   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6770   int NumElts = VT.getVectorNumElements();
6771   for (int i = 0; i < NumElts; ++i) {
6772     int Pos = i / 2;
6773     Pos += (Lo ? 0 : NumElts / 2);
6774     Mask.push_back(Pos);
6775   }
6776 }
6777 
6778 // Attempt to constant fold, else just create a VECTOR_SHUFFLE.
6779 static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
6780                                 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
6781   if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
6782       (ISD::isBuildVectorOfConstantSDNodes(V2.getNode()) || V2.isUndef())) {
6783     SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
6784     for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
6785       int M = Mask[I];
6786       if (M < 0)
6787         continue;
6788       SDValue V = (M < NumElts) ? V1 : V2;
6789       if (V.isUndef())
6790         continue;
6791       Ops[I] = V.getOperand(M % NumElts);
6792     }
6793     return DAG.getBuildVector(VT, dl, Ops);
6794   }
6795 
6796   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6797 }
6798 
6799 /// Returns a vector_shuffle node for an unpackl operation.
6800 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
6801                           SDValue V1, SDValue V2) {
6802   SmallVector<int, 8> Mask;
6803   createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
6804   return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
6805 }
6806 
6807 /// Returns a vector_shuffle node for an unpackh operation.
6808 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
6809                           SDValue V1, SDValue V2) {
6810   SmallVector<int, 8> Mask;
6811   createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
6812   return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
6813 }
6814 
6815 /// Returns a node that packs the LHS + RHS nodes together at half width.
6816 /// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
6817 /// TODO: Add subvector splitting if/when we have a need for it.
6818 static SDValue getPack(SelectionDAG &DAG, const X86Subtarget &Subtarget,
6819                        const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
6820                        bool PackHiHalf = false) {
6821   MVT OpVT = LHS.getSimpleValueType();
6822   unsigned EltSizeInBits = VT.getScalarSizeInBits();
6823   bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
6824   assert(OpVT == RHS.getSimpleValueType() &&
6825          VT.getSizeInBits() == OpVT.getSizeInBits() &&
6826          (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
6827          "Unexpected PACK operand types");
6828   assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
6829          "Unexpected PACK result type");
6830 
6831   // Rely on vector shuffles for vXi64 -> vXi32 packing.
6832   if (EltSizeInBits == 32) {
6833     SmallVector<int> PackMask;
6834     int Offset = PackHiHalf ? 1 : 0;
6835     int NumElts = VT.getVectorNumElements();
6836     for (int I = 0; I != NumElts; I += 4) {
6837       PackMask.push_back(I + Offset);
6838       PackMask.push_back(I + Offset + 2);
6839       PackMask.push_back(I + Offset + NumElts);
6840       PackMask.push_back(I + Offset + NumElts + 2);
6841     }
6842     return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
6843                                 DAG.getBitcast(VT, RHS), PackMask);
6844   }
6845 
6846   // See if we already have sufficient leading bits for PACKSS/PACKUS.
6847   if (!PackHiHalf) {
6848     if (UsePackUS &&
6849         DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
6850         DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
6851       return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
6852 
6853     if (DAG.ComputeMinSignedBits(LHS) <= EltSizeInBits &&
6854         DAG.ComputeMinSignedBits(RHS) <= EltSizeInBits)
6855       return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
6856   }
6857 
6858   // Fallback to sign/zero extending the requested half and pack.
6859   SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
6860   if (UsePackUS) {
6861     if (PackHiHalf) {
6862       LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
6863       RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
6864     } else {
6865       SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
6866       LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
6867       RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
6868     };
6869     return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
6870   };
6871 
6872   if (!PackHiHalf) {
6873     LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
6874     RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
6875   }
6876   LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
6877   RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
6878   return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
6879 }
6880 
6881 /// Return a vector_shuffle of the specified vector of zero or undef vector.
6882 /// This produces a shuffle where the low element of V2 is swizzled into the
6883 /// zero/undef vector, landing at element Idx.
6884 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
6885 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
6886                                            bool IsZero,
6887                                            const X86Subtarget &Subtarget,
6888                                            SelectionDAG &DAG) {
6889   MVT VT = V2.getSimpleValueType();
6890   SDValue V1 = IsZero
6891     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
6892   int NumElems = VT.getVectorNumElements();
6893   SmallVector<int, 16> MaskVec(NumElems);
6894   for (int i = 0; i != NumElems; ++i)
6895     // If this is the insertion idx, put the low elt of V2 here.
6896     MaskVec[i] = (i == Idx) ? NumElems : i;
6897   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
6898 }
6899 
6900 static const Constant *getTargetConstantFromBasePtr(SDValue Ptr) {
6901   if (Ptr.getOpcode() == X86ISD::Wrapper ||
6902       Ptr.getOpcode() == X86ISD::WrapperRIP)
6903     Ptr = Ptr.getOperand(0);
6904 
6905   auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
6906   if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
6907     return nullptr;
6908 
6909   return CNode->getConstVal();
6910 }
6911 
6912 static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
6913   if (!Load || !ISD::isNormalLoad(Load))
6914     return nullptr;
6915   return getTargetConstantFromBasePtr(Load->getBasePtr());
6916 }
6917 
6918 static const Constant *getTargetConstantFromNode(SDValue Op) {
6919   Op = peekThroughBitcasts(Op);
6920   return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
6921 }
6922 
6923 const Constant *
6924 X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
6925   assert(LD && "Unexpected null LoadSDNode");
6926   return getTargetConstantFromNode(LD);
6927 }
6928 
6929 // Extract raw constant bits from constant pools.
6930 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
6931                                           APInt &UndefElts,
6932                                           SmallVectorImpl<APInt> &EltBits,
6933                                           bool AllowWholeUndefs = true,
6934                                           bool AllowPartialUndefs = true) {
6935   assert(EltBits.empty() && "Expected an empty EltBits vector");
6936 
6937   Op = peekThroughBitcasts(Op);
6938 
6939   EVT VT = Op.getValueType();
6940   unsigned SizeInBits = VT.getSizeInBits();
6941   assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
6942   unsigned NumElts = SizeInBits / EltSizeInBits;
6943 
6944   // Bitcast a source array of element bits to the target size.
6945   auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
6946     unsigned NumSrcElts = UndefSrcElts.getBitWidth();
6947     unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
6948     assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
6949            "Constant bit sizes don't match");
6950 
6951     // Don't split if we don't allow undef bits.
6952     bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
6953     if (UndefSrcElts.getBoolValue() && !AllowUndefs)
6954       return false;
6955 
6956     // If we're already the right size, don't bother bitcasting.
6957     if (NumSrcElts == NumElts) {
6958       UndefElts = UndefSrcElts;
6959       EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
6960       return true;
6961     }
6962 
6963     // Extract all the undef/constant element data and pack into single bitsets.
6964     APInt UndefBits(SizeInBits, 0);
6965     APInt MaskBits(SizeInBits, 0);
6966 
6967     for (unsigned i = 0; i != NumSrcElts; ++i) {
6968       unsigned BitOffset = i * SrcEltSizeInBits;
6969       if (UndefSrcElts[i])
6970         UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
6971       MaskBits.insertBits(SrcEltBits[i], BitOffset);
6972     }
6973 
6974     // Split the undef/constant single bitset data into the target elements.
6975     UndefElts = APInt(NumElts, 0);
6976     EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
6977 
6978     for (unsigned i = 0; i != NumElts; ++i) {
6979       unsigned BitOffset = i * EltSizeInBits;
6980       APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
6981 
6982       // Only treat an element as UNDEF if all bits are UNDEF.
6983       if (UndefEltBits.isAllOnes()) {
6984         if (!AllowWholeUndefs)
6985           return false;
6986         UndefElts.setBit(i);
6987         continue;
6988       }
6989 
6990       // If only some bits are UNDEF then treat them as zero (or bail if not
6991       // supported).
6992       if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
6993         return false;
6994 
6995       EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
6996     }
6997     return true;
6998   };
6999 
7000   // Collect constant bits and insert into mask/undef bit masks.
7001   auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
7002                                 unsigned UndefBitIndex) {
7003     if (!Cst)
7004       return false;
7005     if (isa<UndefValue>(Cst)) {
7006       Undefs.setBit(UndefBitIndex);
7007       return true;
7008     }
7009     if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
7010       Mask = CInt->getValue();
7011       return true;
7012     }
7013     if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
7014       Mask = CFP->getValueAPF().bitcastToAPInt();
7015       return true;
7016     }
7017     return false;
7018   };
7019 
7020   // Handle UNDEFs.
7021   if (Op.isUndef()) {
7022     APInt UndefSrcElts = APInt::getAllOnes(NumElts);
7023     SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
7024     return CastBitData(UndefSrcElts, SrcEltBits);
7025   }
7026 
7027   // Extract scalar constant bits.
7028   if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
7029     APInt UndefSrcElts = APInt::getZero(1);
7030     SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
7031     return CastBitData(UndefSrcElts, SrcEltBits);
7032   }
7033   if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7034     APInt UndefSrcElts = APInt::getZero(1);
7035     APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
7036     SmallVector<APInt, 64> SrcEltBits(1, RawBits);
7037     return CastBitData(UndefSrcElts, SrcEltBits);
7038   }
7039 
7040   // Extract constant bits from build vector.
7041   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
7042     BitVector Undefs;
7043     SmallVector<APInt> SrcEltBits;
7044     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7045     if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
7046       APInt UndefSrcElts = APInt::getNullValue(SrcEltBits.size());
7047       for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
7048         if (Undefs[I])
7049           UndefSrcElts.setBit(I);
7050       return CastBitData(UndefSrcElts, SrcEltBits);
7051     }
7052   }
7053 
7054   // Extract constant bits from constant pool vector.
7055   if (auto *Cst = getTargetConstantFromNode(Op)) {
7056     Type *CstTy = Cst->getType();
7057     unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
7058     if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
7059       return false;
7060 
7061     unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
7062     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7063 
7064     APInt UndefSrcElts(NumSrcElts, 0);
7065     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
7066     for (unsigned i = 0; i != NumSrcElts; ++i)
7067       if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
7068                                UndefSrcElts, i))
7069         return false;
7070 
7071     return CastBitData(UndefSrcElts, SrcEltBits);
7072   }
7073 
7074   // Extract constant bits from a broadcasted constant pool scalar.
7075   if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
7076       EltSizeInBits <= VT.getScalarSizeInBits()) {
7077     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
7078     if (MemIntr->getMemoryVT().getScalarSizeInBits() != VT.getScalarSizeInBits())
7079       return false;
7080 
7081     SDValue Ptr = MemIntr->getBasePtr();
7082     if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
7083       unsigned SrcEltSizeInBits = C->getType()->getScalarSizeInBits();
7084       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7085 
7086       APInt UndefSrcElts(NumSrcElts, 0);
7087       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
7088       if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
7089         if (UndefSrcElts[0])
7090           UndefSrcElts.setBits(0, NumSrcElts);
7091         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
7092         return CastBitData(UndefSrcElts, SrcEltBits);
7093       }
7094     }
7095   }
7096 
7097   // Extract constant bits from a subvector broadcast.
7098   if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
7099     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
7100     SDValue Ptr = MemIntr->getBasePtr();
7101     // The source constant may be larger than the subvector broadcast,
7102     // ensure we extract the correct subvector constants.
7103     if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
7104       Type *CstTy = Cst->getType();
7105       unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
7106       unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
7107       if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
7108           (SizeInBits % SubVecSizeInBits) != 0)
7109         return false;
7110       unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
7111       unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
7112       unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
7113       APInt UndefSubElts(NumSubElts, 0);
7114       SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
7115                                         APInt(CstEltSizeInBits, 0));
7116       for (unsigned i = 0; i != NumSubElts; ++i) {
7117         if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
7118                                  UndefSubElts, i))
7119           return false;
7120         for (unsigned j = 1; j != NumSubVecs; ++j)
7121           SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
7122       }
7123       UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
7124                                      UndefSubElts);
7125       return CastBitData(UndefSubElts, SubEltBits);
7126     }
7127   }
7128 
7129   // Extract a rematerialized scalar constant insertion.
7130   if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
7131       Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7132       isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
7133     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7134     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
7135 
7136     APInt UndefSrcElts(NumSrcElts, 0);
7137     SmallVector<APInt, 64> SrcEltBits;
7138     auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
7139     SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
7140     SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
7141     return CastBitData(UndefSrcElts, SrcEltBits);
7142   }
7143 
7144   // Insert constant bits from a base and sub vector sources.
7145   if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
7146     // If bitcasts to larger elements we might lose track of undefs - don't
7147     // allow any to be safe.
7148     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
7149     bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
7150 
7151     APInt UndefSrcElts, UndefSubElts;
7152     SmallVector<APInt, 32> EltSrcBits, EltSubBits;
7153     if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
7154                                       UndefSubElts, EltSubBits,
7155                                       AllowWholeUndefs && AllowUndefs,
7156                                       AllowPartialUndefs && AllowUndefs) &&
7157         getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
7158                                       UndefSrcElts, EltSrcBits,
7159                                       AllowWholeUndefs && AllowUndefs,
7160                                       AllowPartialUndefs && AllowUndefs)) {
7161       unsigned BaseIdx = Op.getConstantOperandVal(2);
7162       UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
7163       for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
7164         EltSrcBits[BaseIdx + i] = EltSubBits[i];
7165       return CastBitData(UndefSrcElts, EltSrcBits);
7166     }
7167   }
7168 
7169   // Extract constant bits from a subvector's source.
7170   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7171     // TODO - support extract_subvector through bitcasts.
7172     if (EltSizeInBits != VT.getScalarSizeInBits())
7173       return false;
7174 
7175     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
7176                                       UndefElts, EltBits, AllowWholeUndefs,
7177                                       AllowPartialUndefs)) {
7178       EVT SrcVT = Op.getOperand(0).getValueType();
7179       unsigned NumSrcElts = SrcVT.getVectorNumElements();
7180       unsigned NumSubElts = VT.getVectorNumElements();
7181       unsigned BaseIdx = Op.getConstantOperandVal(1);
7182       UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
7183       if ((BaseIdx + NumSubElts) != NumSrcElts)
7184         EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
7185       if (BaseIdx != 0)
7186         EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
7187       return true;
7188     }
7189   }
7190 
7191   // Extract constant bits from shuffle node sources.
7192   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
7193     // TODO - support shuffle through bitcasts.
7194     if (EltSizeInBits != VT.getScalarSizeInBits())
7195       return false;
7196 
7197     ArrayRef<int> Mask = SVN->getMask();
7198     if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
7199         llvm::any_of(Mask, [](int M) { return M < 0; }))
7200       return false;
7201 
7202     APInt UndefElts0, UndefElts1;
7203     SmallVector<APInt, 32> EltBits0, EltBits1;
7204     if (isAnyInRange(Mask, 0, NumElts) &&
7205         !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
7206                                        UndefElts0, EltBits0, AllowWholeUndefs,
7207                                        AllowPartialUndefs))
7208       return false;
7209     if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
7210         !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
7211                                        UndefElts1, EltBits1, AllowWholeUndefs,
7212                                        AllowPartialUndefs))
7213       return false;
7214 
7215     UndefElts = APInt::getZero(NumElts);
7216     for (int i = 0; i != (int)NumElts; ++i) {
7217       int M = Mask[i];
7218       if (M < 0) {
7219         UndefElts.setBit(i);
7220         EltBits.push_back(APInt::getZero(EltSizeInBits));
7221       } else if (M < (int)NumElts) {
7222         if (UndefElts0[M])
7223           UndefElts.setBit(i);
7224         EltBits.push_back(EltBits0[M]);
7225       } else {
7226         if (UndefElts1[M - NumElts])
7227           UndefElts.setBit(i);
7228         EltBits.push_back(EltBits1[M - NumElts]);
7229       }
7230     }
7231     return true;
7232   }
7233 
7234   return false;
7235 }
7236 
7237 namespace llvm {
7238 namespace X86 {
7239 bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
7240   APInt UndefElts;
7241   SmallVector<APInt, 16> EltBits;
7242   if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
7243                                     UndefElts, EltBits, true,
7244                                     AllowPartialUndefs)) {
7245     int SplatIndex = -1;
7246     for (int i = 0, e = EltBits.size(); i != e; ++i) {
7247       if (UndefElts[i])
7248         continue;
7249       if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
7250         SplatIndex = -1;
7251         break;
7252       }
7253       SplatIndex = i;
7254     }
7255     if (0 <= SplatIndex) {
7256       SplatVal = EltBits[SplatIndex];
7257       return true;
7258     }
7259   }
7260 
7261   return false;
7262 }
7263 } // namespace X86
7264 } // namespace llvm
7265 
7266 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
7267                                         unsigned MaskEltSizeInBits,
7268                                         SmallVectorImpl<uint64_t> &RawMask,
7269                                         APInt &UndefElts) {
7270   // Extract the raw target constant bits.
7271   SmallVector<APInt, 64> EltBits;
7272   if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
7273                                      EltBits, /* AllowWholeUndefs */ true,
7274                                      /* AllowPartialUndefs */ false))
7275     return false;
7276 
7277   // Insert the extracted elements into the mask.
7278   for (const APInt &Elt : EltBits)
7279     RawMask.push_back(Elt.getZExtValue());
7280 
7281   return true;
7282 }
7283 
7284 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
7285 /// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
7286 /// Note: This ignores saturation, so inputs must be checked first.
7287 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
7288                                   bool Unary, unsigned NumStages = 1) {
7289   assert(Mask.empty() && "Expected an empty shuffle mask vector");
7290   unsigned NumElts = VT.getVectorNumElements();
7291   unsigned NumLanes = VT.getSizeInBits() / 128;
7292   unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
7293   unsigned Offset = Unary ? 0 : NumElts;
7294   unsigned Repetitions = 1u << (NumStages - 1);
7295   unsigned Increment = 1u << NumStages;
7296   assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
7297 
7298   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
7299     for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
7300       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
7301         Mask.push_back(Elt + (Lane * NumEltsPerLane));
7302       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
7303         Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
7304     }
7305   }
7306 }
7307 
7308 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
7309 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
7310                                 APInt &DemandedLHS, APInt &DemandedRHS) {
7311   int NumLanes = VT.getSizeInBits() / 128;
7312   int NumElts = DemandedElts.getBitWidth();
7313   int NumInnerElts = NumElts / 2;
7314   int NumEltsPerLane = NumElts / NumLanes;
7315   int NumInnerEltsPerLane = NumInnerElts / NumLanes;
7316 
7317   DemandedLHS = APInt::getZero(NumInnerElts);
7318   DemandedRHS = APInt::getZero(NumInnerElts);
7319 
7320   // Map DemandedElts to the packed operands.
7321   for (int Lane = 0; Lane != NumLanes; ++Lane) {
7322     for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
7323       int OuterIdx = (Lane * NumEltsPerLane) + Elt;
7324       int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
7325       if (DemandedElts[OuterIdx])
7326         DemandedLHS.setBit(InnerIdx);
7327       if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
7328         DemandedRHS.setBit(InnerIdx);
7329     }
7330   }
7331 }
7332 
7333 // Split the demanded elts of a HADD/HSUB node between its operands.
7334 static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
7335                                  APInt &DemandedLHS, APInt &DemandedRHS) {
7336   int NumLanes = VT.getSizeInBits() / 128;
7337   int NumElts = DemandedElts.getBitWidth();
7338   int NumEltsPerLane = NumElts / NumLanes;
7339   int HalfEltsPerLane = NumEltsPerLane / 2;
7340 
7341   DemandedLHS = APInt::getZero(NumElts);
7342   DemandedRHS = APInt::getZero(NumElts);
7343 
7344   // Map DemandedElts to the horizontal operands.
7345   for (int Idx = 0; Idx != NumElts; ++Idx) {
7346     if (!DemandedElts[Idx])
7347       continue;
7348     int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
7349     int LocalIdx = Idx % NumEltsPerLane;
7350     if (LocalIdx < HalfEltsPerLane) {
7351       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
7352       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
7353     } else {
7354       LocalIdx -= HalfEltsPerLane;
7355       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
7356       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
7357     }
7358   }
7359 }
7360 
7361 /// Calculates the shuffle mask corresponding to the target-specific opcode.
7362 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
7363 /// operands in \p Ops, and returns true.
7364 /// Sets \p IsUnary to true if only one source is used. Note that this will set
7365 /// IsUnary for shuffles which use a single input multiple times, and in those
7366 /// cases it will adjust the mask to only have indices within that single input.
7367 /// It is an error to call this with non-empty Mask/Ops vectors.
7368 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
7369                                  SmallVectorImpl<SDValue> &Ops,
7370                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
7371   unsigned NumElems = VT.getVectorNumElements();
7372   unsigned MaskEltSize = VT.getScalarSizeInBits();
7373   SmallVector<uint64_t, 32> RawMask;
7374   APInt RawUndefs;
7375   uint64_t ImmN;
7376 
7377   assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
7378   assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
7379 
7380   IsUnary = false;
7381   bool IsFakeUnary = false;
7382   switch (N->getOpcode()) {
7383   case X86ISD::BLENDI:
7384     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7385     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7386     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7387     DecodeBLENDMask(NumElems, ImmN, Mask);
7388     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7389     break;
7390   case X86ISD::SHUFP:
7391     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7392     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7393     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7394     DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
7395     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7396     break;
7397   case X86ISD::INSERTPS:
7398     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7399     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7400     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7401     DecodeINSERTPSMask(ImmN, Mask);
7402     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7403     break;
7404   case X86ISD::EXTRQI:
7405     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7406     if (isa<ConstantSDNode>(N->getOperand(1)) &&
7407         isa<ConstantSDNode>(N->getOperand(2))) {
7408       int BitLen = N->getConstantOperandVal(1);
7409       int BitIdx = N->getConstantOperandVal(2);
7410       DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
7411       IsUnary = true;
7412     }
7413     break;
7414   case X86ISD::INSERTQI:
7415     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7416     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7417     if (isa<ConstantSDNode>(N->getOperand(2)) &&
7418         isa<ConstantSDNode>(N->getOperand(3))) {
7419       int BitLen = N->getConstantOperandVal(2);
7420       int BitIdx = N->getConstantOperandVal(3);
7421       DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
7422       IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7423     }
7424     break;
7425   case X86ISD::UNPCKH:
7426     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7427     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7428     DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
7429     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7430     break;
7431   case X86ISD::UNPCKL:
7432     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7433     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7434     DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
7435     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7436     break;
7437   case X86ISD::MOVHLPS:
7438     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7439     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7440     DecodeMOVHLPSMask(NumElems, Mask);
7441     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7442     break;
7443   case X86ISD::MOVLHPS:
7444     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7445     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7446     DecodeMOVLHPSMask(NumElems, Mask);
7447     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7448     break;
7449   case X86ISD::VALIGN:
7450     assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
7451            "Only 32-bit and 64-bit elements are supported!");
7452     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7453     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7454     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7455     DecodeVALIGNMask(NumElems, ImmN, Mask);
7456     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7457     Ops.push_back(N->getOperand(1));
7458     Ops.push_back(N->getOperand(0));
7459     break;
7460   case X86ISD::PALIGNR:
7461     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7462     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7463     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7464     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7465     DecodePALIGNRMask(NumElems, ImmN, Mask);
7466     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7467     Ops.push_back(N->getOperand(1));
7468     Ops.push_back(N->getOperand(0));
7469     break;
7470   case X86ISD::VSHLDQ:
7471     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7472     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7473     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7474     DecodePSLLDQMask(NumElems, ImmN, Mask);
7475     IsUnary = true;
7476     break;
7477   case X86ISD::VSRLDQ:
7478     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7479     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7480     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7481     DecodePSRLDQMask(NumElems, ImmN, Mask);
7482     IsUnary = true;
7483     break;
7484   case X86ISD::PSHUFD:
7485   case X86ISD::VPERMILPI:
7486     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7487     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7488     DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
7489     IsUnary = true;
7490     break;
7491   case X86ISD::PSHUFHW:
7492     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7493     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7494     DecodePSHUFHWMask(NumElems, ImmN, Mask);
7495     IsUnary = true;
7496     break;
7497   case X86ISD::PSHUFLW:
7498     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7499     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7500     DecodePSHUFLWMask(NumElems, ImmN, Mask);
7501     IsUnary = true;
7502     break;
7503   case X86ISD::VZEXT_MOVL:
7504     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7505     DecodeZeroMoveLowMask(NumElems, Mask);
7506     IsUnary = true;
7507     break;
7508   case X86ISD::VBROADCAST:
7509     // We only decode broadcasts of same-sized vectors, peeking through to
7510     // extracted subvectors is likely to cause hasOneUse issues with
7511     // SimplifyDemandedBits etc.
7512     if (N->getOperand(0).getValueType() == VT) {
7513       DecodeVectorBroadcast(NumElems, Mask);
7514       IsUnary = true;
7515       break;
7516     }
7517     return false;
7518   case X86ISD::VPERMILPV: {
7519     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7520     IsUnary = true;
7521     SDValue MaskNode = N->getOperand(1);
7522     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7523                                     RawUndefs)) {
7524       DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
7525       break;
7526     }
7527     return false;
7528   }
7529   case X86ISD::PSHUFB: {
7530     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7531     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7532     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7533     IsUnary = true;
7534     SDValue MaskNode = N->getOperand(1);
7535     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7536       DecodePSHUFBMask(RawMask, RawUndefs, Mask);
7537       break;
7538     }
7539     return false;
7540   }
7541   case X86ISD::VPERMI:
7542     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7543     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7544     DecodeVPERMMask(NumElems, ImmN, Mask);
7545     IsUnary = true;
7546     break;
7547   case X86ISD::MOVSS:
7548   case X86ISD::MOVSD:
7549   case X86ISD::MOVSH:
7550     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7551     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7552     DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
7553     break;
7554   case X86ISD::VPERM2X128:
7555     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7556     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7557     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7558     DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
7559     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7560     break;
7561   case X86ISD::SHUF128:
7562     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7563     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7564     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7565     decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
7566     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7567     break;
7568   case X86ISD::MOVSLDUP:
7569     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7570     DecodeMOVSLDUPMask(NumElems, Mask);
7571     IsUnary = true;
7572     break;
7573   case X86ISD::MOVSHDUP:
7574     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7575     DecodeMOVSHDUPMask(NumElems, Mask);
7576     IsUnary = true;
7577     break;
7578   case X86ISD::MOVDDUP:
7579     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7580     DecodeMOVDDUPMask(NumElems, Mask);
7581     IsUnary = true;
7582     break;
7583   case X86ISD::VPERMIL2: {
7584     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7585     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7586     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7587     SDValue MaskNode = N->getOperand(2);
7588     SDValue CtrlNode = N->getOperand(3);
7589     if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
7590       unsigned CtrlImm = CtrlOp->getZExtValue();
7591       if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7592                                       RawUndefs)) {
7593         DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
7594                             Mask);
7595         break;
7596       }
7597     }
7598     return false;
7599   }
7600   case X86ISD::VPPERM: {
7601     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7602     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7603     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7604     SDValue MaskNode = N->getOperand(2);
7605     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7606       DecodeVPPERMMask(RawMask, RawUndefs, Mask);
7607       break;
7608     }
7609     return false;
7610   }
7611   case X86ISD::VPERMV: {
7612     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7613     IsUnary = true;
7614     // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
7615     Ops.push_back(N->getOperand(1));
7616     SDValue MaskNode = N->getOperand(0);
7617     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7618                                     RawUndefs)) {
7619       DecodeVPERMVMask(RawMask, RawUndefs, Mask);
7620       break;
7621     }
7622     return false;
7623   }
7624   case X86ISD::VPERMV3: {
7625     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7626     assert(N->getOperand(2).getValueType() == VT && "Unexpected value type");
7627     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
7628     // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
7629     Ops.push_back(N->getOperand(0));
7630     Ops.push_back(N->getOperand(2));
7631     SDValue MaskNode = N->getOperand(1);
7632     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7633                                     RawUndefs)) {
7634       DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
7635       break;
7636     }
7637     return false;
7638   }
7639   default: llvm_unreachable("unknown target shuffle node");
7640   }
7641 
7642   // Empty mask indicates the decode failed.
7643   if (Mask.empty())
7644     return false;
7645 
7646   // Check if we're getting a shuffle mask with zero'd elements.
7647   if (!AllowSentinelZero && isAnyZero(Mask))
7648     return false;
7649 
7650   // If we have a fake unary shuffle, the shuffle mask is spread across two
7651   // inputs that are actually the same node. Re-map the mask to always point
7652   // into the first input.
7653   if (IsFakeUnary)
7654     for (int &M : Mask)
7655       if (M >= (int)Mask.size())
7656         M -= Mask.size();
7657 
7658   // If we didn't already add operands in the opcode-specific code, default to
7659   // adding 1 or 2 operands starting at 0.
7660   if (Ops.empty()) {
7661     Ops.push_back(N->getOperand(0));
7662     if (!IsUnary || IsFakeUnary)
7663       Ops.push_back(N->getOperand(1));
7664   }
7665 
7666   return true;
7667 }
7668 
7669 // Wrapper for getTargetShuffleMask with InUnary;
7670 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
7671                                  SmallVectorImpl<SDValue> &Ops,
7672                                  SmallVectorImpl<int> &Mask) {
7673   bool IsUnary;
7674   return getTargetShuffleMask(N, VT, AllowSentinelZero, Ops, Mask, IsUnary);
7675 }
7676 
7677 /// Compute whether each element of a shuffle is zeroable.
7678 ///
7679 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7680 /// Either it is an undef element in the shuffle mask, the element of the input
7681 /// referenced is undef, or the element of the input referenced is known to be
7682 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7683 /// as many lanes with this technique as possible to simplify the remaining
7684 /// shuffle.
7685 static void computeZeroableShuffleElements(ArrayRef<int> Mask,
7686                                            SDValue V1, SDValue V2,
7687                                            APInt &KnownUndef, APInt &KnownZero) {
7688   int Size = Mask.size();
7689   KnownUndef = KnownZero = APInt::getZero(Size);
7690 
7691   V1 = peekThroughBitcasts(V1);
7692   V2 = peekThroughBitcasts(V2);
7693 
7694   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7695   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7696 
7697   int VectorSizeInBits = V1.getValueSizeInBits();
7698   int ScalarSizeInBits = VectorSizeInBits / Size;
7699   assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
7700 
7701   for (int i = 0; i < Size; ++i) {
7702     int M = Mask[i];
7703     // Handle the easy cases.
7704     if (M < 0) {
7705       KnownUndef.setBit(i);
7706       continue;
7707     }
7708     if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7709       KnownZero.setBit(i);
7710       continue;
7711     }
7712 
7713     // Determine shuffle input and normalize the mask.
7714     SDValue V = M < Size ? V1 : V2;
7715     M %= Size;
7716 
7717     // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
7718     if (V.getOpcode() != ISD::BUILD_VECTOR)
7719       continue;
7720 
7721     // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
7722     // the (larger) source element must be UNDEF/ZERO.
7723     if ((Size % V.getNumOperands()) == 0) {
7724       int Scale = Size / V->getNumOperands();
7725       SDValue Op = V.getOperand(M / Scale);
7726       if (Op.isUndef())
7727         KnownUndef.setBit(i);
7728       if (X86::isZeroNode(Op))
7729         KnownZero.setBit(i);
7730       else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
7731         APInt Val = Cst->getAPIntValue();
7732         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7733         if (Val == 0)
7734           KnownZero.setBit(i);
7735       } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7736         APInt Val = Cst->getValueAPF().bitcastToAPInt();
7737         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7738         if (Val == 0)
7739           KnownZero.setBit(i);
7740       }
7741       continue;
7742     }
7743 
7744     // If the BUILD_VECTOR has more elements then all the (smaller) source
7745     // elements must be UNDEF or ZERO.
7746     if ((V.getNumOperands() % Size) == 0) {
7747       int Scale = V->getNumOperands() / Size;
7748       bool AllUndef = true;
7749       bool AllZero = true;
7750       for (int j = 0; j < Scale; ++j) {
7751         SDValue Op = V.getOperand((M * Scale) + j);
7752         AllUndef &= Op.isUndef();
7753         AllZero &= X86::isZeroNode(Op);
7754       }
7755       if (AllUndef)
7756         KnownUndef.setBit(i);
7757       if (AllZero)
7758         KnownZero.setBit(i);
7759       continue;
7760     }
7761   }
7762 }
7763 
7764 /// Decode a target shuffle mask and inputs and see if any values are
7765 /// known to be undef or zero from their inputs.
7766 /// Returns true if the target shuffle mask was decoded.
7767 /// FIXME: Merge this with computeZeroableShuffleElements?
7768 static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
7769                                          SmallVectorImpl<SDValue> &Ops,
7770                                          APInt &KnownUndef, APInt &KnownZero) {
7771   bool IsUnary;
7772   if (!isTargetShuffle(N.getOpcode()))
7773     return false;
7774 
7775   MVT VT = N.getSimpleValueType();
7776   if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
7777     return false;
7778 
7779   int Size = Mask.size();
7780   SDValue V1 = Ops[0];
7781   SDValue V2 = IsUnary ? V1 : Ops[1];
7782   KnownUndef = KnownZero = APInt::getZero(Size);
7783 
7784   V1 = peekThroughBitcasts(V1);
7785   V2 = peekThroughBitcasts(V2);
7786 
7787   assert((VT.getSizeInBits() % Size) == 0 &&
7788          "Illegal split of shuffle value type");
7789   unsigned EltSizeInBits = VT.getSizeInBits() / Size;
7790 
7791   // Extract known constant input data.
7792   APInt UndefSrcElts[2];
7793   SmallVector<APInt, 32> SrcEltBits[2];
7794   bool IsSrcConstant[2] = {
7795       getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
7796                                     SrcEltBits[0], true, false),
7797       getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
7798                                     SrcEltBits[1], true, false)};
7799 
7800   for (int i = 0; i < Size; ++i) {
7801     int M = Mask[i];
7802 
7803     // Already decoded as SM_SentinelZero / SM_SentinelUndef.
7804     if (M < 0) {
7805       assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
7806       if (SM_SentinelUndef == M)
7807         KnownUndef.setBit(i);
7808       if (SM_SentinelZero == M)
7809         KnownZero.setBit(i);
7810       continue;
7811     }
7812 
7813     // Determine shuffle input and normalize the mask.
7814     unsigned SrcIdx = M / Size;
7815     SDValue V = M < Size ? V1 : V2;
7816     M %= Size;
7817 
7818     // We are referencing an UNDEF input.
7819     if (V.isUndef()) {
7820       KnownUndef.setBit(i);
7821       continue;
7822     }
7823 
7824     // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
7825     // TODO: We currently only set UNDEF for integer types - floats use the same
7826     // registers as vectors and many of the scalar folded loads rely on the
7827     // SCALAR_TO_VECTOR pattern.
7828     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7829         (Size % V.getValueType().getVectorNumElements()) == 0) {
7830       int Scale = Size / V.getValueType().getVectorNumElements();
7831       int Idx = M / Scale;
7832       if (Idx != 0 && !VT.isFloatingPoint())
7833         KnownUndef.setBit(i);
7834       else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
7835         KnownZero.setBit(i);
7836       continue;
7837     }
7838 
7839     // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
7840     // base vectors.
7841     if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
7842       SDValue Vec = V.getOperand(0);
7843       int NumVecElts = Vec.getValueType().getVectorNumElements();
7844       if (Vec.isUndef() && Size == NumVecElts) {
7845         int Idx = V.getConstantOperandVal(2);
7846         int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
7847         if (M < Idx || (Idx + NumSubElts) <= M)
7848           KnownUndef.setBit(i);
7849       }
7850       continue;
7851     }
7852 
7853     // Attempt to extract from the source's constant bits.
7854     if (IsSrcConstant[SrcIdx]) {
7855       if (UndefSrcElts[SrcIdx][M])
7856         KnownUndef.setBit(i);
7857       else if (SrcEltBits[SrcIdx][M] == 0)
7858         KnownZero.setBit(i);
7859     }
7860   }
7861 
7862   assert(VT.getVectorNumElements() == (unsigned)Size &&
7863          "Different mask size from vector size!");
7864   return true;
7865 }
7866 
7867 // Replace target shuffle mask elements with known undef/zero sentinels.
7868 static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
7869                                               const APInt &KnownUndef,
7870                                               const APInt &KnownZero,
7871                                               bool ResolveKnownZeros= true) {
7872   unsigned NumElts = Mask.size();
7873   assert(KnownUndef.getBitWidth() == NumElts &&
7874          KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
7875 
7876   for (unsigned i = 0; i != NumElts; ++i) {
7877     if (KnownUndef[i])
7878       Mask[i] = SM_SentinelUndef;
7879     else if (ResolveKnownZeros && KnownZero[i])
7880       Mask[i] = SM_SentinelZero;
7881   }
7882 }
7883 
7884 // Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
7885 static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
7886                                               APInt &KnownUndef,
7887                                               APInt &KnownZero) {
7888   unsigned NumElts = Mask.size();
7889   KnownUndef = KnownZero = APInt::getZero(NumElts);
7890 
7891   for (unsigned i = 0; i != NumElts; ++i) {
7892     int M = Mask[i];
7893     if (SM_SentinelUndef == M)
7894       KnownUndef.setBit(i);
7895     if (SM_SentinelZero == M)
7896       KnownZero.setBit(i);
7897   }
7898 }
7899 
7900 // Forward declaration (for getFauxShuffleMask recursive check).
7901 // TODO: Use DemandedElts variant.
7902 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7903                                    SmallVectorImpl<int> &Mask,
7904                                    const SelectionDAG &DAG, unsigned Depth,
7905                                    bool ResolveKnownElts);
7906 
7907 // Attempt to decode ops that could be represented as a shuffle mask.
7908 // The decoded shuffle mask may contain a different number of elements to the
7909 // destination value type.
7910 static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
7911                                SmallVectorImpl<int> &Mask,
7912                                SmallVectorImpl<SDValue> &Ops,
7913                                const SelectionDAG &DAG, unsigned Depth,
7914                                bool ResolveKnownElts) {
7915   Mask.clear();
7916   Ops.clear();
7917 
7918   MVT VT = N.getSimpleValueType();
7919   unsigned NumElts = VT.getVectorNumElements();
7920   unsigned NumSizeInBits = VT.getSizeInBits();
7921   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7922   if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
7923     return false;
7924   assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
7925   unsigned NumSizeInBytes = NumSizeInBits / 8;
7926   unsigned NumBytesPerElt = NumBitsPerElt / 8;
7927 
7928   unsigned Opcode = N.getOpcode();
7929   switch (Opcode) {
7930   case ISD::VECTOR_SHUFFLE: {
7931     // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
7932     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
7933     if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
7934       Mask.append(ShuffleMask.begin(), ShuffleMask.end());
7935       Ops.push_back(N.getOperand(0));
7936       Ops.push_back(N.getOperand(1));
7937       return true;
7938     }
7939     return false;
7940   }
7941   case ISD::AND:
7942   case X86ISD::ANDNP: {
7943     // Attempt to decode as a per-byte mask.
7944     APInt UndefElts;
7945     SmallVector<APInt, 32> EltBits;
7946     SDValue N0 = N.getOperand(0);
7947     SDValue N1 = N.getOperand(1);
7948     bool IsAndN = (X86ISD::ANDNP == Opcode);
7949     uint64_t ZeroMask = IsAndN ? 255 : 0;
7950     if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
7951       return false;
7952     for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
7953       if (UndefElts[i]) {
7954         Mask.push_back(SM_SentinelUndef);
7955         continue;
7956       }
7957       const APInt &ByteBits = EltBits[i];
7958       if (ByteBits != 0 && ByteBits != 255)
7959         return false;
7960       Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
7961     }
7962     Ops.push_back(IsAndN ? N1 : N0);
7963     return true;
7964   }
7965   case ISD::OR: {
7966     // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
7967     // is a valid shuffle index.
7968     SDValue N0 = peekThroughBitcasts(N.getOperand(0));
7969     SDValue N1 = peekThroughBitcasts(N.getOperand(1));
7970     if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
7971       return false;
7972     SmallVector<int, 64> SrcMask0, SrcMask1;
7973     SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
7974     if (!getTargetShuffleInputs(N0, SrcInputs0, SrcMask0, DAG, Depth + 1,
7975                                 true) ||
7976         !getTargetShuffleInputs(N1, SrcInputs1, SrcMask1, DAG, Depth + 1,
7977                                 true))
7978       return false;
7979 
7980     size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
7981     SmallVector<int, 64> Mask0, Mask1;
7982     narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
7983     narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
7984     for (int i = 0; i != (int)MaskSize; ++i) {
7985       // NOTE: Don't handle SM_SentinelUndef, as we can end up in infinite
7986       // loops converting between OR and BLEND shuffles due to
7987       // canWidenShuffleElements merging away undef elements, meaning we
7988       // fail to recognise the OR as the undef element isn't known zero.
7989       if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
7990         Mask.push_back(SM_SentinelZero);
7991       else if (Mask1[i] == SM_SentinelZero)
7992         Mask.push_back(i);
7993       else if (Mask0[i] == SM_SentinelZero)
7994         Mask.push_back(i + MaskSize);
7995       else
7996         return false;
7997     }
7998     Ops.push_back(N0);
7999     Ops.push_back(N1);
8000     return true;
8001   }
8002   case ISD::INSERT_SUBVECTOR: {
8003     SDValue Src = N.getOperand(0);
8004     SDValue Sub = N.getOperand(1);
8005     EVT SubVT = Sub.getValueType();
8006     unsigned NumSubElts = SubVT.getVectorNumElements();
8007     if (!N->isOnlyUserOf(Sub.getNode()))
8008       return false;
8009     uint64_t InsertIdx = N.getConstantOperandVal(2);
8010     // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
8011     if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8012         Sub.getOperand(0).getValueType() == VT) {
8013       uint64_t ExtractIdx = Sub.getConstantOperandVal(1);
8014       for (int i = 0; i != (int)NumElts; ++i)
8015         Mask.push_back(i);
8016       for (int i = 0; i != (int)NumSubElts; ++i)
8017         Mask[InsertIdx + i] = NumElts + ExtractIdx + i;
8018       Ops.push_back(Src);
8019       Ops.push_back(Sub.getOperand(0));
8020       return true;
8021     }
8022     // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
8023     SmallVector<int, 64> SubMask;
8024     SmallVector<SDValue, 2> SubInputs;
8025     if (!getTargetShuffleInputs(peekThroughOneUseBitcasts(Sub), SubInputs,
8026                                 SubMask, DAG, Depth + 1, ResolveKnownElts))
8027       return false;
8028 
8029     // Subvector shuffle inputs must not be larger than the subvector.
8030     if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
8031           return SubVT.getFixedSizeInBits() <
8032                  SubInput.getValueSizeInBits().getFixedSize();
8033         }))
8034       return false;
8035 
8036     if (SubMask.size() != NumSubElts) {
8037       assert(((SubMask.size() % NumSubElts) == 0 ||
8038               (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale");
8039       if ((NumSubElts % SubMask.size()) == 0) {
8040         int Scale = NumSubElts / SubMask.size();
8041         SmallVector<int,64> ScaledSubMask;
8042         narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
8043         SubMask = ScaledSubMask;
8044       } else {
8045         int Scale = SubMask.size() / NumSubElts;
8046         NumSubElts = SubMask.size();
8047         NumElts *= Scale;
8048         InsertIdx *= Scale;
8049       }
8050     }
8051     Ops.push_back(Src);
8052     Ops.append(SubInputs.begin(), SubInputs.end());
8053     if (ISD::isBuildVectorAllZeros(Src.getNode()))
8054       Mask.append(NumElts, SM_SentinelZero);
8055     else
8056       for (int i = 0; i != (int)NumElts; ++i)
8057         Mask.push_back(i);
8058     for (int i = 0; i != (int)NumSubElts; ++i) {
8059       int M = SubMask[i];
8060       if (0 <= M) {
8061         int InputIdx = M / NumSubElts;
8062         M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
8063       }
8064       Mask[i + InsertIdx] = M;
8065     }
8066     return true;
8067   }
8068   case X86ISD::PINSRB:
8069   case X86ISD::PINSRW:
8070   case ISD::SCALAR_TO_VECTOR:
8071   case ISD::INSERT_VECTOR_ELT: {
8072     // Match against a insert_vector_elt/scalar_to_vector of an extract from a
8073     // vector, for matching src/dst vector types.
8074     SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
8075 
8076     unsigned DstIdx = 0;
8077     if (Opcode != ISD::SCALAR_TO_VECTOR) {
8078       // Check we have an in-range constant insertion index.
8079       if (!isa<ConstantSDNode>(N.getOperand(2)) ||
8080           N.getConstantOperandAPInt(2).uge(NumElts))
8081         return false;
8082       DstIdx = N.getConstantOperandVal(2);
8083 
8084       // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
8085       if (X86::isZeroNode(Scl)) {
8086         Ops.push_back(N.getOperand(0));
8087         for (unsigned i = 0; i != NumElts; ++i)
8088           Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
8089         return true;
8090       }
8091     }
8092 
8093     // Peek through trunc/aext/zext.
8094     // TODO: aext shouldn't require SM_SentinelZero padding.
8095     // TODO: handle shift of scalars.
8096     unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
8097     while (Scl.getOpcode() == ISD::TRUNCATE ||
8098            Scl.getOpcode() == ISD::ANY_EXTEND ||
8099            Scl.getOpcode() == ISD::ZERO_EXTEND) {
8100       Scl = Scl.getOperand(0);
8101       MinBitsPerElt =
8102           std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
8103     }
8104     if ((MinBitsPerElt % 8) != 0)
8105       return false;
8106 
8107     // Attempt to find the source vector the scalar was extracted from.
8108     SDValue SrcExtract;
8109     if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
8110          Scl.getOpcode() == X86ISD::PEXTRW ||
8111          Scl.getOpcode() == X86ISD::PEXTRB) &&
8112         Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
8113       SrcExtract = Scl;
8114     }
8115     if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
8116       return false;
8117 
8118     SDValue SrcVec = SrcExtract.getOperand(0);
8119     EVT SrcVT = SrcVec.getValueType();
8120     if (!SrcVT.getScalarType().isByteSized())
8121       return false;
8122     unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
8123     unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
8124     unsigned DstByte = DstIdx * NumBytesPerElt;
8125     MinBitsPerElt =
8126         std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
8127 
8128     // Create 'identity' byte level shuffle mask and then add inserted bytes.
8129     if (Opcode == ISD::SCALAR_TO_VECTOR) {
8130       Ops.push_back(SrcVec);
8131       Mask.append(NumSizeInBytes, SM_SentinelUndef);
8132     } else {
8133       Ops.push_back(SrcVec);
8134       Ops.push_back(N.getOperand(0));
8135       for (int i = 0; i != (int)NumSizeInBytes; ++i)
8136         Mask.push_back(NumSizeInBytes + i);
8137     }
8138 
8139     unsigned MinBytesPerElts = MinBitsPerElt / 8;
8140     MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
8141     for (unsigned i = 0; i != MinBytesPerElts; ++i)
8142       Mask[DstByte + i] = SrcByte + i;
8143     for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
8144       Mask[DstByte + i] = SM_SentinelZero;
8145     return true;
8146   }
8147   case X86ISD::PACKSS:
8148   case X86ISD::PACKUS: {
8149     SDValue N0 = N.getOperand(0);
8150     SDValue N1 = N.getOperand(1);
8151     assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
8152            N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
8153            "Unexpected input value type");
8154 
8155     APInt EltsLHS, EltsRHS;
8156     getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
8157 
8158     // If we know input saturation won't happen (or we don't care for particular
8159     // lanes), we can treat this as a truncation shuffle.
8160     bool Offset0 = false, Offset1 = false;
8161     if (Opcode == X86ISD::PACKSS) {
8162       if ((!(N0.isUndef() || EltsLHS.isZero()) &&
8163            DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
8164           (!(N1.isUndef() || EltsRHS.isZero()) &&
8165            DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
8166         return false;
8167       // We can't easily fold ASHR into a shuffle, but if it was feeding a
8168       // PACKSS then it was likely being used for sign-extension for a
8169       // truncation, so just peek through and adjust the mask accordingly.
8170       if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
8171           N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
8172         Offset0 = true;
8173         N0 = N0.getOperand(0);
8174       }
8175       if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
8176           N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
8177         Offset1 = true;
8178         N1 = N1.getOperand(0);
8179       }
8180     } else {
8181       APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
8182       if ((!(N0.isUndef() || EltsLHS.isZero()) &&
8183            !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
8184           (!(N1.isUndef() || EltsRHS.isZero()) &&
8185            !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
8186         return false;
8187     }
8188 
8189     bool IsUnary = (N0 == N1);
8190 
8191     Ops.push_back(N0);
8192     if (!IsUnary)
8193       Ops.push_back(N1);
8194 
8195     createPackShuffleMask(VT, Mask, IsUnary);
8196 
8197     if (Offset0 || Offset1) {
8198       for (int &M : Mask)
8199         if ((Offset0 && isInRange(M, 0, NumElts)) ||
8200             (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
8201           ++M;
8202     }
8203     return true;
8204   }
8205   case X86ISD::VTRUNC: {
8206     SDValue Src = N.getOperand(0);
8207     EVT SrcVT = Src.getValueType();
8208     // Truncated source must be a simple vector.
8209     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
8210         (SrcVT.getScalarSizeInBits() % 8) != 0)
8211       return false;
8212     unsigned NumSrcElts = SrcVT.getVectorNumElements();
8213     unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
8214     unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
8215     assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
8216     for (unsigned i = 0; i != NumSrcElts; ++i)
8217       Mask.push_back(i * Scale);
8218     Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
8219     Ops.push_back(Src);
8220     return true;
8221   }
8222   case X86ISD::VSHLI:
8223   case X86ISD::VSRLI: {
8224     uint64_t ShiftVal = N.getConstantOperandVal(1);
8225     // Out of range bit shifts are guaranteed to be zero.
8226     if (NumBitsPerElt <= ShiftVal) {
8227       Mask.append(NumElts, SM_SentinelZero);
8228       return true;
8229     }
8230 
8231     // We can only decode 'whole byte' bit shifts as shuffles.
8232     if ((ShiftVal % 8) != 0)
8233       break;
8234 
8235     uint64_t ByteShift = ShiftVal / 8;
8236     Ops.push_back(N.getOperand(0));
8237 
8238     // Clear mask to all zeros and insert the shifted byte indices.
8239     Mask.append(NumSizeInBytes, SM_SentinelZero);
8240 
8241     if (X86ISD::VSHLI == Opcode) {
8242       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
8243         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
8244           Mask[i + j] = i + j - ByteShift;
8245     } else {
8246       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
8247         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
8248           Mask[i + j - ByteShift] = i + j;
8249     }
8250     return true;
8251   }
8252   case X86ISD::VROTLI:
8253   case X86ISD::VROTRI: {
8254     // We can only decode 'whole byte' bit rotates as shuffles.
8255     uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
8256     if ((RotateVal % 8) != 0)
8257       return false;
8258     Ops.push_back(N.getOperand(0));
8259     int Offset = RotateVal / 8;
8260     Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
8261     for (int i = 0; i != (int)NumElts; ++i) {
8262       int BaseIdx = i * NumBytesPerElt;
8263       for (int j = 0; j != (int)NumBytesPerElt; ++j) {
8264         Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
8265       }
8266     }
8267     return true;
8268   }
8269   case X86ISD::VBROADCAST: {
8270     SDValue Src = N.getOperand(0);
8271     if (!Src.getSimpleValueType().isVector()) {
8272       if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8273           !isNullConstant(Src.getOperand(1)) ||
8274           Src.getOperand(0).getValueType().getScalarType() !=
8275               VT.getScalarType())
8276         return false;
8277       Src = Src.getOperand(0);
8278     }
8279     Ops.push_back(Src);
8280     Mask.append(NumElts, 0);
8281     return true;
8282   }
8283   case ISD::ZERO_EXTEND:
8284   case ISD::ANY_EXTEND:
8285   case ISD::ZERO_EXTEND_VECTOR_INREG:
8286   case ISD::ANY_EXTEND_VECTOR_INREG: {
8287     SDValue Src = N.getOperand(0);
8288     EVT SrcVT = Src.getValueType();
8289 
8290     // Extended source must be a simple vector.
8291     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
8292         (SrcVT.getScalarSizeInBits() % 8) != 0)
8293       return false;
8294 
8295     bool IsAnyExtend =
8296         (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
8297     DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
8298                          IsAnyExtend, Mask);
8299     Ops.push_back(Src);
8300     return true;
8301   }
8302   }
8303 
8304   return false;
8305 }
8306 
8307 /// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
8308 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
8309                                               SmallVectorImpl<int> &Mask) {
8310   int MaskWidth = Mask.size();
8311   SmallVector<SDValue, 16> UsedInputs;
8312   for (int i = 0, e = Inputs.size(); i < e; ++i) {
8313     int lo = UsedInputs.size() * MaskWidth;
8314     int hi = lo + MaskWidth;
8315 
8316     // Strip UNDEF input usage.
8317     if (Inputs[i].isUndef())
8318       for (int &M : Mask)
8319         if ((lo <= M) && (M < hi))
8320           M = SM_SentinelUndef;
8321 
8322     // Check for unused inputs.
8323     if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
8324       for (int &M : Mask)
8325         if (lo <= M)
8326           M -= MaskWidth;
8327       continue;
8328     }
8329 
8330     // Check for repeated inputs.
8331     bool IsRepeat = false;
8332     for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
8333       if (UsedInputs[j] != Inputs[i])
8334         continue;
8335       for (int &M : Mask)
8336         if (lo <= M)
8337           M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
8338       IsRepeat = true;
8339       break;
8340     }
8341     if (IsRepeat)
8342       continue;
8343 
8344     UsedInputs.push_back(Inputs[i]);
8345   }
8346   Inputs = UsedInputs;
8347 }
8348 
8349 /// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
8350 /// and then sets the SM_SentinelUndef and SM_SentinelZero values.
8351 /// Returns true if the target shuffle mask was decoded.
8352 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
8353                                    SmallVectorImpl<SDValue> &Inputs,
8354                                    SmallVectorImpl<int> &Mask,
8355                                    APInt &KnownUndef, APInt &KnownZero,
8356                                    const SelectionDAG &DAG, unsigned Depth,
8357                                    bool ResolveKnownElts) {
8358   EVT VT = Op.getValueType();
8359   if (!VT.isSimple() || !VT.isVector())
8360     return false;
8361 
8362   if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
8363     if (ResolveKnownElts)
8364       resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
8365     return true;
8366   }
8367   if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
8368                          ResolveKnownElts)) {
8369     resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
8370     return true;
8371   }
8372   return false;
8373 }
8374 
8375 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
8376                                    SmallVectorImpl<int> &Mask,
8377                                    const SelectionDAG &DAG, unsigned Depth = 0,
8378                                    bool ResolveKnownElts = true) {
8379   EVT VT = Op.getValueType();
8380   if (!VT.isSimple() || !VT.isVector())
8381     return false;
8382 
8383   APInt KnownUndef, KnownZero;
8384   unsigned NumElts = Op.getValueType().getVectorNumElements();
8385   APInt DemandedElts = APInt::getAllOnes(NumElts);
8386   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
8387                                 KnownZero, DAG, Depth, ResolveKnownElts);
8388 }
8389 
8390 // Attempt to create a scalar/subvector broadcast from the base MemSDNode.
8391 static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
8392                                  EVT MemVT, MemSDNode *Mem, unsigned Offset,
8393                                  SelectionDAG &DAG) {
8394   assert((Opcode == X86ISD::VBROADCAST_LOAD ||
8395           Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
8396          "Unknown broadcast load type");
8397 
8398   // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
8399   if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
8400     return SDValue();
8401 
8402   SDValue Ptr =
8403       DAG.getMemBasePlusOffset(Mem->getBasePtr(), TypeSize::Fixed(Offset), DL);
8404   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8405   SDValue Ops[] = {Mem->getChain(), Ptr};
8406   SDValue BcstLd = DAG.getMemIntrinsicNode(
8407       Opcode, DL, Tys, Ops, MemVT,
8408       DAG.getMachineFunction().getMachineMemOperand(
8409           Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
8410   DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
8411   return BcstLd;
8412 }
8413 
8414 /// Returns the scalar element that will make up the i'th
8415 /// element of the result of the vector shuffle.
8416 static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
8417                                    SelectionDAG &DAG, unsigned Depth) {
8418   if (Depth >= SelectionDAG::MaxRecursionDepth)
8419     return SDValue(); // Limit search depth.
8420 
8421   EVT VT = Op.getValueType();
8422   unsigned Opcode = Op.getOpcode();
8423   unsigned NumElems = VT.getVectorNumElements();
8424 
8425   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
8426   if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
8427     int Elt = SV->getMaskElt(Index);
8428 
8429     if (Elt < 0)
8430       return DAG.getUNDEF(VT.getVectorElementType());
8431 
8432     SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
8433     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
8434   }
8435 
8436   // Recurse into target specific vector shuffles to find scalars.
8437   if (isTargetShuffle(Opcode)) {
8438     MVT ShufVT = VT.getSimpleVT();
8439     MVT ShufSVT = ShufVT.getVectorElementType();
8440     int NumElems = (int)ShufVT.getVectorNumElements();
8441     SmallVector<int, 16> ShuffleMask;
8442     SmallVector<SDValue, 16> ShuffleOps;
8443     if (!getTargetShuffleMask(Op.getNode(), ShufVT, true, ShuffleOps,
8444                               ShuffleMask))
8445       return SDValue();
8446 
8447     int Elt = ShuffleMask[Index];
8448     if (Elt == SM_SentinelZero)
8449       return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
8450                                  : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
8451     if (Elt == SM_SentinelUndef)
8452       return DAG.getUNDEF(ShufSVT);
8453 
8454     assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
8455     SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
8456     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
8457   }
8458 
8459   // Recurse into insert_subvector base/sub vector to find scalars.
8460   if (Opcode == ISD::INSERT_SUBVECTOR) {
8461     SDValue Vec = Op.getOperand(0);
8462     SDValue Sub = Op.getOperand(1);
8463     uint64_t SubIdx = Op.getConstantOperandVal(2);
8464     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
8465 
8466     if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
8467       return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
8468     return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
8469   }
8470 
8471   // Recurse into concat_vectors sub vector to find scalars.
8472   if (Opcode == ISD::CONCAT_VECTORS) {
8473     EVT SubVT = Op.getOperand(0).getValueType();
8474     unsigned NumSubElts = SubVT.getVectorNumElements();
8475     uint64_t SubIdx = Index / NumSubElts;
8476     uint64_t SubElt = Index % NumSubElts;
8477     return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
8478   }
8479 
8480   // Recurse into extract_subvector src vector to find scalars.
8481   if (Opcode == ISD::EXTRACT_SUBVECTOR) {
8482     SDValue Src = Op.getOperand(0);
8483     uint64_t SrcIdx = Op.getConstantOperandVal(1);
8484     return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
8485   }
8486 
8487   // We only peek through bitcasts of the same vector width.
8488   if (Opcode == ISD::BITCAST) {
8489     SDValue Src = Op.getOperand(0);
8490     EVT SrcVT = Src.getValueType();
8491     if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
8492       return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
8493     return SDValue();
8494   }
8495 
8496   // Actual nodes that may contain scalar elements
8497 
8498   // For insert_vector_elt - either return the index matching scalar or recurse
8499   // into the base vector.
8500   if (Opcode == ISD::INSERT_VECTOR_ELT &&
8501       isa<ConstantSDNode>(Op.getOperand(2))) {
8502     if (Op.getConstantOperandAPInt(2) == Index)
8503       return Op.getOperand(1);
8504     return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
8505   }
8506 
8507   if (Opcode == ISD::SCALAR_TO_VECTOR)
8508     return (Index == 0) ? Op.getOperand(0)
8509                         : DAG.getUNDEF(VT.getVectorElementType());
8510 
8511   if (Opcode == ISD::BUILD_VECTOR)
8512     return Op.getOperand(Index);
8513 
8514   return SDValue();
8515 }
8516 
8517 // Use PINSRB/PINSRW/PINSRD to create a build vector.
8518 static SDValue LowerBuildVectorAsInsert(SDValue Op, const APInt &NonZeroMask,
8519                                         unsigned NumNonZero, unsigned NumZero,
8520                                         SelectionDAG &DAG,
8521                                         const X86Subtarget &Subtarget) {
8522   MVT VT = Op.getSimpleValueType();
8523   unsigned NumElts = VT.getVectorNumElements();
8524   assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
8525           ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
8526          "Illegal vector insertion");
8527 
8528   SDLoc dl(Op);
8529   SDValue V;
8530   bool First = true;
8531 
8532   for (unsigned i = 0; i < NumElts; ++i) {
8533     bool IsNonZero = NonZeroMask[i];
8534     if (!IsNonZero)
8535       continue;
8536 
8537     // If the build vector contains zeros or our first insertion is not the
8538     // first index then insert into zero vector to break any register
8539     // dependency else use SCALAR_TO_VECTOR.
8540     if (First) {
8541       First = false;
8542       if (NumZero || 0 != i)
8543         V = getZeroVector(VT, Subtarget, DAG, dl);
8544       else {
8545         assert(0 == i && "Expected insertion into zero-index");
8546         V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8547         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
8548         V = DAG.getBitcast(VT, V);
8549         continue;
8550       }
8551     }
8552     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
8553                     DAG.getIntPtrConstant(i, dl));
8554   }
8555 
8556   return V;
8557 }
8558 
8559 /// Custom lower build_vector of v16i8.
8560 static SDValue LowerBuildVectorv16i8(SDValue Op, const APInt &NonZeroMask,
8561                                      unsigned NumNonZero, unsigned NumZero,
8562                                      SelectionDAG &DAG,
8563                                      const X86Subtarget &Subtarget) {
8564   if (NumNonZero > 8 && !Subtarget.hasSSE41())
8565     return SDValue();
8566 
8567   // SSE4.1 - use PINSRB to insert each byte directly.
8568   if (Subtarget.hasSSE41())
8569     return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
8570                                     Subtarget);
8571 
8572   SDLoc dl(Op);
8573   SDValue V;
8574 
8575   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
8576   for (unsigned i = 0; i < 16; i += 2) {
8577     bool ThisIsNonZero = NonZeroMask[i];
8578     bool NextIsNonZero = NonZeroMask[i + 1];
8579     if (!ThisIsNonZero && !NextIsNonZero)
8580       continue;
8581 
8582     // FIXME: Investigate combining the first 4 bytes as a i32 instead.
8583     SDValue Elt;
8584     if (ThisIsNonZero) {
8585       if (NumZero || NextIsNonZero)
8586         Elt = DAG.getZExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8587       else
8588         Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8589     }
8590 
8591     if (NextIsNonZero) {
8592       SDValue NextElt = Op.getOperand(i + 1);
8593       if (i == 0 && NumZero)
8594         NextElt = DAG.getZExtOrTrunc(NextElt, dl, MVT::i32);
8595       else
8596         NextElt = DAG.getAnyExtOrTrunc(NextElt, dl, MVT::i32);
8597       NextElt = DAG.getNode(ISD::SHL, dl, MVT::i32, NextElt,
8598                             DAG.getConstant(8, dl, MVT::i8));
8599       if (ThisIsNonZero)
8600         Elt = DAG.getNode(ISD::OR, dl, MVT::i32, NextElt, Elt);
8601       else
8602         Elt = NextElt;
8603     }
8604 
8605     // If our first insertion is not the first index or zeros are needed, then
8606     // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
8607     // elements undefined).
8608     if (!V) {
8609       if (i != 0 || NumZero)
8610         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
8611       else {
8612         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Elt);
8613         V = DAG.getBitcast(MVT::v8i16, V);
8614         continue;
8615       }
8616     }
8617     Elt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Elt);
8618     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, Elt,
8619                     DAG.getIntPtrConstant(i / 2, dl));
8620   }
8621 
8622   return DAG.getBitcast(MVT::v16i8, V);
8623 }
8624 
8625 /// Custom lower build_vector of v8i16.
8626 static SDValue LowerBuildVectorv8i16(SDValue Op, const APInt &NonZeroMask,
8627                                      unsigned NumNonZero, unsigned NumZero,
8628                                      SelectionDAG &DAG,
8629                                      const X86Subtarget &Subtarget) {
8630   if (NumNonZero > 4 && !Subtarget.hasSSE41())
8631     return SDValue();
8632 
8633   // Use PINSRW to insert each byte directly.
8634   return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
8635                                   Subtarget);
8636 }
8637 
8638 /// Custom lower build_vector of v4i32 or v4f32.
8639 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
8640                                      const X86Subtarget &Subtarget) {
8641   // If this is a splat of a pair of elements, use MOVDDUP (unless the target
8642   // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
8643   // Because we're creating a less complicated build vector here, we may enable
8644   // further folding of the MOVDDUP via shuffle transforms.
8645   if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
8646       Op.getOperand(0) == Op.getOperand(2) &&
8647       Op.getOperand(1) == Op.getOperand(3) &&
8648       Op.getOperand(0) != Op.getOperand(1)) {
8649     SDLoc DL(Op);
8650     MVT VT = Op.getSimpleValueType();
8651     MVT EltVT = VT.getVectorElementType();
8652     // Create a new build vector with the first 2 elements followed by undef
8653     // padding, bitcast to v2f64, duplicate, and bitcast back.
8654     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
8655                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
8656     SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
8657     SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
8658     return DAG.getBitcast(VT, Dup);
8659   }
8660 
8661   // Find all zeroable elements.
8662   std::bitset<4> Zeroable, Undefs;
8663   for (int i = 0; i < 4; ++i) {
8664     SDValue Elt = Op.getOperand(i);
8665     Undefs[i] = Elt.isUndef();
8666     Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
8667   }
8668   assert(Zeroable.size() - Zeroable.count() > 1 &&
8669          "We expect at least two non-zero elements!");
8670 
8671   // We only know how to deal with build_vector nodes where elements are either
8672   // zeroable or extract_vector_elt with constant index.
8673   SDValue FirstNonZero;
8674   unsigned FirstNonZeroIdx;
8675   for (unsigned i = 0; i < 4; ++i) {
8676     if (Zeroable[i])
8677       continue;
8678     SDValue Elt = Op.getOperand(i);
8679     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8680         !isa<ConstantSDNode>(Elt.getOperand(1)))
8681       return SDValue();
8682     // Make sure that this node is extracting from a 128-bit vector.
8683     MVT VT = Elt.getOperand(0).getSimpleValueType();
8684     if (!VT.is128BitVector())
8685       return SDValue();
8686     if (!FirstNonZero.getNode()) {
8687       FirstNonZero = Elt;
8688       FirstNonZeroIdx = i;
8689     }
8690   }
8691 
8692   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
8693   SDValue V1 = FirstNonZero.getOperand(0);
8694   MVT VT = V1.getSimpleValueType();
8695 
8696   // See if this build_vector can be lowered as a blend with zero.
8697   SDValue Elt;
8698   unsigned EltMaskIdx, EltIdx;
8699   int Mask[4];
8700   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
8701     if (Zeroable[EltIdx]) {
8702       // The zero vector will be on the right hand side.
8703       Mask[EltIdx] = EltIdx+4;
8704       continue;
8705     }
8706 
8707     Elt = Op->getOperand(EltIdx);
8708     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
8709     EltMaskIdx = Elt.getConstantOperandVal(1);
8710     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
8711       break;
8712     Mask[EltIdx] = EltIdx;
8713   }
8714 
8715   if (EltIdx == 4) {
8716     // Let the shuffle legalizer deal with blend operations.
8717     SDValue VZeroOrUndef = (Zeroable == Undefs)
8718                                ? DAG.getUNDEF(VT)
8719                                : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
8720     if (V1.getSimpleValueType() != VT)
8721       V1 = DAG.getBitcast(VT, V1);
8722     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
8723   }
8724 
8725   // See if we can lower this build_vector to a INSERTPS.
8726   if (!Subtarget.hasSSE41())
8727     return SDValue();
8728 
8729   SDValue V2 = Elt.getOperand(0);
8730   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
8731     V1 = SDValue();
8732 
8733   bool CanFold = true;
8734   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
8735     if (Zeroable[i])
8736       continue;
8737 
8738     SDValue Current = Op->getOperand(i);
8739     SDValue SrcVector = Current->getOperand(0);
8740     if (!V1.getNode())
8741       V1 = SrcVector;
8742     CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
8743   }
8744 
8745   if (!CanFold)
8746     return SDValue();
8747 
8748   assert(V1.getNode() && "Expected at least two non-zero elements!");
8749   if (V1.getSimpleValueType() != MVT::v4f32)
8750     V1 = DAG.getBitcast(MVT::v4f32, V1);
8751   if (V2.getSimpleValueType() != MVT::v4f32)
8752     V2 = DAG.getBitcast(MVT::v4f32, V2);
8753 
8754   // Ok, we can emit an INSERTPS instruction.
8755   unsigned ZMask = Zeroable.to_ulong();
8756 
8757   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
8758   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8759   SDLoc DL(Op);
8760   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8761                                DAG.getIntPtrConstant(InsertPSMask, DL, true));
8762   return DAG.getBitcast(VT, Result);
8763 }
8764 
8765 /// Return a vector logical shift node.
8766 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
8767                          SelectionDAG &DAG, const TargetLowering &TLI,
8768                          const SDLoc &dl) {
8769   assert(VT.is128BitVector() && "Unknown type for VShift");
8770   MVT ShVT = MVT::v16i8;
8771   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
8772   SrcOp = DAG.getBitcast(ShVT, SrcOp);
8773   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
8774   SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
8775   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
8776 }
8777 
8778 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
8779                                       SelectionDAG &DAG) {
8780 
8781   // Check if the scalar load can be widened into a vector load. And if
8782   // the address is "base + cst" see if the cst can be "absorbed" into
8783   // the shuffle mask.
8784   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
8785     SDValue Ptr = LD->getBasePtr();
8786     if (!ISD::isNormalLoad(LD) || !LD->isSimple())
8787       return SDValue();
8788     EVT PVT = LD->getValueType(0);
8789     if (PVT != MVT::i32 && PVT != MVT::f32)
8790       return SDValue();
8791 
8792     int FI = -1;
8793     int64_t Offset = 0;
8794     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
8795       FI = FINode->getIndex();
8796       Offset = 0;
8797     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
8798                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
8799       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
8800       Offset = Ptr.getConstantOperandVal(1);
8801       Ptr = Ptr.getOperand(0);
8802     } else {
8803       return SDValue();
8804     }
8805 
8806     // FIXME: 256-bit vector instructions don't require a strict alignment,
8807     // improve this code to support it better.
8808     Align RequiredAlign(VT.getSizeInBits() / 8);
8809     SDValue Chain = LD->getChain();
8810     // Make sure the stack object alignment is at least 16 or 32.
8811     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8812     MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
8813     if (!InferredAlign || *InferredAlign < RequiredAlign) {
8814       if (MFI.isFixedObjectIndex(FI)) {
8815         // Can't change the alignment. FIXME: It's possible to compute
8816         // the exact stack offset and reference FI + adjust offset instead.
8817         // If someone *really* cares about this. That's the way to implement it.
8818         return SDValue();
8819       } else {
8820         MFI.setObjectAlignment(FI, RequiredAlign);
8821       }
8822     }
8823 
8824     // (Offset % 16 or 32) must be multiple of 4. Then address is then
8825     // Ptr + (Offset & ~15).
8826     if (Offset < 0)
8827       return SDValue();
8828     if ((Offset % RequiredAlign.value()) & 3)
8829       return SDValue();
8830     int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
8831     if (StartOffset) {
8832       SDLoc DL(Ptr);
8833       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
8834                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
8835     }
8836 
8837     int EltNo = (Offset - StartOffset) >> 2;
8838     unsigned NumElems = VT.getVectorNumElements();
8839 
8840     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
8841     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
8842                              LD->getPointerInfo().getWithOffset(StartOffset));
8843 
8844     SmallVector<int, 8> Mask(NumElems, EltNo);
8845 
8846     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
8847   }
8848 
8849   return SDValue();
8850 }
8851 
8852 // Recurse to find a LoadSDNode source and the accumulated ByteOffest.
8853 static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
8854   if (ISD::isNON_EXTLoad(Elt.getNode())) {
8855     auto *BaseLd = cast<LoadSDNode>(Elt);
8856     if (!BaseLd->isSimple())
8857       return false;
8858     Ld = BaseLd;
8859     ByteOffset = 0;
8860     return true;
8861   }
8862 
8863   switch (Elt.getOpcode()) {
8864   case ISD::BITCAST:
8865   case ISD::TRUNCATE:
8866   case ISD::SCALAR_TO_VECTOR:
8867     return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
8868   case ISD::SRL:
8869     if (auto *AmtC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
8870       uint64_t Amt = AmtC->getZExtValue();
8871       if ((Amt % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
8872         ByteOffset += Amt / 8;
8873         return true;
8874       }
8875     }
8876     break;
8877   case ISD::EXTRACT_VECTOR_ELT:
8878     if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
8879       SDValue Src = Elt.getOperand(0);
8880       unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
8881       unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
8882       if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
8883           findEltLoadSrc(Src, Ld, ByteOffset)) {
8884         uint64_t Idx = IdxC->getZExtValue();
8885         ByteOffset += Idx * (SrcSizeInBits / 8);
8886         return true;
8887       }
8888     }
8889     break;
8890   }
8891 
8892   return false;
8893 }
8894 
8895 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
8896 /// elements can be replaced by a single large load which has the same value as
8897 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
8898 ///
8899 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
8900 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
8901                                         const SDLoc &DL, SelectionDAG &DAG,
8902                                         const X86Subtarget &Subtarget,
8903                                         bool IsAfterLegalize) {
8904   if ((VT.getScalarSizeInBits() % 8) != 0)
8905     return SDValue();
8906 
8907   unsigned NumElems = Elts.size();
8908 
8909   int LastLoadedElt = -1;
8910   APInt LoadMask = APInt::getZero(NumElems);
8911   APInt ZeroMask = APInt::getZero(NumElems);
8912   APInt UndefMask = APInt::getZero(NumElems);
8913 
8914   SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
8915   SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
8916 
8917   // For each element in the initializer, see if we've found a load, zero or an
8918   // undef.
8919   for (unsigned i = 0; i < NumElems; ++i) {
8920     SDValue Elt = peekThroughBitcasts(Elts[i]);
8921     if (!Elt.getNode())
8922       return SDValue();
8923     if (Elt.isUndef()) {
8924       UndefMask.setBit(i);
8925       continue;
8926     }
8927     if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
8928       ZeroMask.setBit(i);
8929       continue;
8930     }
8931 
8932     // Each loaded element must be the correct fractional portion of the
8933     // requested vector load.
8934     unsigned EltSizeInBits = Elt.getValueSizeInBits();
8935     if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
8936       return SDValue();
8937 
8938     if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
8939       return SDValue();
8940     unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
8941     if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
8942       return SDValue();
8943 
8944     LoadMask.setBit(i);
8945     LastLoadedElt = i;
8946   }
8947   assert((ZeroMask.countPopulation() + UndefMask.countPopulation() +
8948           LoadMask.countPopulation()) == NumElems &&
8949          "Incomplete element masks");
8950 
8951   // Handle Special Cases - all undef or undef/zero.
8952   if (UndefMask.countPopulation() == NumElems)
8953     return DAG.getUNDEF(VT);
8954   if ((ZeroMask.countPopulation() + UndefMask.countPopulation()) == NumElems)
8955     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
8956                           : DAG.getConstantFP(0.0, DL, VT);
8957 
8958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8959   int FirstLoadedElt = LoadMask.countTrailingZeros();
8960   SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
8961   EVT EltBaseVT = EltBase.getValueType();
8962   assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
8963          "Register/Memory size mismatch");
8964   LoadSDNode *LDBase = Loads[FirstLoadedElt];
8965   assert(LDBase && "Did not find base load for merging consecutive loads");
8966   unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
8967   unsigned BaseSizeInBytes = BaseSizeInBits / 8;
8968   int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
8969   int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
8970   assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
8971 
8972   // TODO: Support offsetting the base load.
8973   if (ByteOffsets[FirstLoadedElt] != 0)
8974     return SDValue();
8975 
8976   // Check to see if the element's load is consecutive to the base load
8977   // or offset from a previous (already checked) load.
8978   auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
8979     LoadSDNode *Ld = Loads[EltIdx];
8980     int64_t ByteOffset = ByteOffsets[EltIdx];
8981     if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
8982       int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
8983       return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
8984               Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
8985     }
8986     return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
8987                                               EltIdx - FirstLoadedElt);
8988   };
8989 
8990   // Consecutive loads can contain UNDEFS but not ZERO elements.
8991   // Consecutive loads with UNDEFs and ZEROs elements require a
8992   // an additional shuffle stage to clear the ZERO elements.
8993   bool IsConsecutiveLoad = true;
8994   bool IsConsecutiveLoadWithZeros = true;
8995   for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
8996     if (LoadMask[i]) {
8997       if (!CheckConsecutiveLoad(LDBase, i)) {
8998         IsConsecutiveLoad = false;
8999         IsConsecutiveLoadWithZeros = false;
9000         break;
9001       }
9002     } else if (ZeroMask[i]) {
9003       IsConsecutiveLoad = false;
9004     }
9005   }
9006 
9007   auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
9008     auto MMOFlags = LDBase->getMemOperand()->getFlags();
9009     assert(LDBase->isSimple() &&
9010            "Cannot merge volatile or atomic loads.");
9011     SDValue NewLd =
9012         DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
9013                     LDBase->getPointerInfo(), LDBase->getOriginalAlign(),
9014                     MMOFlags);
9015     for (auto *LD : Loads)
9016       if (LD)
9017         DAG.makeEquivalentMemoryOrdering(LD, NewLd);
9018     return NewLd;
9019   };
9020 
9021   // Check if the base load is entirely dereferenceable.
9022   bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
9023       VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
9024 
9025   // LOAD - all consecutive load/undefs (must start/end with a load or be
9026   // entirely dereferenceable). If we have found an entire vector of loads and
9027   // undefs, then return a large load of the entire vector width starting at the
9028   // base pointer. If the vector contains zeros, then attempt to shuffle those
9029   // elements.
9030   if (FirstLoadedElt == 0 &&
9031       (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
9032       (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
9033     if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
9034       return SDValue();
9035 
9036     // Don't create 256-bit non-temporal aligned loads without AVX2 as these
9037     // will lower to regular temporal loads and use the cache.
9038     if (LDBase->isNonTemporal() && LDBase->getAlignment() >= 32 &&
9039         VT.is256BitVector() && !Subtarget.hasInt256())
9040       return SDValue();
9041 
9042     if (NumElems == 1)
9043       return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
9044 
9045     if (!ZeroMask)
9046       return CreateLoad(VT, LDBase);
9047 
9048     // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
9049     // vector and a zero vector to clear out the zero elements.
9050     if (!IsAfterLegalize && VT.isVector()) {
9051       unsigned NumMaskElts = VT.getVectorNumElements();
9052       if ((NumMaskElts % NumElems) == 0) {
9053         unsigned Scale = NumMaskElts / NumElems;
9054         SmallVector<int, 4> ClearMask(NumMaskElts, -1);
9055         for (unsigned i = 0; i < NumElems; ++i) {
9056           if (UndefMask[i])
9057             continue;
9058           int Offset = ZeroMask[i] ? NumMaskElts : 0;
9059           for (unsigned j = 0; j != Scale; ++j)
9060             ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
9061         }
9062         SDValue V = CreateLoad(VT, LDBase);
9063         SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
9064                                    : DAG.getConstantFP(0.0, DL, VT);
9065         return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
9066       }
9067     }
9068   }
9069 
9070   // If the upper half of a ymm/zmm load is undef then just load the lower half.
9071   if (VT.is256BitVector() || VT.is512BitVector()) {
9072     unsigned HalfNumElems = NumElems / 2;
9073     if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnes()) {
9074       EVT HalfVT =
9075           EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
9076       SDValue HalfLD =
9077           EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
9078                                    DAG, Subtarget, IsAfterLegalize);
9079       if (HalfLD)
9080         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
9081                            HalfLD, DAG.getIntPtrConstant(0, DL));
9082     }
9083   }
9084 
9085   // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
9086   if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
9087       ((LoadSizeInBits == 16 && Subtarget.hasFP16()) || LoadSizeInBits == 32 ||
9088        LoadSizeInBits == 64) &&
9089       ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
9090     MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
9091                                       : MVT::getIntegerVT(LoadSizeInBits);
9092     MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
9093     // Allow v4f32 on SSE1 only targets.
9094     // FIXME: Add more isel patterns so we can just use VT directly.
9095     if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
9096       VecVT = MVT::v4f32;
9097     if (TLI.isTypeLegal(VecVT)) {
9098       SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
9099       SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
9100       SDValue ResNode = DAG.getMemIntrinsicNode(
9101           X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
9102           LDBase->getOriginalAlign(), MachineMemOperand::MOLoad);
9103       for (auto *LD : Loads)
9104         if (LD)
9105           DAG.makeEquivalentMemoryOrdering(LD, ResNode);
9106       return DAG.getBitcast(VT, ResNode);
9107     }
9108   }
9109 
9110   // BROADCAST - match the smallest possible repetition pattern, load that
9111   // scalar/subvector element and then broadcast to the entire vector.
9112   if (ZeroMask.isZero() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
9113       (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
9114     for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
9115       unsigned RepeatSize = SubElems * BaseSizeInBits;
9116       unsigned ScalarSize = std::min(RepeatSize, 64u);
9117       if (!Subtarget.hasAVX2() && ScalarSize < 32)
9118         continue;
9119 
9120       // Don't attempt a 1:N subvector broadcast - it should be caught by
9121       // combineConcatVectorOps, else will cause infinite loops.
9122       if (RepeatSize > ScalarSize && SubElems == 1)
9123         continue;
9124 
9125       bool Match = true;
9126       SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
9127       for (unsigned i = 0; i != NumElems && Match; ++i) {
9128         if (!LoadMask[i])
9129           continue;
9130         SDValue Elt = peekThroughBitcasts(Elts[i]);
9131         if (RepeatedLoads[i % SubElems].isUndef())
9132           RepeatedLoads[i % SubElems] = Elt;
9133         else
9134           Match &= (RepeatedLoads[i % SubElems] == Elt);
9135       }
9136 
9137       // We must have loads at both ends of the repetition.
9138       Match &= !RepeatedLoads.front().isUndef();
9139       Match &= !RepeatedLoads.back().isUndef();
9140       if (!Match)
9141         continue;
9142 
9143       EVT RepeatVT =
9144           VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
9145               ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
9146               : EVT::getFloatingPointVT(ScalarSize);
9147       if (RepeatSize > ScalarSize)
9148         RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
9149                                     RepeatSize / ScalarSize);
9150       EVT BroadcastVT =
9151           EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
9152                            VT.getSizeInBits() / ScalarSize);
9153       if (TLI.isTypeLegal(BroadcastVT)) {
9154         if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
9155                 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize)) {
9156           SDValue Broadcast = RepeatLoad;
9157           if (RepeatSize > ScalarSize) {
9158             while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
9159               Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
9160           } else {
9161             if (!Subtarget.hasAVX2() &&
9162                 !X86::mayFoldLoadIntoBroadcastFromMem(
9163                     RepeatLoad, RepeatVT.getScalarType().getSimpleVT(),
9164                     Subtarget,
9165                     /*AssumeSingleUse=*/true))
9166               return SDValue();
9167             Broadcast =
9168                 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
9169           }
9170           return DAG.getBitcast(VT, Broadcast);
9171         }
9172       }
9173     }
9174   }
9175 
9176   return SDValue();
9177 }
9178 
9179 // Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
9180 // load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
9181 // are consecutive, non-overlapping, and in the right order.
9182 static SDValue combineToConsecutiveLoads(EVT VT, SDValue Op, const SDLoc &DL,
9183                                          SelectionDAG &DAG,
9184                                          const X86Subtarget &Subtarget,
9185                                          bool IsAfterLegalize) {
9186   SmallVector<SDValue, 64> Elts;
9187   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9188     if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
9189       Elts.push_back(Elt);
9190       continue;
9191     }
9192     return SDValue();
9193   }
9194   assert(Elts.size() == VT.getVectorNumElements());
9195   return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
9196                                   IsAfterLegalize);
9197 }
9198 
9199 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
9200                                    unsigned SplatBitSize, LLVMContext &C) {
9201   unsigned ScalarSize = VT.getScalarSizeInBits();
9202   unsigned NumElm = SplatBitSize / ScalarSize;
9203 
9204   SmallVector<Constant *, 32> ConstantVec;
9205   for (unsigned i = 0; i < NumElm; i++) {
9206     APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
9207     Constant *Const;
9208     if (VT.isFloatingPoint()) {
9209       if (ScalarSize == 16) {
9210         Const = ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
9211       } else if (ScalarSize == 32) {
9212         Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
9213       } else {
9214         assert(ScalarSize == 64 && "Unsupported floating point scalar size");
9215         Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
9216       }
9217     } else
9218       Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
9219     ConstantVec.push_back(Const);
9220   }
9221   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
9222 }
9223 
9224 static bool isFoldableUseOfShuffle(SDNode *N) {
9225   for (auto *U : N->uses()) {
9226     unsigned Opc = U->getOpcode();
9227     // VPERMV/VPERMV3 shuffles can never fold their index operands.
9228     if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
9229       return false;
9230     if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
9231       return false;
9232     if (isTargetShuffle(Opc))
9233       return true;
9234     if (Opc == ISD::BITCAST) // Ignore bitcasts
9235       return isFoldableUseOfShuffle(U);
9236     if (N->hasOneUse())
9237       return true;
9238   }
9239   return false;
9240 }
9241 
9242 /// Attempt to use the vbroadcast instruction to generate a splat value
9243 /// from a splat BUILD_VECTOR which uses:
9244 ///  a. A single scalar load, or a constant.
9245 ///  b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
9246 ///
9247 /// The VBROADCAST node is returned when a pattern is found,
9248 /// or SDValue() otherwise.
9249 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
9250                                            const X86Subtarget &Subtarget,
9251                                            SelectionDAG &DAG) {
9252   // VBROADCAST requires AVX.
9253   // TODO: Splats could be generated for non-AVX CPUs using SSE
9254   // instructions, but there's less potential gain for only 128-bit vectors.
9255   if (!Subtarget.hasAVX())
9256     return SDValue();
9257 
9258   MVT VT = BVOp->getSimpleValueType(0);
9259   unsigned NumElts = VT.getVectorNumElements();
9260   SDLoc dl(BVOp);
9261 
9262   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
9263          "Unsupported vector type for broadcast.");
9264 
9265   // See if the build vector is a repeating sequence of scalars (inc. splat).
9266   SDValue Ld;
9267   BitVector UndefElements;
9268   SmallVector<SDValue, 16> Sequence;
9269   if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
9270     assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
9271     if (Sequence.size() == 1)
9272       Ld = Sequence[0];
9273   }
9274 
9275   // Attempt to use VBROADCASTM
9276   // From this pattern:
9277   // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
9278   // b. t1 = (build_vector t0 t0)
9279   //
9280   // Create (VBROADCASTM v2i1 X)
9281   if (!Sequence.empty() && Subtarget.hasCDI()) {
9282     // If not a splat, are the upper sequence values zeroable?
9283     unsigned SeqLen = Sequence.size();
9284     bool UpperZeroOrUndef =
9285         SeqLen == 1 ||
9286         llvm::all_of(makeArrayRef(Sequence).drop_front(), [](SDValue V) {
9287           return !V || V.isUndef() || isNullConstant(V);
9288         });
9289     SDValue Op0 = Sequence[0];
9290     if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
9291                              (Op0.getOpcode() == ISD::ZERO_EXTEND &&
9292                               Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
9293       SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
9294                              ? Op0.getOperand(0)
9295                              : Op0.getOperand(0).getOperand(0);
9296       MVT MaskVT = BOperand.getSimpleValueType();
9297       MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
9298       if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) ||  // for broadcastmb2q
9299           (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
9300         MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
9301         if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
9302           unsigned Scale = 512 / VT.getSizeInBits();
9303           BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
9304         }
9305         SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
9306         if (BcstVT.getSizeInBits() != VT.getSizeInBits())
9307           Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
9308         return DAG.getBitcast(VT, Bcst);
9309       }
9310     }
9311   }
9312 
9313   unsigned NumUndefElts = UndefElements.count();
9314   if (!Ld || (NumElts - NumUndefElts) <= 1) {
9315     APInt SplatValue, Undef;
9316     unsigned SplatBitSize;
9317     bool HasUndef;
9318     // Check if this is a repeated constant pattern suitable for broadcasting.
9319     if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
9320         SplatBitSize > VT.getScalarSizeInBits() &&
9321         SplatBitSize < VT.getSizeInBits()) {
9322       // Avoid replacing with broadcast when it's a use of a shuffle
9323       // instruction to preserve the present custom lowering of shuffles.
9324       if (isFoldableUseOfShuffle(BVOp))
9325         return SDValue();
9326       // replace BUILD_VECTOR with broadcast of the repeated constants.
9327       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9328       LLVMContext *Ctx = DAG.getContext();
9329       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
9330       if (Subtarget.hasAVX()) {
9331         if (SplatBitSize == 32 || SplatBitSize == 64 ||
9332             (SplatBitSize < 32 && Subtarget.hasAVX2())) {
9333           // Splatted value can fit in one INTEGER constant in constant pool.
9334           // Load the constant and broadcast it.
9335           MVT CVT = MVT::getIntegerVT(SplatBitSize);
9336           Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
9337           Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
9338           SDValue CP = DAG.getConstantPool(C, PVT);
9339           unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
9340 
9341           Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
9342           SDVTList Tys =
9343               DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
9344           SDValue Ops[] = {DAG.getEntryNode(), CP};
9345           MachinePointerInfo MPI =
9346               MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9347           SDValue Brdcst = DAG.getMemIntrinsicNode(
9348               X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT, MPI, Alignment,
9349               MachineMemOperand::MOLoad);
9350           return DAG.getBitcast(VT, Brdcst);
9351         }
9352         if (SplatBitSize > 64) {
9353           // Load the vector of constants and broadcast it.
9354           Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
9355                                              *Ctx);
9356           SDValue VCP = DAG.getConstantPool(VecC, PVT);
9357           unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
9358           MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
9359           Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
9360           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9361           SDValue Ops[] = {DAG.getEntryNode(), VCP};
9362           MachinePointerInfo MPI =
9363               MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9364           return DAG.getMemIntrinsicNode(
9365               X86ISD::SUBV_BROADCAST_LOAD, dl, Tys, Ops, VVT, MPI, Alignment,
9366               MachineMemOperand::MOLoad);
9367         }
9368       }
9369     }
9370 
9371     // If we are moving a scalar into a vector (Ld must be set and all elements
9372     // but 1 are undef) and that operation is not obviously supported by
9373     // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
9374     // That's better than general shuffling and may eliminate a load to GPR and
9375     // move from scalar to vector register.
9376     if (!Ld || NumElts - NumUndefElts != 1)
9377       return SDValue();
9378     unsigned ScalarSize = Ld.getValueSizeInBits();
9379     if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
9380       return SDValue();
9381   }
9382 
9383   bool ConstSplatVal =
9384       (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
9385   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
9386 
9387   // TODO: Handle broadcasts of non-constant sequences.
9388 
9389   // Make sure that all of the users of a non-constant load are from the
9390   // BUILD_VECTOR node.
9391   // FIXME: Is the use count needed for non-constant, non-load case?
9392   if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
9393     return SDValue();
9394 
9395   unsigned ScalarSize = Ld.getValueSizeInBits();
9396   bool IsGE256 = (VT.getSizeInBits() >= 256);
9397 
9398   // When optimizing for size, generate up to 5 extra bytes for a broadcast
9399   // instruction to save 8 or more bytes of constant pool data.
9400   // TODO: If multiple splats are generated to load the same constant,
9401   // it may be detrimental to overall size. There needs to be a way to detect
9402   // that condition to know if this is truly a size win.
9403   bool OptForSize = DAG.shouldOptForSize();
9404 
9405   // Handle broadcasting a single constant scalar from the constant pool
9406   // into a vector.
9407   // On Sandybridge (no AVX2), it is still better to load a constant vector
9408   // from the constant pool and not to broadcast it from a scalar.
9409   // But override that restriction when optimizing for size.
9410   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
9411   if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
9412     EVT CVT = Ld.getValueType();
9413     assert(!CVT.isVector() && "Must not broadcast a vector type");
9414 
9415     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
9416     // For size optimization, also splat v2f64 and v2i64, and for size opt
9417     // with AVX2, also splat i8 and i16.
9418     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
9419     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
9420         (ScalarSize == 16 && Subtarget.hasFP16() && CVT.isFloatingPoint()) ||
9421         (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
9422       const Constant *C = nullptr;
9423       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
9424         C = CI->getConstantIntValue();
9425       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
9426         C = CF->getConstantFPValue();
9427 
9428       assert(C && "Invalid constant type");
9429 
9430       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9431       SDValue CP =
9432           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
9433       Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
9434 
9435       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9436       SDValue Ops[] = {DAG.getEntryNode(), CP};
9437       MachinePointerInfo MPI =
9438           MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9439       return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
9440                                      MPI, Alignment, MachineMemOperand::MOLoad);
9441     }
9442   }
9443 
9444   // Handle AVX2 in-register broadcasts.
9445   if (!IsLoad && Subtarget.hasInt256() &&
9446       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
9447     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
9448 
9449   // The scalar source must be a normal load.
9450   if (!IsLoad)
9451     return SDValue();
9452 
9453   // Make sure the non-chain result is only used by this build vector.
9454   if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
9455     return SDValue();
9456 
9457   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
9458       (Subtarget.hasVLX() && ScalarSize == 64)) {
9459     auto *LN = cast<LoadSDNode>(Ld);
9460     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9461     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
9462     SDValue BCast =
9463         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
9464                                 LN->getMemoryVT(), LN->getMemOperand());
9465     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
9466     return BCast;
9467   }
9468 
9469   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
9470   // double since there is no vbroadcastsd xmm
9471   if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
9472       (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
9473     auto *LN = cast<LoadSDNode>(Ld);
9474     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9475     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
9476     SDValue BCast =
9477         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
9478                                 LN->getMemoryVT(), LN->getMemOperand());
9479     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
9480     return BCast;
9481   }
9482 
9483   if (ScalarSize == 16 && Subtarget.hasFP16() && IsGE256)
9484     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
9485 
9486   // Unsupported broadcast.
9487   return SDValue();
9488 }
9489 
9490 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
9491 /// underlying vector and index.
9492 ///
9493 /// Modifies \p ExtractedFromVec to the real vector and returns the real
9494 /// index.
9495 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
9496                                          SDValue ExtIdx) {
9497   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
9498   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
9499     return Idx;
9500 
9501   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
9502   // lowered this:
9503   //   (extract_vector_elt (v8f32 %1), Constant<6>)
9504   // to:
9505   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
9506   //                           (extract_subvector (v8f32 %0), Constant<4>),
9507   //                           undef)
9508   //                       Constant<0>)
9509   // In this case the vector is the extract_subvector expression and the index
9510   // is 2, as specified by the shuffle.
9511   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
9512   SDValue ShuffleVec = SVOp->getOperand(0);
9513   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
9514   assert(ShuffleVecVT.getVectorElementType() ==
9515          ExtractedFromVec.getSimpleValueType().getVectorElementType());
9516 
9517   int ShuffleIdx = SVOp->getMaskElt(Idx);
9518   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
9519     ExtractedFromVec = ShuffleVec;
9520     return ShuffleIdx;
9521   }
9522   return Idx;
9523 }
9524 
9525 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
9526   MVT VT = Op.getSimpleValueType();
9527 
9528   // Skip if insert_vec_elt is not supported.
9529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9530   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
9531     return SDValue();
9532 
9533   SDLoc DL(Op);
9534   unsigned NumElems = Op.getNumOperands();
9535 
9536   SDValue VecIn1;
9537   SDValue VecIn2;
9538   SmallVector<unsigned, 4> InsertIndices;
9539   SmallVector<int, 8> Mask(NumElems, -1);
9540 
9541   for (unsigned i = 0; i != NumElems; ++i) {
9542     unsigned Opc = Op.getOperand(i).getOpcode();
9543 
9544     if (Opc == ISD::UNDEF)
9545       continue;
9546 
9547     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
9548       // Quit if more than 1 elements need inserting.
9549       if (InsertIndices.size() > 1)
9550         return SDValue();
9551 
9552       InsertIndices.push_back(i);
9553       continue;
9554     }
9555 
9556     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
9557     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
9558 
9559     // Quit if non-constant index.
9560     if (!isa<ConstantSDNode>(ExtIdx))
9561       return SDValue();
9562     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
9563 
9564     // Quit if extracted from vector of different type.
9565     if (ExtractedFromVec.getValueType() != VT)
9566       return SDValue();
9567 
9568     if (!VecIn1.getNode())
9569       VecIn1 = ExtractedFromVec;
9570     else if (VecIn1 != ExtractedFromVec) {
9571       if (!VecIn2.getNode())
9572         VecIn2 = ExtractedFromVec;
9573       else if (VecIn2 != ExtractedFromVec)
9574         // Quit if more than 2 vectors to shuffle
9575         return SDValue();
9576     }
9577 
9578     if (ExtractedFromVec == VecIn1)
9579       Mask[i] = Idx;
9580     else if (ExtractedFromVec == VecIn2)
9581       Mask[i] = Idx + NumElems;
9582   }
9583 
9584   if (!VecIn1.getNode())
9585     return SDValue();
9586 
9587   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9588   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
9589 
9590   for (unsigned Idx : InsertIndices)
9591     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
9592                      DAG.getIntPtrConstant(Idx, DL));
9593 
9594   return NV;
9595 }
9596 
9597 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
9598 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
9599                                      const X86Subtarget &Subtarget) {
9600 
9601   MVT VT = Op.getSimpleValueType();
9602   assert((VT.getVectorElementType() == MVT::i1) &&
9603          "Unexpected type in LowerBUILD_VECTORvXi1!");
9604 
9605   SDLoc dl(Op);
9606   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
9607       ISD::isBuildVectorAllOnes(Op.getNode()))
9608     return Op;
9609 
9610   uint64_t Immediate = 0;
9611   SmallVector<unsigned, 16> NonConstIdx;
9612   bool IsSplat = true;
9613   bool HasConstElts = false;
9614   int SplatIdx = -1;
9615   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
9616     SDValue In = Op.getOperand(idx);
9617     if (In.isUndef())
9618       continue;
9619     if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
9620       Immediate |= (InC->getZExtValue() & 0x1) << idx;
9621       HasConstElts = true;
9622     } else {
9623       NonConstIdx.push_back(idx);
9624     }
9625     if (SplatIdx < 0)
9626       SplatIdx = idx;
9627     else if (In != Op.getOperand(SplatIdx))
9628       IsSplat = false;
9629   }
9630 
9631   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
9632   if (IsSplat) {
9633     // The build_vector allows the scalar element to be larger than the vector
9634     // element type. We need to mask it to use as a condition unless we know
9635     // the upper bits are zero.
9636     // FIXME: Use computeKnownBits instead of checking specific opcode?
9637     SDValue Cond = Op.getOperand(SplatIdx);
9638     assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
9639     if (Cond.getOpcode() != ISD::SETCC)
9640       Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
9641                          DAG.getConstant(1, dl, MVT::i8));
9642 
9643     // Perform the select in the scalar domain so we can use cmov.
9644     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9645       SDValue Select = DAG.getSelect(dl, MVT::i32, Cond,
9646                                      DAG.getAllOnesConstant(dl, MVT::i32),
9647                                      DAG.getConstant(0, dl, MVT::i32));
9648       Select = DAG.getBitcast(MVT::v32i1, Select);
9649       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Select, Select);
9650     } else {
9651       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9652       SDValue Select = DAG.getSelect(dl, ImmVT, Cond,
9653                                      DAG.getAllOnesConstant(dl, ImmVT),
9654                                      DAG.getConstant(0, dl, ImmVT));
9655       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9656       Select = DAG.getBitcast(VecVT, Select);
9657       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
9658                          DAG.getIntPtrConstant(0, dl));
9659     }
9660   }
9661 
9662   // insert elements one by one
9663   SDValue DstVec;
9664   if (HasConstElts) {
9665     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9666       SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
9667       SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
9668       ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
9669       ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
9670       DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
9671     } else {
9672       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9673       SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
9674       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9675       DstVec = DAG.getBitcast(VecVT, Imm);
9676       DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
9677                            DAG.getIntPtrConstant(0, dl));
9678     }
9679   } else
9680     DstVec = DAG.getUNDEF(VT);
9681 
9682   for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
9683     unsigned InsertIdx = NonConstIdx[i];
9684     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
9685                          Op.getOperand(InsertIdx),
9686                          DAG.getIntPtrConstant(InsertIdx, dl));
9687   }
9688   return DstVec;
9689 }
9690 
9691 LLVM_ATTRIBUTE_UNUSED static bool isHorizOp(unsigned Opcode) {
9692   switch (Opcode) {
9693   case X86ISD::PACKSS:
9694   case X86ISD::PACKUS:
9695   case X86ISD::FHADD:
9696   case X86ISD::FHSUB:
9697   case X86ISD::HADD:
9698   case X86ISD::HSUB:
9699     return true;
9700   }
9701   return false;
9702 }
9703 
9704 /// This is a helper function of LowerToHorizontalOp().
9705 /// This function checks that the build_vector \p N in input implements a
9706 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
9707 /// may not match the layout of an x86 256-bit horizontal instruction.
9708 /// In other words, if this returns true, then some extraction/insertion will
9709 /// be required to produce a valid horizontal instruction.
9710 ///
9711 /// Parameter \p Opcode defines the kind of horizontal operation to match.
9712 /// For example, if \p Opcode is equal to ISD::ADD, then this function
9713 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
9714 /// is equal to ISD::SUB, then this function checks if this is a horizontal
9715 /// arithmetic sub.
9716 ///
9717 /// This function only analyzes elements of \p N whose indices are
9718 /// in range [BaseIdx, LastIdx).
9719 ///
9720 /// TODO: This function was originally used to match both real and fake partial
9721 /// horizontal operations, but the index-matching logic is incorrect for that.
9722 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
9723 /// code because it is only used for partial h-op matching now?
9724 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
9725                                   SelectionDAG &DAG,
9726                                   unsigned BaseIdx, unsigned LastIdx,
9727                                   SDValue &V0, SDValue &V1) {
9728   EVT VT = N->getValueType(0);
9729   assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
9730   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
9731   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
9732          "Invalid Vector in input!");
9733 
9734   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
9735   bool CanFold = true;
9736   unsigned ExpectedVExtractIdx = BaseIdx;
9737   unsigned NumElts = LastIdx - BaseIdx;
9738   V0 = DAG.getUNDEF(VT);
9739   V1 = DAG.getUNDEF(VT);
9740 
9741   // Check if N implements a horizontal binop.
9742   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
9743     SDValue Op = N->getOperand(i + BaseIdx);
9744 
9745     // Skip UNDEFs.
9746     if (Op->isUndef()) {
9747       // Update the expected vector extract index.
9748       if (i * 2 == NumElts)
9749         ExpectedVExtractIdx = BaseIdx;
9750       ExpectedVExtractIdx += 2;
9751       continue;
9752     }
9753 
9754     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
9755 
9756     if (!CanFold)
9757       break;
9758 
9759     SDValue Op0 = Op.getOperand(0);
9760     SDValue Op1 = Op.getOperand(1);
9761 
9762     // Try to match the following pattern:
9763     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
9764     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9765         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9766         Op0.getOperand(0) == Op1.getOperand(0) &&
9767         isa<ConstantSDNode>(Op0.getOperand(1)) &&
9768         isa<ConstantSDNode>(Op1.getOperand(1)));
9769     if (!CanFold)
9770       break;
9771 
9772     unsigned I0 = Op0.getConstantOperandVal(1);
9773     unsigned I1 = Op1.getConstantOperandVal(1);
9774 
9775     if (i * 2 < NumElts) {
9776       if (V0.isUndef()) {
9777         V0 = Op0.getOperand(0);
9778         if (V0.getValueType() != VT)
9779           return false;
9780       }
9781     } else {
9782       if (V1.isUndef()) {
9783         V1 = Op0.getOperand(0);
9784         if (V1.getValueType() != VT)
9785           return false;
9786       }
9787       if (i * 2 == NumElts)
9788         ExpectedVExtractIdx = BaseIdx;
9789     }
9790 
9791     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
9792     if (I0 == ExpectedVExtractIdx)
9793       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
9794     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
9795       // Try to match the following dag sequence:
9796       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
9797       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
9798     } else
9799       CanFold = false;
9800 
9801     ExpectedVExtractIdx += 2;
9802   }
9803 
9804   return CanFold;
9805 }
9806 
9807 /// Emit a sequence of two 128-bit horizontal add/sub followed by
9808 /// a concat_vector.
9809 ///
9810 /// This is a helper function of LowerToHorizontalOp().
9811 /// This function expects two 256-bit vectors called V0 and V1.
9812 /// At first, each vector is split into two separate 128-bit vectors.
9813 /// Then, the resulting 128-bit vectors are used to implement two
9814 /// horizontal binary operations.
9815 ///
9816 /// The kind of horizontal binary operation is defined by \p X86Opcode.
9817 ///
9818 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
9819 /// the two new horizontal binop.
9820 /// When Mode is set, the first horizontal binop dag node would take as input
9821 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
9822 /// horizontal binop dag node would take as input the lower 128-bit of V1
9823 /// and the upper 128-bit of V1.
9824 ///   Example:
9825 ///     HADD V0_LO, V0_HI
9826 ///     HADD V1_LO, V1_HI
9827 ///
9828 /// Otherwise, the first horizontal binop dag node takes as input the lower
9829 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
9830 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
9831 ///   Example:
9832 ///     HADD V0_LO, V1_LO
9833 ///     HADD V0_HI, V1_HI
9834 ///
9835 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
9836 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
9837 /// the upper 128-bits of the result.
9838 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
9839                                      const SDLoc &DL, SelectionDAG &DAG,
9840                                      unsigned X86Opcode, bool Mode,
9841                                      bool isUndefLO, bool isUndefHI) {
9842   MVT VT = V0.getSimpleValueType();
9843   assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
9844          "Invalid nodes in input!");
9845 
9846   unsigned NumElts = VT.getVectorNumElements();
9847   SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
9848   SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
9849   SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
9850   SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
9851   MVT NewVT = V0_LO.getSimpleValueType();
9852 
9853   SDValue LO = DAG.getUNDEF(NewVT);
9854   SDValue HI = DAG.getUNDEF(NewVT);
9855 
9856   if (Mode) {
9857     // Don't emit a horizontal binop if the result is expected to be UNDEF.
9858     if (!isUndefLO && !V0->isUndef())
9859       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
9860     if (!isUndefHI && !V1->isUndef())
9861       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
9862   } else {
9863     // Don't emit a horizontal binop if the result is expected to be UNDEF.
9864     if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
9865       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
9866 
9867     if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
9868       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
9869   }
9870 
9871   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
9872 }
9873 
9874 /// Returns true iff \p BV builds a vector with the result equivalent to
9875 /// the result of ADDSUB/SUBADD operation.
9876 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
9877 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
9878 /// \p Opnd0 and \p Opnd1.
9879 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
9880                              const X86Subtarget &Subtarget, SelectionDAG &DAG,
9881                              SDValue &Opnd0, SDValue &Opnd1,
9882                              unsigned &NumExtracts,
9883                              bool &IsSubAdd) {
9884 
9885   MVT VT = BV->getSimpleValueType(0);
9886   if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
9887     return false;
9888 
9889   unsigned NumElts = VT.getVectorNumElements();
9890   SDValue InVec0 = DAG.getUNDEF(VT);
9891   SDValue InVec1 = DAG.getUNDEF(VT);
9892 
9893   NumExtracts = 0;
9894 
9895   // Odd-numbered elements in the input build vector are obtained from
9896   // adding/subtracting two integer/float elements.
9897   // Even-numbered elements in the input build vector are obtained from
9898   // subtracting/adding two integer/float elements.
9899   unsigned Opc[2] = {0, 0};
9900   for (unsigned i = 0, e = NumElts; i != e; ++i) {
9901     SDValue Op = BV->getOperand(i);
9902 
9903     // Skip 'undef' values.
9904     unsigned Opcode = Op.getOpcode();
9905     if (Opcode == ISD::UNDEF)
9906       continue;
9907 
9908     // Early exit if we found an unexpected opcode.
9909     if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
9910       return false;
9911 
9912     SDValue Op0 = Op.getOperand(0);
9913     SDValue Op1 = Op.getOperand(1);
9914 
9915     // Try to match the following pattern:
9916     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
9917     // Early exit if we cannot match that sequence.
9918     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9919         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9920         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9921         Op0.getOperand(1) != Op1.getOperand(1))
9922       return false;
9923 
9924     unsigned I0 = Op0.getConstantOperandVal(1);
9925     if (I0 != i)
9926       return false;
9927 
9928     // We found a valid add/sub node, make sure its the same opcode as previous
9929     // elements for this parity.
9930     if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
9931       return false;
9932     Opc[i % 2] = Opcode;
9933 
9934     // Update InVec0 and InVec1.
9935     if (InVec0.isUndef()) {
9936       InVec0 = Op0.getOperand(0);
9937       if (InVec0.getSimpleValueType() != VT)
9938         return false;
9939     }
9940     if (InVec1.isUndef()) {
9941       InVec1 = Op1.getOperand(0);
9942       if (InVec1.getSimpleValueType() != VT)
9943         return false;
9944     }
9945 
9946     // Make sure that operands in input to each add/sub node always
9947     // come from a same pair of vectors.
9948     if (InVec0 != Op0.getOperand(0)) {
9949       if (Opcode == ISD::FSUB)
9950         return false;
9951 
9952       // FADD is commutable. Try to commute the operands
9953       // and then test again.
9954       std::swap(Op0, Op1);
9955       if (InVec0 != Op0.getOperand(0))
9956         return false;
9957     }
9958 
9959     if (InVec1 != Op1.getOperand(0))
9960       return false;
9961 
9962     // Increment the number of extractions done.
9963     ++NumExtracts;
9964   }
9965 
9966   // Ensure we have found an opcode for both parities and that they are
9967   // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
9968   // inputs are undef.
9969   if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
9970       InVec0.isUndef() || InVec1.isUndef())
9971     return false;
9972 
9973   IsSubAdd = Opc[0] == ISD::FADD;
9974 
9975   Opnd0 = InVec0;
9976   Opnd1 = InVec1;
9977   return true;
9978 }
9979 
9980 /// Returns true if is possible to fold MUL and an idiom that has already been
9981 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
9982 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
9983 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
9984 ///
9985 /// Prior to calling this function it should be known that there is some
9986 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
9987 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
9988 /// before replacement of such SDNode with ADDSUB operation. Thus the number
9989 /// of \p Opnd0 uses is expected to be equal to 2.
9990 /// For example, this function may be called for the following IR:
9991 ///    %AB = fmul fast <2 x double> %A, %B
9992 ///    %Sub = fsub fast <2 x double> %AB, %C
9993 ///    %Add = fadd fast <2 x double> %AB, %C
9994 ///    %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
9995 ///                            <2 x i32> <i32 0, i32 3>
9996 /// There is a def for %Addsub here, which potentially can be replaced by
9997 /// X86ISD::ADDSUB operation:
9998 ///    %Addsub = X86ISD::ADDSUB %AB, %C
9999 /// and such ADDSUB can further be replaced with FMADDSUB:
10000 ///    %Addsub = FMADDSUB %A, %B, %C.
10001 ///
10002 /// The main reason why this method is called before the replacement of the
10003 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
10004 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
10005 /// FMADDSUB is.
10006 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
10007                                  SelectionDAG &DAG,
10008                                  SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
10009                                  unsigned ExpectedUses) {
10010   if (Opnd0.getOpcode() != ISD::FMUL ||
10011       !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
10012     return false;
10013 
10014   // FIXME: These checks must match the similar ones in
10015   // DAGCombiner::visitFADDForFMACombine. It would be good to have one
10016   // function that would answer if it is Ok to fuse MUL + ADD to FMADD
10017   // or MUL + ADDSUB to FMADDSUB.
10018   const TargetOptions &Options = DAG.getTarget().Options;
10019   bool AllowFusion =
10020       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
10021   if (!AllowFusion)
10022     return false;
10023 
10024   Opnd2 = Opnd1;
10025   Opnd1 = Opnd0.getOperand(1);
10026   Opnd0 = Opnd0.getOperand(0);
10027 
10028   return true;
10029 }
10030 
10031 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
10032 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
10033 /// X86ISD::FMSUBADD node.
10034 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
10035                                        const X86Subtarget &Subtarget,
10036                                        SelectionDAG &DAG) {
10037   SDValue Opnd0, Opnd1;
10038   unsigned NumExtracts;
10039   bool IsSubAdd;
10040   if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
10041                         IsSubAdd))
10042     return SDValue();
10043 
10044   MVT VT = BV->getSimpleValueType(0);
10045   SDLoc DL(BV);
10046 
10047   // Try to generate X86ISD::FMADDSUB node here.
10048   SDValue Opnd2;
10049   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
10050     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
10051     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
10052   }
10053 
10054   // We only support ADDSUB.
10055   if (IsSubAdd)
10056     return SDValue();
10057 
10058   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
10059   // the ADDSUB idiom has been successfully recognized. There are no known
10060   // X86 targets with 512-bit ADDSUB instructions!
10061   // 512-bit ADDSUB idiom recognition was needed only as part of FMADDSUB idiom
10062   // recognition.
10063   if (VT.is512BitVector())
10064     return SDValue();
10065 
10066   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
10067 }
10068 
10069 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
10070                              unsigned &HOpcode, SDValue &V0, SDValue &V1) {
10071   // Initialize outputs to known values.
10072   MVT VT = BV->getSimpleValueType(0);
10073   HOpcode = ISD::DELETED_NODE;
10074   V0 = DAG.getUNDEF(VT);
10075   V1 = DAG.getUNDEF(VT);
10076 
10077   // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
10078   // half of the result is calculated independently from the 128-bit halves of
10079   // the inputs, so that makes the index-checking logic below more complicated.
10080   unsigned NumElts = VT.getVectorNumElements();
10081   unsigned GenericOpcode = ISD::DELETED_NODE;
10082   unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
10083   unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
10084   unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
10085   for (unsigned i = 0; i != Num128BitChunks; ++i) {
10086     for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
10087       // Ignore undef elements.
10088       SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
10089       if (Op.isUndef())
10090         continue;
10091 
10092       // If there's an opcode mismatch, we're done.
10093       if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
10094         return false;
10095 
10096       // Initialize horizontal opcode.
10097       if (HOpcode == ISD::DELETED_NODE) {
10098         GenericOpcode = Op.getOpcode();
10099         switch (GenericOpcode) {
10100         case ISD::ADD: HOpcode = X86ISD::HADD; break;
10101         case ISD::SUB: HOpcode = X86ISD::HSUB; break;
10102         case ISD::FADD: HOpcode = X86ISD::FHADD; break;
10103         case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
10104         default: return false;
10105         }
10106       }
10107 
10108       SDValue Op0 = Op.getOperand(0);
10109       SDValue Op1 = Op.getOperand(1);
10110       if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10111           Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10112           Op0.getOperand(0) != Op1.getOperand(0) ||
10113           !isa<ConstantSDNode>(Op0.getOperand(1)) ||
10114           !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
10115         return false;
10116 
10117       // The source vector is chosen based on which 64-bit half of the
10118       // destination vector is being calculated.
10119       if (j < NumEltsIn64Bits) {
10120         if (V0.isUndef())
10121           V0 = Op0.getOperand(0);
10122       } else {
10123         if (V1.isUndef())
10124           V1 = Op0.getOperand(0);
10125       }
10126 
10127       SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
10128       if (SourceVec != Op0.getOperand(0))
10129         return false;
10130 
10131       // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
10132       unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
10133       unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
10134       unsigned ExpectedIndex = i * NumEltsIn128Bits +
10135                                (j % NumEltsIn64Bits) * 2;
10136       if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
10137         continue;
10138 
10139       // If this is not a commutative op, this does not match.
10140       if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
10141         return false;
10142 
10143       // Addition is commutative, so try swapping the extract indexes.
10144       // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
10145       if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
10146         continue;
10147 
10148       // Extract indexes do not match horizontal requirement.
10149       return false;
10150     }
10151   }
10152   // We matched. Opcode and operands are returned by reference as arguments.
10153   return true;
10154 }
10155 
10156 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
10157                                     SelectionDAG &DAG, unsigned HOpcode,
10158                                     SDValue V0, SDValue V1) {
10159   // If either input vector is not the same size as the build vector,
10160   // extract/insert the low bits to the correct size.
10161   // This is free (examples: zmm --> xmm, xmm --> ymm).
10162   MVT VT = BV->getSimpleValueType(0);
10163   unsigned Width = VT.getSizeInBits();
10164   if (V0.getValueSizeInBits() > Width)
10165     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
10166   else if (V0.getValueSizeInBits() < Width)
10167     V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
10168 
10169   if (V1.getValueSizeInBits() > Width)
10170     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
10171   else if (V1.getValueSizeInBits() < Width)
10172     V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
10173 
10174   unsigned NumElts = VT.getVectorNumElements();
10175   APInt DemandedElts = APInt::getAllOnes(NumElts);
10176   for (unsigned i = 0; i != NumElts; ++i)
10177     if (BV->getOperand(i).isUndef())
10178       DemandedElts.clearBit(i);
10179 
10180   // If we don't need the upper xmm, then perform as a xmm hop.
10181   unsigned HalfNumElts = NumElts / 2;
10182   if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
10183     MVT HalfVT = VT.getHalfNumVectorElementsVT();
10184     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
10185     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
10186     SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
10187     return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
10188   }
10189 
10190   return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
10191 }
10192 
10193 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
10194 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
10195                                    const X86Subtarget &Subtarget,
10196                                    SelectionDAG &DAG) {
10197   // We need at least 2 non-undef elements to make this worthwhile by default.
10198   unsigned NumNonUndefs =
10199       count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
10200   if (NumNonUndefs < 2)
10201     return SDValue();
10202 
10203   // There are 4 sets of horizontal math operations distinguished by type:
10204   // int/FP at 128-bit/256-bit. Each type was introduced with a different
10205   // subtarget feature. Try to match those "native" patterns first.
10206   MVT VT = BV->getSimpleValueType(0);
10207   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
10208       ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
10209       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
10210       ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
10211     unsigned HOpcode;
10212     SDValue V0, V1;
10213     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
10214       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
10215   }
10216 
10217   // Try harder to match 256-bit ops by using extract/concat.
10218   if (!Subtarget.hasAVX() || !VT.is256BitVector())
10219     return SDValue();
10220 
10221   // Count the number of UNDEF operands in the build_vector in input.
10222   unsigned NumElts = VT.getVectorNumElements();
10223   unsigned Half = NumElts / 2;
10224   unsigned NumUndefsLO = 0;
10225   unsigned NumUndefsHI = 0;
10226   for (unsigned i = 0, e = Half; i != e; ++i)
10227     if (BV->getOperand(i)->isUndef())
10228       NumUndefsLO++;
10229 
10230   for (unsigned i = Half, e = NumElts; i != e; ++i)
10231     if (BV->getOperand(i)->isUndef())
10232       NumUndefsHI++;
10233 
10234   SDLoc DL(BV);
10235   SDValue InVec0, InVec1;
10236   if (VT == MVT::v8i32 || VT == MVT::v16i16) {
10237     SDValue InVec2, InVec3;
10238     unsigned X86Opcode;
10239     bool CanFold = true;
10240 
10241     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
10242         isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
10243                               InVec3) &&
10244         ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
10245         ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
10246       X86Opcode = X86ISD::HADD;
10247     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
10248                                    InVec1) &&
10249              isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
10250                                    InVec3) &&
10251              ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
10252              ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
10253       X86Opcode = X86ISD::HSUB;
10254     else
10255       CanFold = false;
10256 
10257     if (CanFold) {
10258       // Do not try to expand this build_vector into a pair of horizontal
10259       // add/sub if we can emit a pair of scalar add/sub.
10260       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
10261         return SDValue();
10262 
10263       // Convert this build_vector into a pair of horizontal binops followed by
10264       // a concat vector. We must adjust the outputs from the partial horizontal
10265       // matching calls above to account for undefined vector halves.
10266       SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
10267       SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
10268       assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
10269       bool isUndefLO = NumUndefsLO == Half;
10270       bool isUndefHI = NumUndefsHI == Half;
10271       return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
10272                                    isUndefHI);
10273     }
10274   }
10275 
10276   if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
10277       VT == MVT::v16i16) {
10278     unsigned X86Opcode;
10279     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
10280       X86Opcode = X86ISD::HADD;
10281     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
10282                                    InVec1))
10283       X86Opcode = X86ISD::HSUB;
10284     else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
10285                                    InVec1))
10286       X86Opcode = X86ISD::FHADD;
10287     else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
10288                                    InVec1))
10289       X86Opcode = X86ISD::FHSUB;
10290     else
10291       return SDValue();
10292 
10293     // Don't try to expand this build_vector into a pair of horizontal add/sub
10294     // if we can simply emit a pair of scalar add/sub.
10295     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
10296       return SDValue();
10297 
10298     // Convert this build_vector into two horizontal add/sub followed by
10299     // a concat vector.
10300     bool isUndefLO = NumUndefsLO == Half;
10301     bool isUndefHI = NumUndefsHI == Half;
10302     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
10303                                  isUndefLO, isUndefHI);
10304   }
10305 
10306   return SDValue();
10307 }
10308 
10309 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
10310                           SelectionDAG &DAG);
10311 
10312 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
10313 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
10314 /// just apply the bit to the vectors.
10315 /// NOTE: Its not in our interest to start make a general purpose vectorizer
10316 /// from this, but enough scalar bit operations are created from the later
10317 /// legalization + scalarization stages to need basic support.
10318 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
10319                                        const X86Subtarget &Subtarget,
10320                                        SelectionDAG &DAG) {
10321   SDLoc DL(Op);
10322   MVT VT = Op->getSimpleValueType(0);
10323   unsigned NumElems = VT.getVectorNumElements();
10324   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10325 
10326   // Check that all elements have the same opcode.
10327   // TODO: Should we allow UNDEFS and if so how many?
10328   unsigned Opcode = Op->getOperand(0).getOpcode();
10329   for (unsigned i = 1; i < NumElems; ++i)
10330     if (Opcode != Op->getOperand(i).getOpcode())
10331       return SDValue();
10332 
10333   // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
10334   bool IsShift = false;
10335   switch (Opcode) {
10336   default:
10337     return SDValue();
10338   case ISD::SHL:
10339   case ISD::SRL:
10340   case ISD::SRA:
10341     IsShift = true;
10342     break;
10343   case ISD::AND:
10344   case ISD::XOR:
10345   case ISD::OR:
10346     // Don't do this if the buildvector is a splat - we'd replace one
10347     // constant with an entire vector.
10348     if (Op->getSplatValue())
10349       return SDValue();
10350     if (!TLI.isOperationLegalOrPromote(Opcode, VT))
10351       return SDValue();
10352     break;
10353   }
10354 
10355   SmallVector<SDValue, 4> LHSElts, RHSElts;
10356   for (SDValue Elt : Op->ops()) {
10357     SDValue LHS = Elt.getOperand(0);
10358     SDValue RHS = Elt.getOperand(1);
10359 
10360     // We expect the canonicalized RHS operand to be the constant.
10361     if (!isa<ConstantSDNode>(RHS))
10362       return SDValue();
10363 
10364     // Extend shift amounts.
10365     if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
10366       if (!IsShift)
10367         return SDValue();
10368       RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
10369     }
10370 
10371     LHSElts.push_back(LHS);
10372     RHSElts.push_back(RHS);
10373   }
10374 
10375   // Limit to shifts by uniform immediates.
10376   // TODO: Only accept vXi8/vXi64 special cases?
10377   // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
10378   if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
10379     return SDValue();
10380 
10381   SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
10382   SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
10383   SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
10384 
10385   if (!IsShift)
10386     return Res;
10387 
10388   // Immediately lower the shift to ensure the constant build vector doesn't
10389   // get converted to a constant pool before the shift is lowered.
10390   return LowerShift(Res, Subtarget, DAG);
10391 }
10392 
10393 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
10394 /// functionality to do this, so it's all zeros, all ones, or some derivation
10395 /// that is cheap to calculate.
10396 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
10397                                          const X86Subtarget &Subtarget) {
10398   SDLoc DL(Op);
10399   MVT VT = Op.getSimpleValueType();
10400 
10401   // Vectors containing all zeros can be matched by pxor and xorps.
10402   if (ISD::isBuildVectorAllZeros(Op.getNode()))
10403     return Op;
10404 
10405   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
10406   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
10407   // vpcmpeqd on 256-bit vectors.
10408   if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
10409     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
10410       return Op;
10411 
10412     return getOnesVector(VT, DAG, DL);
10413   }
10414 
10415   return SDValue();
10416 }
10417 
10418 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
10419 /// from a vector of source values and a vector of extraction indices.
10420 /// The vectors might be manipulated to match the type of the permute op.
10421 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
10422                                      SDLoc &DL, SelectionDAG &DAG,
10423                                      const X86Subtarget &Subtarget) {
10424   MVT ShuffleVT = VT;
10425   EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
10426   unsigned NumElts = VT.getVectorNumElements();
10427   unsigned SizeInBits = VT.getSizeInBits();
10428 
10429   // Adjust IndicesVec to match VT size.
10430   assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
10431          "Illegal variable permute mask size");
10432   if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
10433     // Narrow/widen the indices vector to the correct size.
10434     if (IndicesVec.getValueSizeInBits() > SizeInBits)
10435       IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
10436                                     NumElts * VT.getScalarSizeInBits());
10437     else if (IndicesVec.getValueSizeInBits() < SizeInBits)
10438       IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
10439                                   SDLoc(IndicesVec), SizeInBits);
10440     // Zero-extend the index elements within the vector.
10441     if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
10442       IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
10443                                IndicesVT, IndicesVec);
10444   }
10445   IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
10446 
10447   // Handle SrcVec that don't match VT type.
10448   if (SrcVec.getValueSizeInBits() != SizeInBits) {
10449     if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
10450       // Handle larger SrcVec by treating it as a larger permute.
10451       unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
10452       VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
10453       IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
10454       IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
10455                                   Subtarget, DAG, SDLoc(IndicesVec));
10456       SDValue NewSrcVec =
10457           createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
10458       if (NewSrcVec)
10459         return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
10460       return SDValue();
10461     } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
10462       // Widen smaller SrcVec to match VT.
10463       SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
10464     } else
10465       return SDValue();
10466   }
10467 
10468   auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
10469     assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
10470     EVT SrcVT = Idx.getValueType();
10471     unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
10472     uint64_t IndexScale = 0;
10473     uint64_t IndexOffset = 0;
10474 
10475     // If we're scaling a smaller permute op, then we need to repeat the
10476     // indices, scaling and offsetting them as well.
10477     // e.g. v4i32 -> v16i8 (Scale = 4)
10478     // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
10479     // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
10480     for (uint64_t i = 0; i != Scale; ++i) {
10481       IndexScale |= Scale << (i * NumDstBits);
10482       IndexOffset |= i << (i * NumDstBits);
10483     }
10484 
10485     Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
10486                       DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
10487     Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
10488                       DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
10489     return Idx;
10490   };
10491 
10492   unsigned Opcode = 0;
10493   switch (VT.SimpleTy) {
10494   default:
10495     break;
10496   case MVT::v16i8:
10497     if (Subtarget.hasSSSE3())
10498       Opcode = X86ISD::PSHUFB;
10499     break;
10500   case MVT::v8i16:
10501     if (Subtarget.hasVLX() && Subtarget.hasBWI())
10502       Opcode = X86ISD::VPERMV;
10503     else if (Subtarget.hasSSSE3()) {
10504       Opcode = X86ISD::PSHUFB;
10505       ShuffleVT = MVT::v16i8;
10506     }
10507     break;
10508   case MVT::v4f32:
10509   case MVT::v4i32:
10510     if (Subtarget.hasAVX()) {
10511       Opcode = X86ISD::VPERMILPV;
10512       ShuffleVT = MVT::v4f32;
10513     } else if (Subtarget.hasSSSE3()) {
10514       Opcode = X86ISD::PSHUFB;
10515       ShuffleVT = MVT::v16i8;
10516     }
10517     break;
10518   case MVT::v2f64:
10519   case MVT::v2i64:
10520     if (Subtarget.hasAVX()) {
10521       // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
10522       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10523       Opcode = X86ISD::VPERMILPV;
10524       ShuffleVT = MVT::v2f64;
10525     } else if (Subtarget.hasSSE41()) {
10526       // SSE41 can compare v2i64 - select between indices 0 and 1.
10527       return DAG.getSelectCC(
10528           DL, IndicesVec,
10529           getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
10530           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
10531           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
10532           ISD::CondCode::SETEQ);
10533     }
10534     break;
10535   case MVT::v32i8:
10536     if (Subtarget.hasVLX() && Subtarget.hasVBMI())
10537       Opcode = X86ISD::VPERMV;
10538     else if (Subtarget.hasXOP()) {
10539       SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
10540       SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
10541       SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
10542       SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
10543       return DAG.getNode(
10544           ISD::CONCAT_VECTORS, DL, VT,
10545           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
10546           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
10547     } else if (Subtarget.hasAVX()) {
10548       SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
10549       SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
10550       SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
10551       SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
10552       auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
10553                               ArrayRef<SDValue> Ops) {
10554         // Permute Lo and Hi and then select based on index range.
10555         // This works as SHUFB uses bits[3:0] to permute elements and we don't
10556         // care about the bit[7] as its just an index vector.
10557         SDValue Idx = Ops[2];
10558         EVT VT = Idx.getValueType();
10559         return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
10560                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
10561                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
10562                                ISD::CondCode::SETGT);
10563       };
10564       SDValue Ops[] = {LoLo, HiHi, IndicesVec};
10565       return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
10566                               PSHUFBBuilder);
10567     }
10568     break;
10569   case MVT::v16i16:
10570     if (Subtarget.hasVLX() && Subtarget.hasBWI())
10571       Opcode = X86ISD::VPERMV;
10572     else if (Subtarget.hasAVX()) {
10573       // Scale to v32i8 and perform as v32i8.
10574       IndicesVec = ScaleIndices(IndicesVec, 2);
10575       return DAG.getBitcast(
10576           VT, createVariablePermute(
10577                   MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
10578                   DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
10579     }
10580     break;
10581   case MVT::v8f32:
10582   case MVT::v8i32:
10583     if (Subtarget.hasAVX2())
10584       Opcode = X86ISD::VPERMV;
10585     else if (Subtarget.hasAVX()) {
10586       SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
10587       SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
10588                                           {0, 1, 2, 3, 0, 1, 2, 3});
10589       SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
10590                                           {4, 5, 6, 7, 4, 5, 6, 7});
10591       if (Subtarget.hasXOP())
10592         return DAG.getBitcast(
10593             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
10594                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10595       // Permute Lo and Hi and then select based on index range.
10596       // This works as VPERMILPS only uses index bits[0:1] to permute elements.
10597       SDValue Res = DAG.getSelectCC(
10598           DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
10599           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
10600           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
10601           ISD::CondCode::SETGT);
10602       return DAG.getBitcast(VT, Res);
10603     }
10604     break;
10605   case MVT::v4i64:
10606   case MVT::v4f64:
10607     if (Subtarget.hasAVX512()) {
10608       if (!Subtarget.hasVLX()) {
10609         MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
10610         SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
10611                                 SDLoc(SrcVec));
10612         IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
10613                                     DAG, SDLoc(IndicesVec));
10614         SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
10615                                             DAG, Subtarget);
10616         return extract256BitVector(Res, 0, DAG, DL);
10617       }
10618       Opcode = X86ISD::VPERMV;
10619     } else if (Subtarget.hasAVX()) {
10620       SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
10621       SDValue LoLo =
10622           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
10623       SDValue HiHi =
10624           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
10625       // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
10626       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10627       if (Subtarget.hasXOP())
10628         return DAG.getBitcast(
10629             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
10630                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10631       // Permute Lo and Hi and then select based on index range.
10632       // This works as VPERMILPD only uses index bit[1] to permute elements.
10633       SDValue Res = DAG.getSelectCC(
10634           DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
10635           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
10636           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
10637           ISD::CondCode::SETGT);
10638       return DAG.getBitcast(VT, Res);
10639     }
10640     break;
10641   case MVT::v64i8:
10642     if (Subtarget.hasVBMI())
10643       Opcode = X86ISD::VPERMV;
10644     break;
10645   case MVT::v32i16:
10646     if (Subtarget.hasBWI())
10647       Opcode = X86ISD::VPERMV;
10648     break;
10649   case MVT::v16f32:
10650   case MVT::v16i32:
10651   case MVT::v8f64:
10652   case MVT::v8i64:
10653     if (Subtarget.hasAVX512())
10654       Opcode = X86ISD::VPERMV;
10655     break;
10656   }
10657   if (!Opcode)
10658     return SDValue();
10659 
10660   assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
10661          (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
10662          "Illegal variable permute shuffle type");
10663 
10664   uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
10665   if (Scale > 1)
10666     IndicesVec = ScaleIndices(IndicesVec, Scale);
10667 
10668   EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
10669   IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
10670 
10671   SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
10672   SDValue Res = Opcode == X86ISD::VPERMV
10673                     ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
10674                     : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
10675   return DAG.getBitcast(VT, Res);
10676 }
10677 
10678 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
10679 // reasoned to be a permutation of a vector by indices in a non-constant vector.
10680 // (build_vector (extract_elt V, (extract_elt I, 0)),
10681 //               (extract_elt V, (extract_elt I, 1)),
10682 //                    ...
10683 // ->
10684 // (vpermv I, V)
10685 //
10686 // TODO: Handle undefs
10687 // TODO: Utilize pshufb and zero mask blending to support more efficient
10688 // construction of vectors with constant-0 elements.
10689 static SDValue
10690 LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
10691                                    const X86Subtarget &Subtarget) {
10692   SDValue SrcVec, IndicesVec;
10693   // Check for a match of the permute source vector and permute index elements.
10694   // This is done by checking that the i-th build_vector operand is of the form:
10695   // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
10696   for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
10697     SDValue Op = V.getOperand(Idx);
10698     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10699       return SDValue();
10700 
10701     // If this is the first extract encountered in V, set the source vector,
10702     // otherwise verify the extract is from the previously defined source
10703     // vector.
10704     if (!SrcVec)
10705       SrcVec = Op.getOperand(0);
10706     else if (SrcVec != Op.getOperand(0))
10707       return SDValue();
10708     SDValue ExtractedIndex = Op->getOperand(1);
10709     // Peek through extends.
10710     if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
10711         ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
10712       ExtractedIndex = ExtractedIndex.getOperand(0);
10713     if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10714       return SDValue();
10715 
10716     // If this is the first extract from the index vector candidate, set the
10717     // indices vector, otherwise verify the extract is from the previously
10718     // defined indices vector.
10719     if (!IndicesVec)
10720       IndicesVec = ExtractedIndex.getOperand(0);
10721     else if (IndicesVec != ExtractedIndex.getOperand(0))
10722       return SDValue();
10723 
10724     auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
10725     if (!PermIdx || PermIdx->getAPIntValue() != Idx)
10726       return SDValue();
10727   }
10728 
10729   SDLoc DL(V);
10730   MVT VT = V.getSimpleValueType();
10731   return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
10732 }
10733 
10734 SDValue
10735 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
10736   SDLoc dl(Op);
10737 
10738   MVT VT = Op.getSimpleValueType();
10739   MVT EltVT = VT.getVectorElementType();
10740   unsigned NumElems = Op.getNumOperands();
10741 
10742   // Generate vectors for predicate vectors.
10743   if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
10744     return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
10745 
10746   if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
10747     return VectorConstant;
10748 
10749   unsigned EVTBits = EltVT.getSizeInBits();
10750   APInt UndefMask = APInt::getZero(NumElems);
10751   APInt ZeroMask = APInt::getZero(NumElems);
10752   APInt NonZeroMask = APInt::getZero(NumElems);
10753   bool IsAllConstants = true;
10754   SmallSet<SDValue, 8> Values;
10755   unsigned NumConstants = NumElems;
10756   for (unsigned i = 0; i < NumElems; ++i) {
10757     SDValue Elt = Op.getOperand(i);
10758     if (Elt.isUndef()) {
10759       UndefMask.setBit(i);
10760       continue;
10761     }
10762     Values.insert(Elt);
10763     if (!isa<ConstantSDNode>(Elt) && !isa<ConstantFPSDNode>(Elt)) {
10764       IsAllConstants = false;
10765       NumConstants--;
10766     }
10767     if (X86::isZeroNode(Elt)) {
10768       ZeroMask.setBit(i);
10769     } else {
10770       NonZeroMask.setBit(i);
10771     }
10772   }
10773 
10774   // All undef vector. Return an UNDEF. All zero vectors were handled above.
10775   if (NonZeroMask == 0) {
10776     assert(UndefMask.isAllOnes() && "Fully undef mask expected");
10777     return DAG.getUNDEF(VT);
10778   }
10779 
10780   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
10781 
10782   // If the upper elts of a ymm/zmm are undef/zero then we might be better off
10783   // lowering to a smaller build vector and padding with undef/zero.
10784   if ((VT.is256BitVector() || VT.is512BitVector()) &&
10785       !isFoldableUseOfShuffle(BV)) {
10786     unsigned UpperElems = NumElems / 2;
10787     APInt UndefOrZeroMask = UndefMask | ZeroMask;
10788     unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countLeadingOnes();
10789     if (NumUpperUndefsOrZeros >= UpperElems) {
10790       if (VT.is512BitVector() &&
10791           NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
10792         UpperElems = NumElems - (NumElems / 4);
10793       bool UndefUpper = UndefMask.countLeadingOnes() >= UpperElems;
10794       MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
10795       SDValue NewBV =
10796           DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
10797       return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
10798     }
10799   }
10800 
10801   if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
10802     return AddSub;
10803   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
10804     return HorizontalOp;
10805   if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
10806     return Broadcast;
10807   if (SDValue BitOp = lowerBuildVectorToBitOp(BV, Subtarget, DAG))
10808     return BitOp;
10809 
10810   unsigned NumZero = ZeroMask.countPopulation();
10811   unsigned NumNonZero = NonZeroMask.countPopulation();
10812 
10813   // If we are inserting one variable into a vector of non-zero constants, try
10814   // to avoid loading each constant element as a scalar. Load the constants as a
10815   // vector and then insert the variable scalar element. If insertion is not
10816   // supported, fall back to a shuffle to get the scalar blended with the
10817   // constants. Insertion into a zero vector is handled as a special-case
10818   // somewhere below here.
10819   if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
10820       (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
10821        isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
10822     // Create an all-constant vector. The variable element in the old
10823     // build vector is replaced by undef in the constant vector. Save the
10824     // variable scalar element and its index for use in the insertelement.
10825     LLVMContext &Context = *DAG.getContext();
10826     Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
10827     SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
10828     SDValue VarElt;
10829     SDValue InsIndex;
10830     for (unsigned i = 0; i != NumElems; ++i) {
10831       SDValue Elt = Op.getOperand(i);
10832       if (auto *C = dyn_cast<ConstantSDNode>(Elt))
10833         ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
10834       else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
10835         ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
10836       else if (!Elt.isUndef()) {
10837         assert(!VarElt.getNode() && !InsIndex.getNode() &&
10838                "Expected one variable element in this vector");
10839         VarElt = Elt;
10840         InsIndex = DAG.getVectorIdxConstant(i, dl);
10841       }
10842     }
10843     Constant *CV = ConstantVector::get(ConstVecOps);
10844     SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
10845 
10846     // The constants we just created may not be legal (eg, floating point). We
10847     // must lower the vector right here because we can not guarantee that we'll
10848     // legalize it before loading it. This is also why we could not just create
10849     // a new build vector here. If the build vector contains illegal constants,
10850     // it could get split back up into a series of insert elements.
10851     // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
10852     SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
10853     MachineFunction &MF = DAG.getMachineFunction();
10854     MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
10855     SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
10856     unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
10857     unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
10858     if (InsertC < NumEltsInLow128Bits)
10859       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
10860 
10861     // There's no good way to insert into the high elements of a >128-bit
10862     // vector, so use shuffles to avoid an extract/insert sequence.
10863     assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
10864     assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
10865     SmallVector<int, 8> ShuffleMask;
10866     unsigned NumElts = VT.getVectorNumElements();
10867     for (unsigned i = 0; i != NumElts; ++i)
10868       ShuffleMask.push_back(i == InsertC ? NumElts : i);
10869     SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
10870     return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
10871   }
10872 
10873   // Special case for single non-zero, non-undef, element.
10874   if (NumNonZero == 1) {
10875     unsigned Idx = NonZeroMask.countTrailingZeros();
10876     SDValue Item = Op.getOperand(Idx);
10877 
10878     // If we have a constant or non-constant insertion into the low element of
10879     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
10880     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
10881     // depending on what the source datatype is.
10882     if (Idx == 0) {
10883       if (NumZero == 0)
10884         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10885 
10886       if (EltVT == MVT::i32 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
10887           EltVT == MVT::f64 || (EltVT == MVT::i64 && Subtarget.is64Bit()) ||
10888           (EltVT == MVT::i16 && Subtarget.hasFP16())) {
10889         assert((VT.is128BitVector() || VT.is256BitVector() ||
10890                 VT.is512BitVector()) &&
10891                "Expected an SSE value type!");
10892         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10893         // Turn it into a MOVL (i.e. movsh, movss, movsd, movw or movd) to a
10894         // zero vector.
10895         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
10896       }
10897 
10898       // We can't directly insert an i8 or i16 into a vector, so zero extend
10899       // it to i32 first.
10900       if (EltVT == MVT::i16 || EltVT == MVT::i8) {
10901         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
10902         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
10903         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
10904         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
10905         return DAG.getBitcast(VT, Item);
10906       }
10907     }
10908 
10909     // Is it a vector logical left shift?
10910     if (NumElems == 2 && Idx == 1 &&
10911         X86::isZeroNode(Op.getOperand(0)) &&
10912         !X86::isZeroNode(Op.getOperand(1))) {
10913       unsigned NumBits = VT.getSizeInBits();
10914       return getVShift(true, VT,
10915                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10916                                    VT, Op.getOperand(1)),
10917                        NumBits/2, DAG, *this, dl);
10918     }
10919 
10920     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
10921       return SDValue();
10922 
10923     // Otherwise, if this is a vector with i32 or f32 elements, and the element
10924     // is a non-constant being inserted into an element other than the low one,
10925     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
10926     // movd/movss) to move this into the low element, then shuffle it into
10927     // place.
10928     if (EVTBits == 32) {
10929       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10930       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
10931     }
10932   }
10933 
10934   // Splat is obviously ok. Let legalizer expand it to a shuffle.
10935   if (Values.size() == 1) {
10936     if (EVTBits == 32) {
10937       // Instead of a shuffle like this:
10938       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
10939       // Check if it's possible to issue this instead.
10940       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
10941       unsigned Idx = NonZeroMask.countTrailingZeros();
10942       SDValue Item = Op.getOperand(Idx);
10943       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
10944         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
10945     }
10946     return SDValue();
10947   }
10948 
10949   // A vector full of immediates; various special cases are already
10950   // handled, so this is best done with a single constant-pool load.
10951   if (IsAllConstants)
10952     return SDValue();
10953 
10954   if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
10955       return V;
10956 
10957   // See if we can use a vector load to get all of the elements.
10958   {
10959     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
10960     if (SDValue LD =
10961             EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
10962       return LD;
10963   }
10964 
10965   // If this is a splat of pairs of 32-bit elements, we can use a narrower
10966   // build_vector and broadcast it.
10967   // TODO: We could probably generalize this more.
10968   if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
10969     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
10970                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
10971     auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
10972       // Make sure all the even/odd operands match.
10973       for (unsigned i = 2; i != NumElems; ++i)
10974         if (Ops[i % 2] != Op.getOperand(i))
10975           return false;
10976       return true;
10977     };
10978     if (CanSplat(Op, NumElems, Ops)) {
10979       MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
10980       MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
10981       // Create a new build vector and cast to v2i64/v2f64.
10982       SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
10983                                      DAG.getBuildVector(NarrowVT, dl, Ops));
10984       // Broadcast from v2i64/v2f64 and cast to final VT.
10985       MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
10986       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
10987                                             NewBV));
10988     }
10989   }
10990 
10991   // For AVX-length vectors, build the individual 128-bit pieces and use
10992   // shuffles to put them in place.
10993   if (VT.getSizeInBits() > 128) {
10994     MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
10995 
10996     // Build both the lower and upper subvector.
10997     SDValue Lower =
10998         DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
10999     SDValue Upper = DAG.getBuildVector(
11000         HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
11001 
11002     // Recreate the wider vector with the lower and upper part.
11003     return concatSubVectors(Lower, Upper, DAG, dl);
11004   }
11005 
11006   // Let legalizer expand 2-wide build_vectors.
11007   if (EVTBits == 64) {
11008     if (NumNonZero == 1) {
11009       // One half is zero or undef.
11010       unsigned Idx = NonZeroMask.countTrailingZeros();
11011       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
11012                                Op.getOperand(Idx));
11013       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
11014     }
11015     return SDValue();
11016   }
11017 
11018   // If element VT is < 32 bits, convert it to inserts into a zero vector.
11019   if (EVTBits == 8 && NumElems == 16)
11020     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeroMask, NumNonZero, NumZero,
11021                                           DAG, Subtarget))
11022       return V;
11023 
11024   if (EltVT == MVT::i16 && NumElems == 8)
11025     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeroMask, NumNonZero, NumZero,
11026                                           DAG, Subtarget))
11027       return V;
11028 
11029   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
11030   if (EVTBits == 32 && NumElems == 4)
11031     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
11032       return V;
11033 
11034   // If element VT is == 32 bits, turn it into a number of shuffles.
11035   if (NumElems == 4 && NumZero > 0) {
11036     SmallVector<SDValue, 8> Ops(NumElems);
11037     for (unsigned i = 0; i < 4; ++i) {
11038       bool isZero = !NonZeroMask[i];
11039       if (isZero)
11040         Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
11041       else
11042         Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
11043     }
11044 
11045     for (unsigned i = 0; i < 2; ++i) {
11046       switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
11047         default: llvm_unreachable("Unexpected NonZero count");
11048         case 0:
11049           Ops[i] = Ops[i*2];  // Must be a zero vector.
11050           break;
11051         case 1:
11052           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
11053           break;
11054         case 2:
11055           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
11056           break;
11057         case 3:
11058           Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
11059           break;
11060       }
11061     }
11062 
11063     bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
11064     bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
11065     int MaskVec[] = {
11066       Reverse1 ? 1 : 0,
11067       Reverse1 ? 0 : 1,
11068       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
11069       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
11070     };
11071     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
11072   }
11073 
11074   assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
11075 
11076   // Check for a build vector from mostly shuffle plus few inserting.
11077   if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
11078     return Sh;
11079 
11080   // For SSE 4.1, use insertps to put the high elements into the low element.
11081   if (Subtarget.hasSSE41() && EltVT != MVT::f16) {
11082     SDValue Result;
11083     if (!Op.getOperand(0).isUndef())
11084       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
11085     else
11086       Result = DAG.getUNDEF(VT);
11087 
11088     for (unsigned i = 1; i < NumElems; ++i) {
11089       if (Op.getOperand(i).isUndef()) continue;
11090       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
11091                            Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
11092     }
11093     return Result;
11094   }
11095 
11096   // Otherwise, expand into a number of unpckl*, start by extending each of
11097   // our (non-undef) elements to the full vector width with the element in the
11098   // bottom slot of the vector (which generates no code for SSE).
11099   SmallVector<SDValue, 8> Ops(NumElems);
11100   for (unsigned i = 0; i < NumElems; ++i) {
11101     if (!Op.getOperand(i).isUndef())
11102       Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
11103     else
11104       Ops[i] = DAG.getUNDEF(VT);
11105   }
11106 
11107   // Next, we iteratively mix elements, e.g. for v4f32:
11108   //   Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
11109   //         : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
11110   //   Step 2: unpcklpd X, Y ==>    <3, 2, 1, 0>
11111   for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
11112     // Generate scaled UNPCKL shuffle mask.
11113     SmallVector<int, 16> Mask;
11114     for(unsigned i = 0; i != Scale; ++i)
11115       Mask.push_back(i);
11116     for (unsigned i = 0; i != Scale; ++i)
11117       Mask.push_back(NumElems+i);
11118     Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
11119 
11120     for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
11121       Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
11122   }
11123   return Ops[0];
11124 }
11125 
11126 // 256-bit AVX can use the vinsertf128 instruction
11127 // to create 256-bit vectors from two other 128-bit ones.
11128 // TODO: Detect subvector broadcast here instead of DAG combine?
11129 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
11130                                       const X86Subtarget &Subtarget) {
11131   SDLoc dl(Op);
11132   MVT ResVT = Op.getSimpleValueType();
11133 
11134   assert((ResVT.is256BitVector() ||
11135           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
11136 
11137   unsigned NumOperands = Op.getNumOperands();
11138   unsigned NumZero = 0;
11139   unsigned NumNonZero = 0;
11140   unsigned NonZeros = 0;
11141   for (unsigned i = 0; i != NumOperands; ++i) {
11142     SDValue SubVec = Op.getOperand(i);
11143     if (SubVec.isUndef())
11144       continue;
11145     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
11146       ++NumZero;
11147     else {
11148       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
11149       NonZeros |= 1 << i;
11150       ++NumNonZero;
11151     }
11152   }
11153 
11154   // If we have more than 2 non-zeros, build each half separately.
11155   if (NumNonZero > 2) {
11156     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
11157     ArrayRef<SDUse> Ops = Op->ops();
11158     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11159                              Ops.slice(0, NumOperands/2));
11160     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11161                              Ops.slice(NumOperands/2));
11162     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
11163   }
11164 
11165   // Otherwise, build it up through insert_subvectors.
11166   SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
11167                         : DAG.getUNDEF(ResVT);
11168 
11169   MVT SubVT = Op.getOperand(0).getSimpleValueType();
11170   unsigned NumSubElems = SubVT.getVectorNumElements();
11171   for (unsigned i = 0; i != NumOperands; ++i) {
11172     if ((NonZeros & (1 << i)) == 0)
11173       continue;
11174 
11175     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
11176                       Op.getOperand(i),
11177                       DAG.getIntPtrConstant(i * NumSubElems, dl));
11178   }
11179 
11180   return Vec;
11181 }
11182 
11183 // Returns true if the given node is a type promotion (by concatenating i1
11184 // zeros) of the result of a node that already zeros all upper bits of
11185 // k-register.
11186 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
11187 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
11188                                        const X86Subtarget &Subtarget,
11189                                        SelectionDAG & DAG) {
11190   SDLoc dl(Op);
11191   MVT ResVT = Op.getSimpleValueType();
11192   unsigned NumOperands = Op.getNumOperands();
11193 
11194   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
11195          "Unexpected number of operands in CONCAT_VECTORS");
11196 
11197   uint64_t Zeros = 0;
11198   uint64_t NonZeros = 0;
11199   for (unsigned i = 0; i != NumOperands; ++i) {
11200     SDValue SubVec = Op.getOperand(i);
11201     if (SubVec.isUndef())
11202       continue;
11203     assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
11204     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
11205       Zeros |= (uint64_t)1 << i;
11206     else
11207       NonZeros |= (uint64_t)1 << i;
11208   }
11209 
11210   unsigned NumElems = ResVT.getVectorNumElements();
11211 
11212   // If we are inserting non-zero vector and there are zeros in LSBs and undef
11213   // in the MSBs we need to emit a KSHIFTL. The generic lowering to
11214   // insert_subvector will give us two kshifts.
11215   if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
11216       Log2_64(NonZeros) != NumOperands - 1) {
11217     MVT ShiftVT = ResVT;
11218     if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
11219       ShiftVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
11220     unsigned Idx = Log2_64(NonZeros);
11221     SDValue SubVec = Op.getOperand(Idx);
11222     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
11223     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ShiftVT,
11224                          DAG.getUNDEF(ShiftVT), SubVec,
11225                          DAG.getIntPtrConstant(0, dl));
11226     Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, SubVec,
11227                      DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
11228     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
11229                        DAG.getIntPtrConstant(0, dl));
11230   }
11231 
11232   // If there are zero or one non-zeros we can handle this very simply.
11233   if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
11234     SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
11235     if (!NonZeros)
11236       return Vec;
11237     unsigned Idx = Log2_64(NonZeros);
11238     SDValue SubVec = Op.getOperand(Idx);
11239     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
11240     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
11241                        DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
11242   }
11243 
11244   if (NumOperands > 2) {
11245     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
11246     ArrayRef<SDUse> Ops = Op->ops();
11247     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11248                              Ops.slice(0, NumOperands/2));
11249     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
11250                              Ops.slice(NumOperands/2));
11251     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
11252   }
11253 
11254   assert(countPopulation(NonZeros) == 2 && "Simple cases not handled?");
11255 
11256   if (ResVT.getVectorNumElements() >= 16)
11257     return Op; // The operation is legal with KUNPCK
11258 
11259   SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
11260                             DAG.getUNDEF(ResVT), Op.getOperand(0),
11261                             DAG.getIntPtrConstant(0, dl));
11262   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
11263                      DAG.getIntPtrConstant(NumElems/2, dl));
11264 }
11265 
11266 static SDValue LowerCONCAT_VECTORS(SDValue Op,
11267                                    const X86Subtarget &Subtarget,
11268                                    SelectionDAG &DAG) {
11269   MVT VT = Op.getSimpleValueType();
11270   if (VT.getVectorElementType() == MVT::i1)
11271     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
11272 
11273   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
11274          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
11275           Op.getNumOperands() == 4)));
11276 
11277   // AVX can use the vinsertf128 instruction to create 256-bit vectors
11278   // from two other 128-bit ones.
11279 
11280   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
11281   return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
11282 }
11283 
11284 //===----------------------------------------------------------------------===//
11285 // Vector shuffle lowering
11286 //
11287 // This is an experimental code path for lowering vector shuffles on x86. It is
11288 // designed to handle arbitrary vector shuffles and blends, gracefully
11289 // degrading performance as necessary. It works hard to recognize idiomatic
11290 // shuffles and lower them to optimal instruction patterns without leaving
11291 // a framework that allows reasonably efficient handling of all vector shuffle
11292 // patterns.
11293 //===----------------------------------------------------------------------===//
11294 
11295 /// Tiny helper function to identify a no-op mask.
11296 ///
11297 /// This is a somewhat boring predicate function. It checks whether the mask
11298 /// array input, which is assumed to be a single-input shuffle mask of the kind
11299 /// used by the X86 shuffle instructions (not a fully general
11300 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
11301 /// in-place shuffle are 'no-op's.
11302 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
11303   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11304     assert(Mask[i] >= -1 && "Out of bound mask element!");
11305     if (Mask[i] >= 0 && Mask[i] != i)
11306       return false;
11307   }
11308   return true;
11309 }
11310 
11311 /// Test whether there are elements crossing LaneSizeInBits lanes in this
11312 /// shuffle mask.
11313 ///
11314 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
11315 /// and we routinely test for these.
11316 static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
11317                                       unsigned ScalarSizeInBits,
11318                                       ArrayRef<int> Mask) {
11319   assert(LaneSizeInBits && ScalarSizeInBits &&
11320          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
11321          "Illegal shuffle lane size");
11322   int LaneSize = LaneSizeInBits / ScalarSizeInBits;
11323   int Size = Mask.size();
11324   for (int i = 0; i < Size; ++i)
11325     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
11326       return true;
11327   return false;
11328 }
11329 
11330 /// Test whether there are elements crossing 128-bit lanes in this
11331 /// shuffle mask.
11332 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
11333   return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
11334 }
11335 
11336 /// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
11337 /// from multiple lanes - this is different to isLaneCrossingShuffleMask to
11338 /// better support 'repeated mask + lane permute' style shuffles.
11339 static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
11340                                    unsigned ScalarSizeInBits,
11341                                    ArrayRef<int> Mask) {
11342   assert(LaneSizeInBits && ScalarSizeInBits &&
11343          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
11344          "Illegal shuffle lane size");
11345   int NumElts = Mask.size();
11346   int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
11347   int NumLanes = NumElts / NumEltsPerLane;
11348   if (NumLanes > 1) {
11349     for (int i = 0; i != NumLanes; ++i) {
11350       int SrcLane = -1;
11351       for (int j = 0; j != NumEltsPerLane; ++j) {
11352         int M = Mask[(i * NumEltsPerLane) + j];
11353         if (M < 0)
11354           continue;
11355         int Lane = (M % NumElts) / NumEltsPerLane;
11356         if (SrcLane >= 0 && SrcLane != Lane)
11357           return true;
11358         SrcLane = Lane;
11359       }
11360     }
11361   }
11362   return false;
11363 }
11364 
11365 /// Test whether a shuffle mask is equivalent within each sub-lane.
11366 ///
11367 /// This checks a shuffle mask to see if it is performing the same
11368 /// lane-relative shuffle in each sub-lane. This trivially implies
11369 /// that it is also not lane-crossing. It may however involve a blend from the
11370 /// same lane of a second vector.
11371 ///
11372 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
11373 /// non-trivial to compute in the face of undef lanes. The representation is
11374 /// suitable for use with existing 128-bit shuffles as entries from the second
11375 /// vector have been remapped to [LaneSize, 2*LaneSize).
11376 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
11377                                   ArrayRef<int> Mask,
11378                                   SmallVectorImpl<int> &RepeatedMask) {
11379   auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
11380   RepeatedMask.assign(LaneSize, -1);
11381   int Size = Mask.size();
11382   for (int i = 0; i < Size; ++i) {
11383     assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
11384     if (Mask[i] < 0)
11385       continue;
11386     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
11387       // This entry crosses lanes, so there is no way to model this shuffle.
11388       return false;
11389 
11390     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
11391     // Adjust second vector indices to start at LaneSize instead of Size.
11392     int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
11393                                 : Mask[i] % LaneSize + LaneSize;
11394     if (RepeatedMask[i % LaneSize] < 0)
11395       // This is the first non-undef entry in this slot of a 128-bit lane.
11396       RepeatedMask[i % LaneSize] = LocalM;
11397     else if (RepeatedMask[i % LaneSize] != LocalM)
11398       // Found a mismatch with the repeated mask.
11399       return false;
11400   }
11401   return true;
11402 }
11403 
11404 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
11405 static bool
11406 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
11407                                 SmallVectorImpl<int> &RepeatedMask) {
11408   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
11409 }
11410 
11411 static bool
11412 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
11413   SmallVector<int, 32> RepeatedMask;
11414   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
11415 }
11416 
11417 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
11418 static bool
11419 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
11420                                 SmallVectorImpl<int> &RepeatedMask) {
11421   return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
11422 }
11423 
11424 /// Test whether a target shuffle mask is equivalent within each sub-lane.
11425 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
11426 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
11427                                         unsigned EltSizeInBits,
11428                                         ArrayRef<int> Mask,
11429                                         SmallVectorImpl<int> &RepeatedMask) {
11430   int LaneSize = LaneSizeInBits / EltSizeInBits;
11431   RepeatedMask.assign(LaneSize, SM_SentinelUndef);
11432   int Size = Mask.size();
11433   for (int i = 0; i < Size; ++i) {
11434     assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
11435     if (Mask[i] == SM_SentinelUndef)
11436       continue;
11437     if (Mask[i] == SM_SentinelZero) {
11438       if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
11439         return false;
11440       RepeatedMask[i % LaneSize] = SM_SentinelZero;
11441       continue;
11442     }
11443     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
11444       // This entry crosses lanes, so there is no way to model this shuffle.
11445       return false;
11446 
11447     // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
11448     // later vector indices to start at multiples of LaneSize instead of Size.
11449     int LaneM = Mask[i] / Size;
11450     int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
11451     if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
11452       // This is the first non-undef entry in this slot of a 128-bit lane.
11453       RepeatedMask[i % LaneSize] = LocalM;
11454     else if (RepeatedMask[i % LaneSize] != LocalM)
11455       // Found a mismatch with the repeated mask.
11456       return false;
11457   }
11458   return true;
11459 }
11460 
11461 /// Test whether a target shuffle mask is equivalent within each sub-lane.
11462 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
11463 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
11464                                         ArrayRef<int> Mask,
11465                                         SmallVectorImpl<int> &RepeatedMask) {
11466   return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
11467                                      Mask, RepeatedMask);
11468 }
11469 
11470 /// Checks whether the vector elements referenced by two shuffle masks are
11471 /// equivalent.
11472 static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
11473                                 int Idx, int ExpectedIdx) {
11474   assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
11475          ExpectedIdx < MaskSize && "Out of range element index");
11476   if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
11477     return false;
11478 
11479   switch (Op.getOpcode()) {
11480   case ISD::BUILD_VECTOR:
11481     // If the values are build vectors, we can look through them to find
11482     // equivalent inputs that make the shuffles equivalent.
11483     // TODO: Handle MaskSize != Op.getNumOperands()?
11484     if (MaskSize == (int)Op.getNumOperands() &&
11485         MaskSize == (int)ExpectedOp.getNumOperands())
11486       return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
11487     break;
11488   case X86ISD::VBROADCAST:
11489   case X86ISD::VBROADCAST_LOAD:
11490     // TODO: Handle MaskSize != Op.getValueType().getVectorNumElements()?
11491     return (Op == ExpectedOp &&
11492             (int)Op.getValueType().getVectorNumElements() == MaskSize);
11493   case X86ISD::HADD:
11494   case X86ISD::HSUB:
11495   case X86ISD::FHADD:
11496   case X86ISD::FHSUB:
11497   case X86ISD::PACKSS:
11498   case X86ISD::PACKUS:
11499     // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
11500     // TODO: Handle MaskSize != NumElts?
11501     // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
11502     if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
11503       MVT VT = Op.getSimpleValueType();
11504       int NumElts = VT.getVectorNumElements();
11505       if (MaskSize == NumElts) {
11506         int NumLanes = VT.getSizeInBits() / 128;
11507         int NumEltsPerLane = NumElts / NumLanes;
11508         int NumHalfEltsPerLane = NumEltsPerLane / 2;
11509         bool SameLane =
11510             (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
11511         bool SameElt =
11512             (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
11513         return SameLane && SameElt;
11514       }
11515     }
11516     break;
11517   }
11518 
11519   return false;
11520 }
11521 
11522 /// Checks whether a shuffle mask is equivalent to an explicit list of
11523 /// arguments.
11524 ///
11525 /// This is a fast way to test a shuffle mask against a fixed pattern:
11526 ///
11527 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
11528 ///
11529 /// It returns true if the mask is exactly as wide as the argument list, and
11530 /// each element of the mask is either -1 (signifying undef) or the value given
11531 /// in the argument.
11532 static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
11533                                 SDValue V1 = SDValue(),
11534                                 SDValue V2 = SDValue()) {
11535   int Size = Mask.size();
11536   if (Size != (int)ExpectedMask.size())
11537     return false;
11538 
11539   for (int i = 0; i < Size; ++i) {
11540     assert(Mask[i] >= -1 && "Out of bound mask element!");
11541     int MaskIdx = Mask[i];
11542     int ExpectedIdx = ExpectedMask[i];
11543     if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
11544       SDValue MaskV = MaskIdx < Size ? V1 : V2;
11545       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11546       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
11547       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11548       if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
11549         return false;
11550     }
11551   }
11552   return true;
11553 }
11554 
11555 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
11556 ///
11557 /// The masks must be exactly the same width.
11558 ///
11559 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
11560 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
11561 ///
11562 /// SM_SentinelZero is accepted as a valid negative index but must match in
11563 /// both.
11564 static bool isTargetShuffleEquivalent(MVT VT, ArrayRef<int> Mask,
11565                                       ArrayRef<int> ExpectedMask,
11566                                       SDValue V1 = SDValue(),
11567                                       SDValue V2 = SDValue()) {
11568   int Size = Mask.size();
11569   if (Size != (int)ExpectedMask.size())
11570     return false;
11571   assert(isUndefOrZeroOrInRange(ExpectedMask, 0, 2 * Size) &&
11572          "Illegal target shuffle mask");
11573 
11574   // Check for out-of-range target shuffle mask indices.
11575   if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
11576     return false;
11577 
11578   // Don't use V1/V2 if they're not the same size as the shuffle mask type.
11579   if (V1 && V1.getValueSizeInBits() != VT.getSizeInBits())
11580     V1 = SDValue();
11581   if (V2 && V2.getValueSizeInBits() != VT.getSizeInBits())
11582     V2 = SDValue();
11583 
11584   for (int i = 0; i < Size; ++i) {
11585     int MaskIdx = Mask[i];
11586     int ExpectedIdx = ExpectedMask[i];
11587     if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
11588       continue;
11589     if (0 <= MaskIdx && 0 <= ExpectedIdx) {
11590       SDValue MaskV = MaskIdx < Size ? V1 : V2;
11591       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11592       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
11593       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11594       if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
11595         continue;
11596     }
11597     // TODO - handle SM_Sentinel equivalences.
11598     return false;
11599   }
11600   return true;
11601 }
11602 
11603 // Attempt to create a shuffle mask from a VSELECT condition mask.
11604 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
11605                                          SDValue Cond) {
11606   EVT CondVT = Cond.getValueType();
11607   unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
11608   unsigned NumElts = CondVT.getVectorNumElements();
11609 
11610   APInt UndefElts;
11611   SmallVector<APInt, 32> EltBits;
11612   if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
11613                                      true, false))
11614     return false;
11615 
11616   Mask.resize(NumElts, SM_SentinelUndef);
11617 
11618   for (int i = 0; i != (int)NumElts; ++i) {
11619     Mask[i] = i;
11620     // Arbitrarily choose from the 2nd operand if the select condition element
11621     // is undef.
11622     // TODO: Can we do better by matching patterns such as even/odd?
11623     if (UndefElts[i] || EltBits[i].isZero())
11624       Mask[i] += NumElts;
11625   }
11626 
11627   return true;
11628 }
11629 
11630 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
11631 // instructions.
11632 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT) {
11633   if (VT != MVT::v8i32 && VT != MVT::v8f32)
11634     return false;
11635 
11636   SmallVector<int, 8> Unpcklwd;
11637   createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
11638                           /* Unary = */ false);
11639   SmallVector<int, 8> Unpckhwd;
11640   createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
11641                           /* Unary = */ false);
11642   bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd) ||
11643                          isTargetShuffleEquivalent(VT, Mask, Unpckhwd));
11644   return IsUnpackwdMask;
11645 }
11646 
11647 static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask) {
11648   // Create 128-bit vector type based on mask size.
11649   MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
11650   MVT VT = MVT::getVectorVT(EltVT, Mask.size());
11651 
11652   // We can't assume a canonical shuffle mask, so try the commuted version too.
11653   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
11654   ShuffleVectorSDNode::commuteMask(CommutedMask);
11655 
11656   // Match any of unary/binary or low/high.
11657   for (unsigned i = 0; i != 4; ++i) {
11658     SmallVector<int, 16> UnpackMask;
11659     createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
11660     if (isTargetShuffleEquivalent(VT, Mask, UnpackMask) ||
11661         isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask))
11662       return true;
11663   }
11664   return false;
11665 }
11666 
11667 /// Return true if a shuffle mask chooses elements identically in its top and
11668 /// bottom halves. For example, any splat mask has the same top and bottom
11669 /// halves. If an element is undefined in only one half of the mask, the halves
11670 /// are not considered identical.
11671 static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
11672   assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
11673   unsigned HalfSize = Mask.size() / 2;
11674   for (unsigned i = 0; i != HalfSize; ++i) {
11675     if (Mask[i] != Mask[i + HalfSize])
11676       return false;
11677   }
11678   return true;
11679 }
11680 
11681 /// Get a 4-lane 8-bit shuffle immediate for a mask.
11682 ///
11683 /// This helper function produces an 8-bit shuffle immediate corresponding to
11684 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
11685 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
11686 /// example.
11687 ///
11688 /// NB: We rely heavily on "undef" masks preserving the input lane.
11689 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
11690   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
11691   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
11692   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
11693   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
11694   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
11695 
11696   // If the mask only uses one non-undef element, then fully 'splat' it to
11697   // improve later broadcast matching.
11698   int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
11699   assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
11700 
11701   int FirstElt = Mask[FirstIndex];
11702   if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
11703     return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
11704 
11705   unsigned Imm = 0;
11706   Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
11707   Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
11708   Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
11709   Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
11710   return Imm;
11711 }
11712 
11713 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
11714                                           SelectionDAG &DAG) {
11715   return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
11716 }
11717 
11718 // The Shuffle result is as follow:
11719 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
11720 // Each Zeroable's element correspond to a particular Mask's element.
11721 // As described in computeZeroableShuffleElements function.
11722 //
11723 // The function looks for a sub-mask that the nonzero elements are in
11724 // increasing order. If such sub-mask exist. The function returns true.
11725 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
11726                                      ArrayRef<int> Mask, const EVT &VectorType,
11727                                      bool &IsZeroSideLeft) {
11728   int NextElement = -1;
11729   // Check if the Mask's nonzero elements are in increasing order.
11730   for (int i = 0, e = Mask.size(); i < e; i++) {
11731     // Checks if the mask's zeros elements are built from only zeros.
11732     assert(Mask[i] >= -1 && "Out of bound mask element!");
11733     if (Mask[i] < 0)
11734       return false;
11735     if (Zeroable[i])
11736       continue;
11737     // Find the lowest non zero element
11738     if (NextElement < 0) {
11739       NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
11740       IsZeroSideLeft = NextElement != 0;
11741     }
11742     // Exit if the mask's non zero elements are not in increasing order.
11743     if (NextElement != Mask[i])
11744       return false;
11745     NextElement++;
11746   }
11747   return true;
11748 }
11749 
11750 /// Try to lower a shuffle with a single PSHUFB of V1 or V2.
11751 static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
11752                                       ArrayRef<int> Mask, SDValue V1,
11753                                       SDValue V2, const APInt &Zeroable,
11754                                       const X86Subtarget &Subtarget,
11755                                       SelectionDAG &DAG) {
11756   int Size = Mask.size();
11757   int LaneSize = 128 / VT.getScalarSizeInBits();
11758   const int NumBytes = VT.getSizeInBits() / 8;
11759   const int NumEltBytes = VT.getScalarSizeInBits() / 8;
11760 
11761   assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
11762          (Subtarget.hasAVX2() && VT.is256BitVector()) ||
11763          (Subtarget.hasBWI() && VT.is512BitVector()));
11764 
11765   SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
11766   // Sign bit set in i8 mask means zero element.
11767   SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
11768 
11769   SDValue V;
11770   for (int i = 0; i < NumBytes; ++i) {
11771     int M = Mask[i / NumEltBytes];
11772     if (M < 0) {
11773       PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
11774       continue;
11775     }
11776     if (Zeroable[i / NumEltBytes]) {
11777       PSHUFBMask[i] = ZeroMask;
11778       continue;
11779     }
11780 
11781     // We can only use a single input of V1 or V2.
11782     SDValue SrcV = (M >= Size ? V2 : V1);
11783     if (V && V != SrcV)
11784       return SDValue();
11785     V = SrcV;
11786     M %= Size;
11787 
11788     // PSHUFB can't cross lanes, ensure this doesn't happen.
11789     if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
11790       return SDValue();
11791 
11792     M = M % LaneSize;
11793     M = M * NumEltBytes + (i % NumEltBytes);
11794     PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
11795   }
11796   assert(V && "Failed to find a source input");
11797 
11798   MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
11799   return DAG.getBitcast(
11800       VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
11801                       DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
11802 }
11803 
11804 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
11805                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
11806                            const SDLoc &dl);
11807 
11808 // X86 has dedicated shuffle that can be lowered to VEXPAND
11809 static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
11810                                     const APInt &Zeroable,
11811                                     ArrayRef<int> Mask, SDValue &V1,
11812                                     SDValue &V2, SelectionDAG &DAG,
11813                                     const X86Subtarget &Subtarget) {
11814   bool IsLeftZeroSide = true;
11815   if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
11816                                 IsLeftZeroSide))
11817     return SDValue();
11818   unsigned VEXPANDMask = (~Zeroable).getZExtValue();
11819   MVT IntegerType =
11820       MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
11821   SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
11822   unsigned NumElts = VT.getVectorNumElements();
11823   assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
11824          "Unexpected number of vector elements");
11825   SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
11826                               Subtarget, DAG, DL);
11827   SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
11828   SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
11829   return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
11830 }
11831 
11832 static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
11833                                   unsigned &UnpackOpcode, bool IsUnary,
11834                                   ArrayRef<int> TargetMask, const SDLoc &DL,
11835                                   SelectionDAG &DAG,
11836                                   const X86Subtarget &Subtarget) {
11837   int NumElts = VT.getVectorNumElements();
11838 
11839   bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
11840   for (int i = 0; i != NumElts; i += 2) {
11841     int M1 = TargetMask[i + 0];
11842     int M2 = TargetMask[i + 1];
11843     Undef1 &= (SM_SentinelUndef == M1);
11844     Undef2 &= (SM_SentinelUndef == M2);
11845     Zero1 &= isUndefOrZero(M1);
11846     Zero2 &= isUndefOrZero(M2);
11847   }
11848   assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
11849          "Zeroable shuffle detected");
11850 
11851   // Attempt to match the target mask against the unpack lo/hi mask patterns.
11852   SmallVector<int, 64> Unpckl, Unpckh;
11853   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
11854   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, V1,
11855                                 (IsUnary ? V1 : V2))) {
11856     UnpackOpcode = X86ISD::UNPCKL;
11857     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
11858     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
11859     return true;
11860   }
11861 
11862   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
11863   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, V1,
11864                                 (IsUnary ? V1 : V2))) {
11865     UnpackOpcode = X86ISD::UNPCKH;
11866     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
11867     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
11868     return true;
11869   }
11870 
11871   // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
11872   if (IsUnary && (Zero1 || Zero2)) {
11873     // Don't bother if we can blend instead.
11874     if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
11875         isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
11876       return false;
11877 
11878     bool MatchLo = true, MatchHi = true;
11879     for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
11880       int M = TargetMask[i];
11881 
11882       // Ignore if the input is known to be zero or the index is undef.
11883       if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
11884           (M == SM_SentinelUndef))
11885         continue;
11886 
11887       MatchLo &= (M == Unpckl[i]);
11888       MatchHi &= (M == Unpckh[i]);
11889     }
11890 
11891     if (MatchLo || MatchHi) {
11892       UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11893       V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
11894       V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
11895       return true;
11896     }
11897   }
11898 
11899   // If a binary shuffle, commute and try again.
11900   if (!IsUnary) {
11901     ShuffleVectorSDNode::commuteMask(Unpckl);
11902     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl)) {
11903       UnpackOpcode = X86ISD::UNPCKL;
11904       std::swap(V1, V2);
11905       return true;
11906     }
11907 
11908     ShuffleVectorSDNode::commuteMask(Unpckh);
11909     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh)) {
11910       UnpackOpcode = X86ISD::UNPCKH;
11911       std::swap(V1, V2);
11912       return true;
11913     }
11914   }
11915 
11916   return false;
11917 }
11918 
11919 // X86 has dedicated unpack instructions that can handle specific blend
11920 // operations: UNPCKH and UNPCKL.
11921 static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
11922                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
11923                                      SelectionDAG &DAG) {
11924   SmallVector<int, 8> Unpckl;
11925   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
11926   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11927     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
11928 
11929   SmallVector<int, 8> Unpckh;
11930   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
11931   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11932     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
11933 
11934   // Commute and try again.
11935   ShuffleVectorSDNode::commuteMask(Unpckl);
11936   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11937     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
11938 
11939   ShuffleVectorSDNode::commuteMask(Unpckh);
11940   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11941     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
11942 
11943   return SDValue();
11944 }
11945 
11946 /// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
11947 /// followed by unpack 256-bit.
11948 static SDValue lowerShuffleWithUNPCK256(const SDLoc &DL, MVT VT,
11949                                         ArrayRef<int> Mask, SDValue V1,
11950                                         SDValue V2, SelectionDAG &DAG) {
11951   SmallVector<int, 32> Unpckl, Unpckh;
11952   createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
11953   createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
11954 
11955   unsigned UnpackOpcode;
11956   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11957     UnpackOpcode = X86ISD::UNPCKL;
11958   else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11959     UnpackOpcode = X86ISD::UNPCKH;
11960   else
11961     return SDValue();
11962 
11963   // This is a "natural" unpack operation (rather than the 128-bit sectored
11964   // operation implemented by AVX). We need to rearrange 64-bit chunks of the
11965   // input in order to use the x86 instruction.
11966   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
11967                             DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
11968   V1 = DAG.getBitcast(VT, V1);
11969   return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
11970 }
11971 
11972 // Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
11973 // source into the lower elements and zeroing the upper elements.
11974 static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
11975                                  ArrayRef<int> Mask, const APInt &Zeroable,
11976                                  const X86Subtarget &Subtarget) {
11977   if (!VT.is512BitVector() && !Subtarget.hasVLX())
11978     return false;
11979 
11980   unsigned NumElts = Mask.size();
11981   unsigned EltSizeInBits = VT.getScalarSizeInBits();
11982   unsigned MaxScale = 64 / EltSizeInBits;
11983 
11984   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11985     unsigned SrcEltBits = EltSizeInBits * Scale;
11986     if (SrcEltBits < 32 && !Subtarget.hasBWI())
11987       continue;
11988     unsigned NumSrcElts = NumElts / Scale;
11989     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
11990       continue;
11991     unsigned UpperElts = NumElts - NumSrcElts;
11992     if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
11993       continue;
11994     SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
11995     SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
11996     DstVT = MVT::getIntegerVT(EltSizeInBits);
11997     if ((NumSrcElts * EltSizeInBits) >= 128) {
11998       // ISD::TRUNCATE
11999       DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
12000     } else {
12001       // X86ISD::VTRUNC
12002       DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
12003     }
12004     return true;
12005   }
12006 
12007   return false;
12008 }
12009 
12010 // Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
12011 // element padding to the final DstVT.
12012 static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
12013                                   const X86Subtarget &Subtarget,
12014                                   SelectionDAG &DAG, bool ZeroUppers) {
12015   MVT SrcVT = Src.getSimpleValueType();
12016   MVT DstSVT = DstVT.getScalarType();
12017   unsigned NumDstElts = DstVT.getVectorNumElements();
12018   unsigned NumSrcElts = SrcVT.getVectorNumElements();
12019   unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
12020 
12021   if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
12022     return SDValue();
12023 
12024   // Perform a direct ISD::TRUNCATE if possible.
12025   if (NumSrcElts == NumDstElts)
12026     return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
12027 
12028   if (NumSrcElts > NumDstElts) {
12029     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
12030     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
12031     return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
12032   }
12033 
12034   if ((NumSrcElts * DstEltSizeInBits) >= 128) {
12035     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
12036     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
12037     return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
12038                           DstVT.getSizeInBits());
12039   }
12040 
12041   // Non-VLX targets must truncate from a 512-bit type, so we need to
12042   // widen, truncate and then possibly extract the original subvector.
12043   if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
12044     SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
12045     return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
12046   }
12047 
12048   // Fallback to a X86ISD::VTRUNC, padding if necessary.
12049   MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
12050   SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
12051   if (DstVT != TruncVT)
12052     Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
12053                            DstVT.getSizeInBits());
12054   return Trunc;
12055 }
12056 
12057 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
12058 //
12059 // An example is the following:
12060 //
12061 // t0: ch = EntryToken
12062 //           t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
12063 //         t25: v4i32 = truncate t2
12064 //       t41: v8i16 = bitcast t25
12065 //       t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
12066 //       Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
12067 //     t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
12068 //   t18: v2i64 = bitcast t51
12069 //
12070 // One can just use a single vpmovdw instruction, without avx512vl we need to
12071 // use the zmm variant and extract the lower subvector, padding with zeroes.
12072 // TODO: Merge with lowerShuffleAsVTRUNC.
12073 static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, MVT VT, SDValue V1,
12074                                      SDValue V2, ArrayRef<int> Mask,
12075                                      const APInt &Zeroable,
12076                                      const X86Subtarget &Subtarget,
12077                                      SelectionDAG &DAG) {
12078   assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
12079   if (!Subtarget.hasAVX512())
12080     return SDValue();
12081 
12082   unsigned NumElts = VT.getVectorNumElements();
12083   unsigned EltSizeInBits = VT.getScalarSizeInBits();
12084   unsigned MaxScale = 64 / EltSizeInBits;
12085   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
12086     unsigned NumSrcElts = NumElts / Scale;
12087     unsigned UpperElts = NumElts - NumSrcElts;
12088     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
12089         !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
12090       continue;
12091 
12092     SDValue Src = V1;
12093     if (!Src.hasOneUse())
12094       return SDValue();
12095 
12096     Src = peekThroughOneUseBitcasts(Src);
12097     if (Src.getOpcode() != ISD::TRUNCATE ||
12098         Src.getScalarValueSizeInBits() != (EltSizeInBits * Scale))
12099       return SDValue();
12100     Src = Src.getOperand(0);
12101 
12102     // VPMOVWB is only available with avx512bw.
12103     MVT SrcVT = Src.getSimpleValueType();
12104     if (SrcVT.getVectorElementType() == MVT::i16 && VT == MVT::v16i8 &&
12105         !Subtarget.hasBWI())
12106       return SDValue();
12107 
12108     bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
12109     return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
12110   }
12111 
12112   return SDValue();
12113 }
12114 
12115 // Attempt to match binary shuffle patterns as a truncate.
12116 static SDValue lowerShuffleAsVTRUNC(const SDLoc &DL, MVT VT, SDValue V1,
12117                                     SDValue V2, ArrayRef<int> Mask,
12118                                     const APInt &Zeroable,
12119                                     const X86Subtarget &Subtarget,
12120                                     SelectionDAG &DAG) {
12121   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12122          "Unexpected VTRUNC type");
12123   if (!Subtarget.hasAVX512())
12124     return SDValue();
12125 
12126   unsigned NumElts = VT.getVectorNumElements();
12127   unsigned EltSizeInBits = VT.getScalarSizeInBits();
12128   unsigned MaxScale = 64 / EltSizeInBits;
12129   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
12130     // TODO: Support non-BWI VPMOVWB truncations?
12131     unsigned SrcEltBits = EltSizeInBits * Scale;
12132     if (SrcEltBits < 32 && !Subtarget.hasBWI())
12133       continue;
12134 
12135     // Match shuffle <0,Scale,2*Scale,..,undef_or_zero,undef_or_zero,...>
12136     // Bail if the V2 elements are undef.
12137     unsigned NumHalfSrcElts = NumElts / Scale;
12138     unsigned NumSrcElts = 2 * NumHalfSrcElts;
12139     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
12140         isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
12141       continue;
12142 
12143     // The elements beyond the truncation must be undef/zero.
12144     unsigned UpperElts = NumElts - NumSrcElts;
12145     if (UpperElts > 0 &&
12146         !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
12147       continue;
12148     bool UndefUppers =
12149         UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
12150 
12151     // As we're using both sources then we need to concat them together
12152     // and truncate from the double-sized src.
12153     MVT ConcatVT = MVT::getVectorVT(VT.getScalarType(), NumElts * 2);
12154     SDValue Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
12155 
12156     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
12157     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
12158     Src = DAG.getBitcast(SrcVT, Src);
12159     return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
12160   }
12161 
12162   return SDValue();
12163 }
12164 
12165 /// Check whether a compaction lowering can be done by dropping even
12166 /// elements and compute how many times even elements must be dropped.
12167 ///
12168 /// This handles shuffles which take every Nth element where N is a power of
12169 /// two. Example shuffle masks:
12170 ///
12171 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
12172 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
12173 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
12174 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
12175 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
12176 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
12177 ///
12178 /// Any of these lanes can of course be undef.
12179 ///
12180 /// This routine only supports N <= 3.
12181 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
12182 /// for larger N.
12183 ///
12184 /// \returns N above, or the number of times even elements must be dropped if
12185 /// there is such a number. Otherwise returns zero.
12186 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask,
12187                                           bool IsSingleInput) {
12188   // The modulus for the shuffle vector entries is based on whether this is
12189   // a single input or not.
12190   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
12191   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
12192          "We should only be called with masks with a power-of-2 size!");
12193 
12194   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
12195 
12196   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
12197   // and 2^3 simultaneously. This is because we may have ambiguity with
12198   // partially undef inputs.
12199   bool ViableForN[3] = {true, true, true};
12200 
12201   for (int i = 0, e = Mask.size(); i < e; ++i) {
12202     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
12203     // want.
12204     if (Mask[i] < 0)
12205       continue;
12206 
12207     bool IsAnyViable = false;
12208     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
12209       if (ViableForN[j]) {
12210         uint64_t N = j + 1;
12211 
12212         // The shuffle mask must be equal to (i * 2^N) % M.
12213         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
12214           IsAnyViable = true;
12215         else
12216           ViableForN[j] = false;
12217       }
12218     // Early exit if we exhaust the possible powers of two.
12219     if (!IsAnyViable)
12220       break;
12221   }
12222 
12223   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
12224     if (ViableForN[j])
12225       return j + 1;
12226 
12227   // Return 0 as there is no viable power of two.
12228   return 0;
12229 }
12230 
12231 // X86 has dedicated pack instructions that can handle specific truncation
12232 // operations: PACKSS and PACKUS.
12233 // Checks for compaction shuffle masks if MaxStages > 1.
12234 // TODO: Add support for matching multiple PACKSS/PACKUS stages.
12235 static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
12236                                  unsigned &PackOpcode, ArrayRef<int> TargetMask,
12237                                  const SelectionDAG &DAG,
12238                                  const X86Subtarget &Subtarget,
12239                                  unsigned MaxStages = 1) {
12240   unsigned NumElts = VT.getVectorNumElements();
12241   unsigned BitSize = VT.getScalarSizeInBits();
12242   assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
12243          "Illegal maximum compaction");
12244 
12245   auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
12246     unsigned NumSrcBits = PackVT.getScalarSizeInBits();
12247     unsigned NumPackedBits = NumSrcBits - BitSize;
12248     N1 = peekThroughBitcasts(N1);
12249     N2 = peekThroughBitcasts(N2);
12250     unsigned NumBits1 = N1.getScalarValueSizeInBits();
12251     unsigned NumBits2 = N2.getScalarValueSizeInBits();
12252     bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
12253     bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
12254     if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
12255         (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
12256       return false;
12257     if (Subtarget.hasSSE41() || BitSize == 8) {
12258       APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
12259       if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
12260           (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
12261         V1 = N1;
12262         V2 = N2;
12263         SrcVT = PackVT;
12264         PackOpcode = X86ISD::PACKUS;
12265         return true;
12266       }
12267     }
12268     bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
12269     bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
12270     if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
12271          DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
12272         (N2.isUndef() || IsZero2 || IsAllOnes2 ||
12273          DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
12274       V1 = N1;
12275       V2 = N2;
12276       SrcVT = PackVT;
12277       PackOpcode = X86ISD::PACKSS;
12278       return true;
12279     }
12280     return false;
12281   };
12282 
12283   // Attempt to match against wider and wider compaction patterns.
12284   for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
12285     MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
12286     MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
12287 
12288     // Try binary shuffle.
12289     SmallVector<int, 32> BinaryMask;
12290     createPackShuffleMask(VT, BinaryMask, false, NumStages);
12291     if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, V1, V2))
12292       if (MatchPACK(V1, V2, PackVT))
12293         return true;
12294 
12295     // Try unary shuffle.
12296     SmallVector<int, 32> UnaryMask;
12297     createPackShuffleMask(VT, UnaryMask, true, NumStages);
12298     if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, V1))
12299       if (MatchPACK(V1, V1, PackVT))
12300         return true;
12301   }
12302 
12303   return false;
12304 }
12305 
12306 static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
12307                                     SDValue V1, SDValue V2, SelectionDAG &DAG,
12308                                     const X86Subtarget &Subtarget) {
12309   MVT PackVT;
12310   unsigned PackOpcode;
12311   unsigned SizeBits = VT.getSizeInBits();
12312   unsigned EltBits = VT.getScalarSizeInBits();
12313   unsigned MaxStages = Log2_32(64 / EltBits);
12314   if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
12315                             Subtarget, MaxStages))
12316     return SDValue();
12317 
12318   unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
12319   unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
12320 
12321   // Don't lower multi-stage packs on AVX512, truncation is better.
12322   if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
12323     return SDValue();
12324 
12325   // Pack to the largest type possible:
12326   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
12327   unsigned MaxPackBits = 16;
12328   if (CurrentEltBits > 16 &&
12329       (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
12330     MaxPackBits = 32;
12331 
12332   // Repeatedly pack down to the target size.
12333   SDValue Res;
12334   for (unsigned i = 0; i != NumStages; ++i) {
12335     unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
12336     unsigned NumSrcElts = SizeBits / SrcEltBits;
12337     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
12338     MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
12339     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
12340     MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
12341     Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
12342                       DAG.getBitcast(SrcVT, V2));
12343     V1 = V2 = Res;
12344     CurrentEltBits /= 2;
12345   }
12346   assert(Res && Res.getValueType() == VT &&
12347          "Failed to lower compaction shuffle");
12348   return Res;
12349 }
12350 
12351 /// Try to emit a bitmask instruction for a shuffle.
12352 ///
12353 /// This handles cases where we can model a blend exactly as a bitmask due to
12354 /// one of the inputs being zeroable.
12355 static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
12356                                      SDValue V2, ArrayRef<int> Mask,
12357                                      const APInt &Zeroable,
12358                                      const X86Subtarget &Subtarget,
12359                                      SelectionDAG &DAG) {
12360   MVT MaskVT = VT;
12361   MVT EltVT = VT.getVectorElementType();
12362   SDValue Zero, AllOnes;
12363   // Use f64 if i64 isn't legal.
12364   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
12365     EltVT = MVT::f64;
12366     MaskVT = MVT::getVectorVT(EltVT, Mask.size());
12367   }
12368 
12369   MVT LogicVT = VT;
12370   if (EltVT == MVT::f32 || EltVT == MVT::f64) {
12371     Zero = DAG.getConstantFP(0.0, DL, EltVT);
12372     APFloat AllOnesValue =
12373         APFloat::getAllOnesValue(SelectionDAG::EVTToAPFloatSemantics(EltVT));
12374     AllOnes = DAG.getConstantFP(AllOnesValue, DL, EltVT);
12375     LogicVT =
12376         MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
12377   } else {
12378     Zero = DAG.getConstant(0, DL, EltVT);
12379     AllOnes = DAG.getAllOnesConstant(DL, EltVT);
12380   }
12381 
12382   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
12383   SDValue V;
12384   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12385     if (Zeroable[i])
12386       continue;
12387     if (Mask[i] % Size != i)
12388       return SDValue(); // Not a blend.
12389     if (!V)
12390       V = Mask[i] < Size ? V1 : V2;
12391     else if (V != (Mask[i] < Size ? V1 : V2))
12392       return SDValue(); // Can only let one input through the mask.
12393 
12394     VMaskOps[i] = AllOnes;
12395   }
12396   if (!V)
12397     return SDValue(); // No non-zeroable elements!
12398 
12399   SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
12400   VMask = DAG.getBitcast(LogicVT, VMask);
12401   V = DAG.getBitcast(LogicVT, V);
12402   SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
12403   return DAG.getBitcast(VT, And);
12404 }
12405 
12406 /// Try to emit a blend instruction for a shuffle using bit math.
12407 ///
12408 /// This is used as a fallback approach when first class blend instructions are
12409 /// unavailable. Currently it is only suitable for integer vectors, but could
12410 /// be generalized for floating point vectors if desirable.
12411 static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
12412                                       SDValue V2, ArrayRef<int> Mask,
12413                                       SelectionDAG &DAG) {
12414   assert(VT.isInteger() && "Only supports integer vector types!");
12415   MVT EltVT = VT.getVectorElementType();
12416   SDValue Zero = DAG.getConstant(0, DL, EltVT);
12417   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
12418   SmallVector<SDValue, 16> MaskOps;
12419   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12420     if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
12421       return SDValue(); // Shuffled input!
12422     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
12423   }
12424 
12425   SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
12426   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
12427   V2 = DAG.getNode(X86ISD::ANDNP, DL, VT, V1Mask, V2);
12428   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
12429 }
12430 
12431 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
12432                                     SDValue PreservedSrc,
12433                                     const X86Subtarget &Subtarget,
12434                                     SelectionDAG &DAG);
12435 
12436 static bool matchShuffleAsBlend(SDValue V1, SDValue V2,
12437                                 MutableArrayRef<int> Mask,
12438                                 const APInt &Zeroable, bool &ForceV1Zero,
12439                                 bool &ForceV2Zero, uint64_t &BlendMask) {
12440   bool V1IsZeroOrUndef =
12441       V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
12442   bool V2IsZeroOrUndef =
12443       V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
12444 
12445   BlendMask = 0;
12446   ForceV1Zero = false, ForceV2Zero = false;
12447   assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
12448 
12449   // Attempt to generate the binary blend mask. If an input is zero then
12450   // we can use any lane.
12451   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12452     int M = Mask[i];
12453     if (M == SM_SentinelUndef)
12454       continue;
12455     if (M == i ||
12456         (0 <= M && M < Size && IsElementEquivalent(Size, V1, V1, M, i))) {
12457       Mask[i] = i;
12458       continue;
12459     }
12460     if (M == (i + Size) ||
12461         (Size <= M && IsElementEquivalent(Size, V2, V2, M - Size, i))) {
12462       BlendMask |= 1ull << i;
12463       Mask[i] = i + Size;
12464       continue;
12465     }
12466     if (Zeroable[i]) {
12467       if (V1IsZeroOrUndef) {
12468         ForceV1Zero = true;
12469         Mask[i] = i;
12470         continue;
12471       }
12472       if (V2IsZeroOrUndef) {
12473         ForceV2Zero = true;
12474         BlendMask |= 1ull << i;
12475         Mask[i] = i + Size;
12476         continue;
12477       }
12478     }
12479     return false;
12480   }
12481   return true;
12482 }
12483 
12484 static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
12485                                             int Scale) {
12486   uint64_t ScaledMask = 0;
12487   for (int i = 0; i != Size; ++i)
12488     if (BlendMask & (1ull << i))
12489       ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
12490   return ScaledMask;
12491 }
12492 
12493 /// Try to emit a blend instruction for a shuffle.
12494 ///
12495 /// This doesn't do any checks for the availability of instructions for blending
12496 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
12497 /// be matched in the backend with the type given. What it does check for is
12498 /// that the shuffle mask is a blend, or convertible into a blend with zero.
12499 static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
12500                                    SDValue V2, ArrayRef<int> Original,
12501                                    const APInt &Zeroable,
12502                                    const X86Subtarget &Subtarget,
12503                                    SelectionDAG &DAG) {
12504   uint64_t BlendMask = 0;
12505   bool ForceV1Zero = false, ForceV2Zero = false;
12506   SmallVector<int, 64> Mask(Original.begin(), Original.end());
12507   if (!matchShuffleAsBlend(V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
12508                            BlendMask))
12509     return SDValue();
12510 
12511   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
12512   if (ForceV1Zero)
12513     V1 = getZeroVector(VT, Subtarget, DAG, DL);
12514   if (ForceV2Zero)
12515     V2 = getZeroVector(VT, Subtarget, DAG, DL);
12516 
12517   switch (VT.SimpleTy) {
12518   case MVT::v4i64:
12519   case MVT::v8i32:
12520     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
12521     LLVM_FALLTHROUGH;
12522   case MVT::v4f64:
12523   case MVT::v8f32:
12524     assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
12525     LLVM_FALLTHROUGH;
12526   case MVT::v2f64:
12527   case MVT::v2i64:
12528   case MVT::v4f32:
12529   case MVT::v4i32:
12530   case MVT::v8i16:
12531     assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
12532     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
12533                        DAG.getTargetConstant(BlendMask, DL, MVT::i8));
12534   case MVT::v16i16: {
12535     assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
12536     SmallVector<int, 8> RepeatedMask;
12537     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
12538       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
12539       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
12540       BlendMask = 0;
12541       for (int i = 0; i < 8; ++i)
12542         if (RepeatedMask[i] >= 8)
12543           BlendMask |= 1ull << i;
12544       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12545                          DAG.getTargetConstant(BlendMask, DL, MVT::i8));
12546     }
12547     // Use PBLENDW for lower/upper lanes and then blend lanes.
12548     // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
12549     // merge to VSELECT where useful.
12550     uint64_t LoMask = BlendMask & 0xFF;
12551     uint64_t HiMask = (BlendMask >> 8) & 0xFF;
12552     if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
12553       SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12554                                DAG.getTargetConstant(LoMask, DL, MVT::i8));
12555       SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12556                                DAG.getTargetConstant(HiMask, DL, MVT::i8));
12557       return DAG.getVectorShuffle(
12558           MVT::v16i16, DL, Lo, Hi,
12559           {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
12560     }
12561     LLVM_FALLTHROUGH;
12562   }
12563   case MVT::v32i8:
12564     assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
12565     LLVM_FALLTHROUGH;
12566   case MVT::v16i8: {
12567     assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
12568 
12569     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
12570     if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
12571                                                Subtarget, DAG))
12572       return Masked;
12573 
12574     if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
12575       MVT IntegerType =
12576           MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
12577       SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
12578       return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
12579     }
12580 
12581     // If we have VPTERNLOG, we can use that as a bit blend.
12582     if (Subtarget.hasVLX())
12583       if (SDValue BitBlend =
12584               lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
12585         return BitBlend;
12586 
12587     // Scale the blend by the number of bytes per element.
12588     int Scale = VT.getScalarSizeInBits() / 8;
12589 
12590     // This form of blend is always done on bytes. Compute the byte vector
12591     // type.
12592     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12593 
12594     // x86 allows load folding with blendvb from the 2nd source operand. But
12595     // we are still using LLVM select here (see comment below), so that's V1.
12596     // If V2 can be load-folded and V1 cannot be load-folded, then commute to
12597     // allow that load-folding possibility.
12598     if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
12599       ShuffleVectorSDNode::commuteMask(Mask);
12600       std::swap(V1, V2);
12601     }
12602 
12603     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
12604     // mix of LLVM's code generator and the x86 backend. We tell the code
12605     // generator that boolean values in the elements of an x86 vector register
12606     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
12607     // mapping a select to operand #1, and 'false' mapping to operand #2. The
12608     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
12609     // of the element (the remaining are ignored) and 0 in that high bit would
12610     // mean operand #1 while 1 in the high bit would mean operand #2. So while
12611     // the LLVM model for boolean values in vector elements gets the relevant
12612     // bit set, it is set backwards and over constrained relative to x86's
12613     // actual model.
12614     SmallVector<SDValue, 32> VSELECTMask;
12615     for (int i = 0, Size = Mask.size(); i < Size; ++i)
12616       for (int j = 0; j < Scale; ++j)
12617         VSELECTMask.push_back(
12618             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
12619                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
12620                                           MVT::i8));
12621 
12622     V1 = DAG.getBitcast(BlendVT, V1);
12623     V2 = DAG.getBitcast(BlendVT, V2);
12624     return DAG.getBitcast(
12625         VT,
12626         DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
12627                       V1, V2));
12628   }
12629   case MVT::v16f32:
12630   case MVT::v8f64:
12631   case MVT::v8i64:
12632   case MVT::v16i32:
12633   case MVT::v32i16:
12634   case MVT::v64i8: {
12635     // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
12636     bool OptForSize = DAG.shouldOptForSize();
12637     if (!OptForSize) {
12638       if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
12639                                                  Subtarget, DAG))
12640         return Masked;
12641     }
12642 
12643     // Otherwise load an immediate into a GPR, cast to k-register, and use a
12644     // masked move.
12645     MVT IntegerType =
12646         MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
12647     SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
12648     return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
12649   }
12650   default:
12651     llvm_unreachable("Not a supported integer vector type!");
12652   }
12653 }
12654 
12655 /// Try to lower as a blend of elements from two inputs followed by
12656 /// a single-input permutation.
12657 ///
12658 /// This matches the pattern where we can blend elements from two inputs and
12659 /// then reduce the shuffle to a single-input permutation.
12660 static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
12661                                              SDValue V1, SDValue V2,
12662                                              ArrayRef<int> Mask,
12663                                              SelectionDAG &DAG,
12664                                              bool ImmBlends = false) {
12665   // We build up the blend mask while checking whether a blend is a viable way
12666   // to reduce the shuffle.
12667   SmallVector<int, 32> BlendMask(Mask.size(), -1);
12668   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
12669 
12670   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12671     if (Mask[i] < 0)
12672       continue;
12673 
12674     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
12675 
12676     if (BlendMask[Mask[i] % Size] < 0)
12677       BlendMask[Mask[i] % Size] = Mask[i];
12678     else if (BlendMask[Mask[i] % Size] != Mask[i])
12679       return SDValue(); // Can't blend in the needed input!
12680 
12681     PermuteMask[i] = Mask[i] % Size;
12682   }
12683 
12684   // If only immediate blends, then bail if the blend mask can't be widened to
12685   // i16.
12686   unsigned EltSize = VT.getScalarSizeInBits();
12687   if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
12688     return SDValue();
12689 
12690   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
12691   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
12692 }
12693 
12694 /// Try to lower as an unpack of elements from two inputs followed by
12695 /// a single-input permutation.
12696 ///
12697 /// This matches the pattern where we can unpack elements from two inputs and
12698 /// then reduce the shuffle to a single-input (wider) permutation.
12699 static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
12700                                              SDValue V1, SDValue V2,
12701                                              ArrayRef<int> Mask,
12702                                              SelectionDAG &DAG) {
12703   int NumElts = Mask.size();
12704   int NumLanes = VT.getSizeInBits() / 128;
12705   int NumLaneElts = NumElts / NumLanes;
12706   int NumHalfLaneElts = NumLaneElts / 2;
12707 
12708   bool MatchLo = true, MatchHi = true;
12709   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
12710 
12711   // Determine UNPCKL/UNPCKH type and operand order.
12712   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
12713     for (int Elt = 0; Elt != NumLaneElts; ++Elt) {
12714       int M = Mask[Lane + Elt];
12715       if (M < 0)
12716         continue;
12717 
12718       SDValue &Op = Ops[Elt & 1];
12719       if (M < NumElts && (Op.isUndef() || Op == V1))
12720         Op = V1;
12721       else if (NumElts <= M && (Op.isUndef() || Op == V2))
12722         Op = V2;
12723       else
12724         return SDValue();
12725 
12726       int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
12727       MatchLo &= isUndefOrInRange(M, Lo, Mid) ||
12728                  isUndefOrInRange(M, NumElts + Lo, NumElts + Mid);
12729       MatchHi &= isUndefOrInRange(M, Mid, Hi) ||
12730                  isUndefOrInRange(M, NumElts + Mid, NumElts + Hi);
12731       if (!MatchLo && !MatchHi)
12732         return SDValue();
12733     }
12734   }
12735   assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
12736 
12737   // Now check that each pair of elts come from the same unpack pair
12738   // and set the permute mask based on each pair.
12739   // TODO - Investigate cases where we permute individual elements.
12740   SmallVector<int, 32> PermuteMask(NumElts, -1);
12741   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
12742     for (int Elt = 0; Elt != NumLaneElts; Elt += 2) {
12743       int M0 = Mask[Lane + Elt + 0];
12744       int M1 = Mask[Lane + Elt + 1];
12745       if (0 <= M0 && 0 <= M1 &&
12746           (M0 % NumHalfLaneElts) != (M1 % NumHalfLaneElts))
12747         return SDValue();
12748       if (0 <= M0)
12749         PermuteMask[Lane + Elt + 0] = Lane + (2 * (M0 % NumHalfLaneElts));
12750       if (0 <= M1)
12751         PermuteMask[Lane + Elt + 1] = Lane + (2 * (M1 % NumHalfLaneElts)) + 1;
12752     }
12753   }
12754 
12755   unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
12756   SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
12757   return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
12758 }
12759 
12760 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
12761 /// permuting the elements of the result in place.
12762 static SDValue lowerShuffleAsByteRotateAndPermute(
12763     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12764     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12765   if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
12766       (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
12767       (VT.is512BitVector() && !Subtarget.hasBWI()))
12768     return SDValue();
12769 
12770   // We don't currently support lane crossing permutes.
12771   if (is128BitLaneCrossingShuffleMask(VT, Mask))
12772     return SDValue();
12773 
12774   int Scale = VT.getScalarSizeInBits() / 8;
12775   int NumLanes = VT.getSizeInBits() / 128;
12776   int NumElts = VT.getVectorNumElements();
12777   int NumEltsPerLane = NumElts / NumLanes;
12778 
12779   // Determine range of mask elts.
12780   bool Blend1 = true;
12781   bool Blend2 = true;
12782   std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
12783   std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
12784   for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
12785     for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
12786       int M = Mask[Lane + Elt];
12787       if (M < 0)
12788         continue;
12789       if (M < NumElts) {
12790         Blend1 &= (M == (Lane + Elt));
12791         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
12792         M = M % NumEltsPerLane;
12793         Range1.first = std::min(Range1.first, M);
12794         Range1.second = std::max(Range1.second, M);
12795       } else {
12796         M -= NumElts;
12797         Blend2 &= (M == (Lane + Elt));
12798         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
12799         M = M % NumEltsPerLane;
12800         Range2.first = std::min(Range2.first, M);
12801         Range2.second = std::max(Range2.second, M);
12802       }
12803     }
12804   }
12805 
12806   // Bail if we don't need both elements.
12807   // TODO - it might be worth doing this for unary shuffles if the permute
12808   // can be widened.
12809   if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
12810       !(0 <= Range2.first && Range2.second < NumEltsPerLane))
12811     return SDValue();
12812 
12813   if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
12814     return SDValue();
12815 
12816   // Rotate the 2 ops so we can access both ranges, then permute the result.
12817   auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
12818     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12819     SDValue Rotate = DAG.getBitcast(
12820         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
12821                         DAG.getBitcast(ByteVT, Lo),
12822                         DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
12823     SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
12824     for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
12825       for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
12826         int M = Mask[Lane + Elt];
12827         if (M < 0)
12828           continue;
12829         if (M < NumElts)
12830           PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
12831         else
12832           PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
12833       }
12834     }
12835     return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
12836   };
12837 
12838   // Check if the ranges are small enough to rotate from either direction.
12839   if (Range2.second < Range1.first)
12840     return RotateAndPermute(V1, V2, Range1.first, 0);
12841   if (Range1.second < Range2.first)
12842     return RotateAndPermute(V2, V1, Range2.first, NumElts);
12843   return SDValue();
12844 }
12845 
12846 static bool isBroadcastShuffleMask(ArrayRef<int> Mask) {
12847   return isUndefOrEqual(Mask, 0);
12848 }
12849 
12850 static bool isNoopOrBroadcastShuffleMask(ArrayRef<int> Mask) {
12851   return isNoopShuffleMask(Mask) || isBroadcastShuffleMask(Mask);
12852 }
12853 
12854 /// Generic routine to decompose a shuffle and blend into independent
12855 /// blends and permutes.
12856 ///
12857 /// This matches the extremely common pattern for handling combined
12858 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
12859 /// operations. It will try to pick the best arrangement of shuffles and
12860 /// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
12861 static SDValue lowerShuffleAsDecomposedShuffleMerge(
12862     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12863     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12864   int NumElts = Mask.size();
12865   int NumLanes = VT.getSizeInBits() / 128;
12866   int NumEltsPerLane = NumElts / NumLanes;
12867 
12868   // Shuffle the input elements into the desired positions in V1 and V2 and
12869   // unpack/blend them together.
12870   bool IsAlternating = true;
12871   SmallVector<int, 32> V1Mask(NumElts, -1);
12872   SmallVector<int, 32> V2Mask(NumElts, -1);
12873   SmallVector<int, 32> FinalMask(NumElts, -1);
12874   for (int i = 0; i < NumElts; ++i) {
12875     int M = Mask[i];
12876     if (M >= 0 && M < NumElts) {
12877       V1Mask[i] = M;
12878       FinalMask[i] = i;
12879       IsAlternating &= (i & 1) == 0;
12880     } else if (M >= NumElts) {
12881       V2Mask[i] = M - NumElts;
12882       FinalMask[i] = i + NumElts;
12883       IsAlternating &= (i & 1) == 1;
12884     }
12885   }
12886 
12887   // If we effectively only demand the 0'th element of \p Input, and not only
12888   // as 0'th element, then broadcast said input,
12889   // and change \p InputMask to be a no-op (identity) mask.
12890   auto canonicalizeBroadcastableInput = [DL, VT, &Subtarget,
12891                                          &DAG](SDValue &Input,
12892                                                MutableArrayRef<int> InputMask) {
12893     unsigned EltSizeInBits = Input.getScalarValueSizeInBits();
12894     if (!Subtarget.hasAVX2() && (!Subtarget.hasAVX() || EltSizeInBits < 32 ||
12895                                  !X86::mayFoldLoad(Input, Subtarget)))
12896       return;
12897     if (isNoopShuffleMask(InputMask))
12898       return;
12899     assert(isBroadcastShuffleMask(InputMask) &&
12900            "Expected to demand only the 0'th element.");
12901     Input = DAG.getNode(X86ISD::VBROADCAST, DL, VT, Input);
12902     for (auto I : enumerate(InputMask)) {
12903       int &InputMaskElt = I.value();
12904       if (InputMaskElt >= 0)
12905         InputMaskElt = I.index();
12906     }
12907   };
12908 
12909   // Currently, we may need to produce one shuffle per input, and blend results.
12910   // It is possible that the shuffle for one of the inputs is already a no-op.
12911   // See if we can simplify non-no-op shuffles into broadcasts,
12912   // which we consider to be strictly better than an arbitrary shuffle.
12913   if (isNoopOrBroadcastShuffleMask(V1Mask) &&
12914       isNoopOrBroadcastShuffleMask(V2Mask)) {
12915     canonicalizeBroadcastableInput(V1, V1Mask);
12916     canonicalizeBroadcastableInput(V2, V2Mask);
12917   }
12918 
12919   // Try to lower with the simpler initial blend/unpack/rotate strategies unless
12920   // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
12921   // the shuffle may be able to fold with a load or other benefit. However, when
12922   // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
12923   // pre-shuffle first is a better strategy.
12924   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
12925     // Only prefer immediate blends to unpack/rotate.
12926     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12927                                                           DAG, true))
12928       return BlendPerm;
12929     if (SDValue UnpackPerm = lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask,
12930                                                            DAG))
12931       return UnpackPerm;
12932     if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
12933             DL, VT, V1, V2, Mask, Subtarget, DAG))
12934       return RotatePerm;
12935     // Unpack/rotate failed - try again with variable blends.
12936     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12937                                                           DAG))
12938       return BlendPerm;
12939   }
12940 
12941   // If the final mask is an alternating blend of vXi8/vXi16, convert to an
12942   // UNPCKL(SHUFFLE, SHUFFLE) pattern.
12943   // TODO: It doesn't have to be alternating - but each lane mustn't have more
12944   // than half the elements coming from each source.
12945   if (IsAlternating && VT.getScalarSizeInBits() < 32) {
12946     V1Mask.assign(NumElts, -1);
12947     V2Mask.assign(NumElts, -1);
12948     FinalMask.assign(NumElts, -1);
12949     for (int i = 0; i != NumElts; i += NumEltsPerLane)
12950       for (int j = 0; j != NumEltsPerLane; ++j) {
12951         int M = Mask[i + j];
12952         if (M >= 0 && M < NumElts) {
12953           V1Mask[i + (j / 2)] = M;
12954           FinalMask[i + j] = i + (j / 2);
12955         } else if (M >= NumElts) {
12956           V2Mask[i + (j / 2)] = M - NumElts;
12957           FinalMask[i + j] = i + (j / 2) + NumElts;
12958         }
12959       }
12960   }
12961 
12962   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12963   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12964   return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
12965 }
12966 
12967 /// Try to lower a vector shuffle as a bit rotation.
12968 ///
12969 /// Look for a repeated rotation pattern in each sub group.
12970 /// Returns a ISD::ROTL element rotation amount or -1 if failed.
12971 static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
12972   int NumElts = Mask.size();
12973   assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
12974 
12975   int RotateAmt = -1;
12976   for (int i = 0; i != NumElts; i += NumSubElts) {
12977     for (int j = 0; j != NumSubElts; ++j) {
12978       int M = Mask[i + j];
12979       if (M < 0)
12980         continue;
12981       if (!isInRange(M, i, i + NumSubElts))
12982         return -1;
12983       int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
12984       if (0 <= RotateAmt && Offset != RotateAmt)
12985         return -1;
12986       RotateAmt = Offset;
12987     }
12988   }
12989   return RotateAmt;
12990 }
12991 
12992 static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
12993                                    const X86Subtarget &Subtarget,
12994                                    ArrayRef<int> Mask) {
12995   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12996   assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
12997 
12998   // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
12999   int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
13000   int MaxSubElts = 64 / EltSizeInBits;
13001   for (int NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
13002     int RotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
13003     if (RotateAmt < 0)
13004       continue;
13005 
13006     int NumElts = Mask.size();
13007     MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
13008     RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
13009     return RotateAmt * EltSizeInBits;
13010   }
13011 
13012   return -1;
13013 }
13014 
13015 /// Lower shuffle using X86ISD::VROTLI rotations.
13016 static SDValue lowerShuffleAsBitRotate(const SDLoc &DL, MVT VT, SDValue V1,
13017                                        ArrayRef<int> Mask,
13018                                        const X86Subtarget &Subtarget,
13019                                        SelectionDAG &DAG) {
13020   // Only XOP + AVX512 targets have bit rotation instructions.
13021   // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
13022   bool IsLegal =
13023       (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
13024   if (!IsLegal && Subtarget.hasSSE3())
13025     return SDValue();
13026 
13027   MVT RotateVT;
13028   int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
13029                                           Subtarget, Mask);
13030   if (RotateAmt < 0)
13031     return SDValue();
13032 
13033   // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
13034   // expanded to OR(SRL,SHL), will be more efficient, but if they can
13035   // widen to vXi16 or more then existing lowering should will be better.
13036   if (!IsLegal) {
13037     if ((RotateAmt % 16) == 0)
13038       return SDValue();
13039     // TODO: Use getTargetVShiftByConstNode.
13040     unsigned ShlAmt = RotateAmt;
13041     unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
13042     V1 = DAG.getBitcast(RotateVT, V1);
13043     SDValue SHL = DAG.getNode(X86ISD::VSHLI, DL, RotateVT, V1,
13044                               DAG.getTargetConstant(ShlAmt, DL, MVT::i8));
13045     SDValue SRL = DAG.getNode(X86ISD::VSRLI, DL, RotateVT, V1,
13046                               DAG.getTargetConstant(SrlAmt, DL, MVT::i8));
13047     SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
13048     return DAG.getBitcast(VT, Rot);
13049   }
13050 
13051   SDValue Rot =
13052       DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
13053                   DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
13054   return DAG.getBitcast(VT, Rot);
13055 }
13056 
13057 /// Try to match a vector shuffle as an element rotation.
13058 ///
13059 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
13060 static int matchShuffleAsElementRotate(SDValue &V1, SDValue &V2,
13061                                        ArrayRef<int> Mask) {
13062   int NumElts = Mask.size();
13063 
13064   // We need to detect various ways of spelling a rotation:
13065   //   [11, 12, 13, 14, 15,  0,  1,  2]
13066   //   [-1, 12, 13, 14, -1, -1,  1, -1]
13067   //   [-1, -1, -1, -1, -1, -1,  1,  2]
13068   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
13069   //   [-1,  4,  5,  6, -1, -1,  9, -1]
13070   //   [-1,  4,  5,  6, -1, -1, -1, -1]
13071   int Rotation = 0;
13072   SDValue Lo, Hi;
13073   for (int i = 0; i < NumElts; ++i) {
13074     int M = Mask[i];
13075     assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
13076            "Unexpected mask index.");
13077     if (M < 0)
13078       continue;
13079 
13080     // Determine where a rotated vector would have started.
13081     int StartIdx = i - (M % NumElts);
13082     if (StartIdx == 0)
13083       // The identity rotation isn't interesting, stop.
13084       return -1;
13085 
13086     // If we found the tail of a vector the rotation must be the missing
13087     // front. If we found the head of a vector, it must be how much of the
13088     // head.
13089     int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
13090 
13091     if (Rotation == 0)
13092       Rotation = CandidateRotation;
13093     else if (Rotation != CandidateRotation)
13094       // The rotations don't match, so we can't match this mask.
13095       return -1;
13096 
13097     // Compute which value this mask is pointing at.
13098     SDValue MaskV = M < NumElts ? V1 : V2;
13099 
13100     // Compute which of the two target values this index should be assigned
13101     // to. This reflects whether the high elements are remaining or the low
13102     // elements are remaining.
13103     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
13104 
13105     // Either set up this value if we've not encountered it before, or check
13106     // that it remains consistent.
13107     if (!TargetV)
13108       TargetV = MaskV;
13109     else if (TargetV != MaskV)
13110       // This may be a rotation, but it pulls from the inputs in some
13111       // unsupported interleaving.
13112       return -1;
13113   }
13114 
13115   // Check that we successfully analyzed the mask, and normalize the results.
13116   assert(Rotation != 0 && "Failed to locate a viable rotation!");
13117   assert((Lo || Hi) && "Failed to find a rotated input vector!");
13118   if (!Lo)
13119     Lo = Hi;
13120   else if (!Hi)
13121     Hi = Lo;
13122 
13123   V1 = Lo;
13124   V2 = Hi;
13125 
13126   return Rotation;
13127 }
13128 
13129 /// Try to lower a vector shuffle as a byte rotation.
13130 ///
13131 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
13132 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
13133 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
13134 /// try to generically lower a vector shuffle through such an pattern. It
13135 /// does not check for the profitability of lowering either as PALIGNR or
13136 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
13137 /// This matches shuffle vectors that look like:
13138 ///
13139 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
13140 ///
13141 /// Essentially it concatenates V1 and V2, shifts right by some number of
13142 /// elements, and takes the low elements as the result. Note that while this is
13143 /// specified as a *right shift* because x86 is little-endian, it is a *left
13144 /// rotate* of the vector lanes.
13145 static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
13146                                     ArrayRef<int> Mask) {
13147   // Don't accept any shuffles with zero elements.
13148   if (isAnyZero(Mask))
13149     return -1;
13150 
13151   // PALIGNR works on 128-bit lanes.
13152   SmallVector<int, 16> RepeatedMask;
13153   if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
13154     return -1;
13155 
13156   int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
13157   if (Rotation <= 0)
13158     return -1;
13159 
13160   // PALIGNR rotates bytes, so we need to scale the
13161   // rotation based on how many bytes are in the vector lane.
13162   int NumElts = RepeatedMask.size();
13163   int Scale = 16 / NumElts;
13164   return Rotation * Scale;
13165 }
13166 
13167 static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
13168                                         SDValue V2, ArrayRef<int> Mask,
13169                                         const X86Subtarget &Subtarget,
13170                                         SelectionDAG &DAG) {
13171   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
13172 
13173   SDValue Lo = V1, Hi = V2;
13174   int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
13175   if (ByteRotation <= 0)
13176     return SDValue();
13177 
13178   // Cast the inputs to i8 vector of correct length to match PALIGNR or
13179   // PSLLDQ/PSRLDQ.
13180   MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
13181   Lo = DAG.getBitcast(ByteVT, Lo);
13182   Hi = DAG.getBitcast(ByteVT, Hi);
13183 
13184   // SSSE3 targets can use the palignr instruction.
13185   if (Subtarget.hasSSSE3()) {
13186     assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
13187            "512-bit PALIGNR requires BWI instructions");
13188     return DAG.getBitcast(
13189         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
13190                         DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
13191   }
13192 
13193   assert(VT.is128BitVector() &&
13194          "Rotate-based lowering only supports 128-bit lowering!");
13195   assert(Mask.size() <= 16 &&
13196          "Can shuffle at most 16 bytes in a 128-bit vector!");
13197   assert(ByteVT == MVT::v16i8 &&
13198          "SSE2 rotate lowering only needed for v16i8!");
13199 
13200   // Default SSE2 implementation
13201   int LoByteShift = 16 - ByteRotation;
13202   int HiByteShift = ByteRotation;
13203 
13204   SDValue LoShift =
13205       DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
13206                   DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
13207   SDValue HiShift =
13208       DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
13209                   DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
13210   return DAG.getBitcast(VT,
13211                         DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
13212 }
13213 
13214 /// Try to lower a vector shuffle as a dword/qword rotation.
13215 ///
13216 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
13217 /// rotation of the concatenation of two vectors; This routine will
13218 /// try to generically lower a vector shuffle through such an pattern.
13219 ///
13220 /// Essentially it concatenates V1 and V2, shifts right by some number of
13221 /// elements, and takes the low elements as the result. Note that while this is
13222 /// specified as a *right shift* because x86 is little-endian, it is a *left
13223 /// rotate* of the vector lanes.
13224 static SDValue lowerShuffleAsVALIGN(const SDLoc &DL, MVT VT, SDValue V1,
13225                                     SDValue V2, ArrayRef<int> Mask,
13226                                     const X86Subtarget &Subtarget,
13227                                     SelectionDAG &DAG) {
13228   assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
13229          "Only 32-bit and 64-bit elements are supported!");
13230 
13231   // 128/256-bit vectors are only supported with VLX.
13232   assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
13233          && "VLX required for 128/256-bit vectors");
13234 
13235   SDValue Lo = V1, Hi = V2;
13236   int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
13237   if (Rotation <= 0)
13238     return SDValue();
13239 
13240   return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
13241                      DAG.getTargetConstant(Rotation, DL, MVT::i8));
13242 }
13243 
13244 /// Try to lower a vector shuffle as a byte shift sequence.
13245 static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
13246                                            SDValue V2, ArrayRef<int> Mask,
13247                                            const APInt &Zeroable,
13248                                            const X86Subtarget &Subtarget,
13249                                            SelectionDAG &DAG) {
13250   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
13251   assert(VT.is128BitVector() && "Only 128-bit vectors supported");
13252 
13253   // We need a shuffle that has zeros at one/both ends and a sequential
13254   // shuffle from one source within.
13255   unsigned ZeroLo = Zeroable.countTrailingOnes();
13256   unsigned ZeroHi = Zeroable.countLeadingOnes();
13257   if (!ZeroLo && !ZeroHi)
13258     return SDValue();
13259 
13260   unsigned NumElts = Mask.size();
13261   unsigned Len = NumElts - (ZeroLo + ZeroHi);
13262   if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
13263     return SDValue();
13264 
13265   unsigned Scale = VT.getScalarSizeInBits() / 8;
13266   ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
13267   if (!isUndefOrInRange(StubMask, 0, NumElts) &&
13268       !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
13269     return SDValue();
13270 
13271   SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
13272   Res = DAG.getBitcast(MVT::v16i8, Res);
13273 
13274   // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
13275   // inner sequential set of elements, possibly offset:
13276   // 01234567 --> zzzzzz01 --> 1zzzzzzz
13277   // 01234567 --> 4567zzzz --> zzzzz456
13278   // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
13279   if (ZeroLo == 0) {
13280     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
13281     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
13282                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
13283     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
13284                       DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
13285   } else if (ZeroHi == 0) {
13286     unsigned Shift = Mask[ZeroLo] % NumElts;
13287     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
13288                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
13289     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
13290                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
13291   } else if (!Subtarget.hasSSSE3()) {
13292     // If we don't have PSHUFB then its worth avoiding an AND constant mask
13293     // by performing 3 byte shifts. Shuffle combining can kick in above that.
13294     // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
13295     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
13296     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
13297                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
13298     Shift += Mask[ZeroLo] % NumElts;
13299     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
13300                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
13301     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
13302                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
13303   } else
13304     return SDValue();
13305 
13306   return DAG.getBitcast(VT, Res);
13307 }
13308 
13309 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
13310 ///
13311 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
13312 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
13313 /// matches elements from one of the input vectors shuffled to the left or
13314 /// right with zeroable elements 'shifted in'. It handles both the strictly
13315 /// bit-wise element shifts and the byte shift across an entire 128-bit double
13316 /// quad word lane.
13317 ///
13318 /// PSHL : (little-endian) left bit shift.
13319 /// [ zz, 0, zz,  2 ]
13320 /// [ -1, 4, zz, -1 ]
13321 /// PSRL : (little-endian) right bit shift.
13322 /// [  1, zz,  3, zz]
13323 /// [ -1, -1,  7, zz]
13324 /// PSLLDQ : (little-endian) left byte shift
13325 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
13326 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
13327 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
13328 /// PSRLDQ : (little-endian) right byte shift
13329 /// [  5, 6,  7, zz, zz, zz, zz, zz]
13330 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
13331 /// [  1, 2, -1, -1, -1, -1, zz, zz]
13332 static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
13333                                unsigned ScalarSizeInBits, ArrayRef<int> Mask,
13334                                int MaskOffset, const APInt &Zeroable,
13335                                const X86Subtarget &Subtarget) {
13336   int Size = Mask.size();
13337   unsigned SizeInBits = Size * ScalarSizeInBits;
13338 
13339   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
13340     for (int i = 0; i < Size; i += Scale)
13341       for (int j = 0; j < Shift; ++j)
13342         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
13343           return false;
13344 
13345     return true;
13346   };
13347 
13348   auto MatchShift = [&](int Shift, int Scale, bool Left) {
13349     for (int i = 0; i != Size; i += Scale) {
13350       unsigned Pos = Left ? i + Shift : i;
13351       unsigned Low = Left ? i : i + Shift;
13352       unsigned Len = Scale - Shift;
13353       if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
13354         return -1;
13355     }
13356 
13357     int ShiftEltBits = ScalarSizeInBits * Scale;
13358     bool ByteShift = ShiftEltBits > 64;
13359     Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
13360                   : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
13361     int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
13362 
13363     // Normalize the scale for byte shifts to still produce an i64 element
13364     // type.
13365     Scale = ByteShift ? Scale / 2 : Scale;
13366 
13367     // We need to round trip through the appropriate type for the shift.
13368     MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
13369     ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
13370                         : MVT::getVectorVT(ShiftSVT, Size / Scale);
13371     return (int)ShiftAmt;
13372   };
13373 
13374   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
13375   // keep doubling the size of the integer elements up to that. We can
13376   // then shift the elements of the integer vector by whole multiples of
13377   // their width within the elements of the larger integer vector. Test each
13378   // multiple to see if we can find a match with the moved element indices
13379   // and that the shifted in elements are all zeroable.
13380   unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
13381   for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
13382     for (int Shift = 1; Shift != Scale; ++Shift)
13383       for (bool Left : {true, false})
13384         if (CheckZeros(Shift, Scale, Left)) {
13385           int ShiftAmt = MatchShift(Shift, Scale, Left);
13386           if (0 < ShiftAmt)
13387             return ShiftAmt;
13388         }
13389 
13390   // no match
13391   return -1;
13392 }
13393 
13394 static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
13395                                    SDValue V2, ArrayRef<int> Mask,
13396                                    const APInt &Zeroable,
13397                                    const X86Subtarget &Subtarget,
13398                                    SelectionDAG &DAG) {
13399   int Size = Mask.size();
13400   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
13401 
13402   MVT ShiftVT;
13403   SDValue V = V1;
13404   unsigned Opcode;
13405 
13406   // Try to match shuffle against V1 shift.
13407   int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
13408                                      Mask, 0, Zeroable, Subtarget);
13409 
13410   // If V1 failed, try to match shuffle against V2 shift.
13411   if (ShiftAmt < 0) {
13412     ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
13413                                    Mask, Size, Zeroable, Subtarget);
13414     V = V2;
13415   }
13416 
13417   if (ShiftAmt < 0)
13418     return SDValue();
13419 
13420   assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
13421          "Illegal integer vector type");
13422   V = DAG.getBitcast(ShiftVT, V);
13423   V = DAG.getNode(Opcode, DL, ShiftVT, V,
13424                   DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
13425   return DAG.getBitcast(VT, V);
13426 }
13427 
13428 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
13429 // Remainder of lower half result is zero and upper half is all undef.
13430 static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
13431                                 ArrayRef<int> Mask, uint64_t &BitLen,
13432                                 uint64_t &BitIdx, const APInt &Zeroable) {
13433   int Size = Mask.size();
13434   int HalfSize = Size / 2;
13435   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
13436   assert(!Zeroable.isAllOnes() && "Fully zeroable shuffle mask");
13437 
13438   // Upper half must be undefined.
13439   if (!isUndefUpperHalf(Mask))
13440     return false;
13441 
13442   // Determine the extraction length from the part of the
13443   // lower half that isn't zeroable.
13444   int Len = HalfSize;
13445   for (; Len > 0; --Len)
13446     if (!Zeroable[Len - 1])
13447       break;
13448   assert(Len > 0 && "Zeroable shuffle mask");
13449 
13450   // Attempt to match first Len sequential elements from the lower half.
13451   SDValue Src;
13452   int Idx = -1;
13453   for (int i = 0; i != Len; ++i) {
13454     int M = Mask[i];
13455     if (M == SM_SentinelUndef)
13456       continue;
13457     SDValue &V = (M < Size ? V1 : V2);
13458     M = M % Size;
13459 
13460     // The extracted elements must start at a valid index and all mask
13461     // elements must be in the lower half.
13462     if (i > M || M >= HalfSize)
13463       return false;
13464 
13465     if (Idx < 0 || (Src == V && Idx == (M - i))) {
13466       Src = V;
13467       Idx = M - i;
13468       continue;
13469     }
13470     return false;
13471   }
13472 
13473   if (!Src || Idx < 0)
13474     return false;
13475 
13476   assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
13477   BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
13478   BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
13479   V1 = Src;
13480   return true;
13481 }
13482 
13483 // INSERTQ: Extract lowest Len elements from lower half of second source and
13484 // insert over first source, starting at Idx.
13485 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
13486 static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
13487                                   ArrayRef<int> Mask, uint64_t &BitLen,
13488                                   uint64_t &BitIdx) {
13489   int Size = Mask.size();
13490   int HalfSize = Size / 2;
13491   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
13492 
13493   // Upper half must be undefined.
13494   if (!isUndefUpperHalf(Mask))
13495     return false;
13496 
13497   for (int Idx = 0; Idx != HalfSize; ++Idx) {
13498     SDValue Base;
13499 
13500     // Attempt to match first source from mask before insertion point.
13501     if (isUndefInRange(Mask, 0, Idx)) {
13502       /* EMPTY */
13503     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
13504       Base = V1;
13505     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
13506       Base = V2;
13507     } else {
13508       continue;
13509     }
13510 
13511     // Extend the extraction length looking to match both the insertion of
13512     // the second source and the remaining elements of the first.
13513     for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
13514       SDValue Insert;
13515       int Len = Hi - Idx;
13516 
13517       // Match insertion.
13518       if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
13519         Insert = V1;
13520       } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
13521         Insert = V2;
13522       } else {
13523         continue;
13524       }
13525 
13526       // Match the remaining elements of the lower half.
13527       if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
13528         /* EMPTY */
13529       } else if ((!Base || (Base == V1)) &&
13530                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
13531         Base = V1;
13532       } else if ((!Base || (Base == V2)) &&
13533                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
13534                                             Size + Hi)) {
13535         Base = V2;
13536       } else {
13537         continue;
13538       }
13539 
13540       BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
13541       BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
13542       V1 = Base;
13543       V2 = Insert;
13544       return true;
13545     }
13546   }
13547 
13548   return false;
13549 }
13550 
13551 /// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
13552 static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
13553                                      SDValue V2, ArrayRef<int> Mask,
13554                                      const APInt &Zeroable, SelectionDAG &DAG) {
13555   uint64_t BitLen, BitIdx;
13556   if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
13557     return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
13558                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
13559                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
13560 
13561   if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
13562     return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
13563                        V2 ? V2 : DAG.getUNDEF(VT),
13564                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
13565                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
13566 
13567   return SDValue();
13568 }
13569 
13570 /// Lower a vector shuffle as a zero or any extension.
13571 ///
13572 /// Given a specific number of elements, element bit width, and extension
13573 /// stride, produce either a zero or any extension based on the available
13574 /// features of the subtarget. The extended elements are consecutive and
13575 /// begin and can start from an offsetted element index in the input; to
13576 /// avoid excess shuffling the offset must either being in the bottom lane
13577 /// or at the start of a higher lane. All extended elements must be from
13578 /// the same lane.
13579 static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
13580     const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
13581     ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13582   assert(Scale > 1 && "Need a scale to extend.");
13583   int EltBits = VT.getScalarSizeInBits();
13584   int NumElements = VT.getVectorNumElements();
13585   int NumEltsPerLane = 128 / EltBits;
13586   int OffsetLane = Offset / NumEltsPerLane;
13587   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
13588          "Only 8, 16, and 32 bit elements can be extended.");
13589   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
13590   assert(0 <= Offset && "Extension offset must be positive.");
13591   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
13592          "Extension offset must be in the first lane or start an upper lane.");
13593 
13594   // Check that an index is in same lane as the base offset.
13595   auto SafeOffset = [&](int Idx) {
13596     return OffsetLane == (Idx / NumEltsPerLane);
13597   };
13598 
13599   // Shift along an input so that the offset base moves to the first element.
13600   auto ShuffleOffset = [&](SDValue V) {
13601     if (!Offset)
13602       return V;
13603 
13604     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
13605     for (int i = 0; i * Scale < NumElements; ++i) {
13606       int SrcIdx = i + Offset;
13607       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
13608     }
13609     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
13610   };
13611 
13612   // Found a valid a/zext mask! Try various lowering strategies based on the
13613   // input type and available ISA extensions.
13614   if (Subtarget.hasSSE41()) {
13615     // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
13616     // PUNPCK will catch this in a later shuffle match.
13617     if (Offset && Scale == 2 && VT.is128BitVector())
13618       return SDValue();
13619     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
13620                                  NumElements / Scale);
13621     InputV = ShuffleOffset(InputV);
13622     InputV = getEXTEND_VECTOR_INREG(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND,
13623                                     DL, ExtVT, InputV, DAG);
13624     return DAG.getBitcast(VT, InputV);
13625   }
13626 
13627   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
13628 
13629   // For any extends we can cheat for larger element sizes and use shuffle
13630   // instructions that can fold with a load and/or copy.
13631   if (AnyExt && EltBits == 32) {
13632     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
13633                          -1};
13634     return DAG.getBitcast(
13635         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
13636                         DAG.getBitcast(MVT::v4i32, InputV),
13637                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13638   }
13639   if (AnyExt && EltBits == 16 && Scale > 2) {
13640     int PSHUFDMask[4] = {Offset / 2, -1,
13641                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
13642     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
13643                          DAG.getBitcast(MVT::v4i32, InputV),
13644                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
13645     int PSHUFWMask[4] = {1, -1, -1, -1};
13646     unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
13647     return DAG.getBitcast(
13648         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
13649                         DAG.getBitcast(MVT::v8i16, InputV),
13650                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
13651   }
13652 
13653   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
13654   // to 64-bits.
13655   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
13656     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
13657     assert(VT.is128BitVector() && "Unexpected vector width!");
13658 
13659     int LoIdx = Offset * EltBits;
13660     SDValue Lo = DAG.getBitcast(
13661         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
13662                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
13663                                 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
13664 
13665     if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
13666       return DAG.getBitcast(VT, Lo);
13667 
13668     int HiIdx = (Offset + 1) * EltBits;
13669     SDValue Hi = DAG.getBitcast(
13670         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
13671                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
13672                                 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
13673     return DAG.getBitcast(VT,
13674                           DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
13675   }
13676 
13677   // If this would require more than 2 unpack instructions to expand, use
13678   // pshufb when available. We can only use more than 2 unpack instructions
13679   // when zero extending i8 elements which also makes it easier to use pshufb.
13680   if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
13681     assert(NumElements == 16 && "Unexpected byte vector width!");
13682     SDValue PSHUFBMask[16];
13683     for (int i = 0; i < 16; ++i) {
13684       int Idx = Offset + (i / Scale);
13685       if ((i % Scale == 0 && SafeOffset(Idx))) {
13686         PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
13687         continue;
13688       }
13689       PSHUFBMask[i] =
13690           AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
13691     }
13692     InputV = DAG.getBitcast(MVT::v16i8, InputV);
13693     return DAG.getBitcast(
13694         VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
13695                         DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
13696   }
13697 
13698   // If we are extending from an offset, ensure we start on a boundary that
13699   // we can unpack from.
13700   int AlignToUnpack = Offset % (NumElements / Scale);
13701   if (AlignToUnpack) {
13702     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
13703     for (int i = AlignToUnpack; i < NumElements; ++i)
13704       ShMask[i - AlignToUnpack] = i;
13705     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
13706     Offset -= AlignToUnpack;
13707   }
13708 
13709   // Otherwise emit a sequence of unpacks.
13710   do {
13711     unsigned UnpackLoHi = X86ISD::UNPCKL;
13712     if (Offset >= (NumElements / 2)) {
13713       UnpackLoHi = X86ISD::UNPCKH;
13714       Offset -= (NumElements / 2);
13715     }
13716 
13717     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
13718     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
13719                          : getZeroVector(InputVT, Subtarget, DAG, DL);
13720     InputV = DAG.getBitcast(InputVT, InputV);
13721     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
13722     Scale /= 2;
13723     EltBits *= 2;
13724     NumElements /= 2;
13725   } while (Scale > 1);
13726   return DAG.getBitcast(VT, InputV);
13727 }
13728 
13729 /// Try to lower a vector shuffle as a zero extension on any microarch.
13730 ///
13731 /// This routine will try to do everything in its power to cleverly lower
13732 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
13733 /// check for the profitability of this lowering,  it tries to aggressively
13734 /// match this pattern. It will use all of the micro-architectural details it
13735 /// can to emit an efficient lowering. It handles both blends with all-zero
13736 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
13737 /// masking out later).
13738 ///
13739 /// The reason we have dedicated lowering for zext-style shuffles is that they
13740 /// are both incredibly common and often quite performance sensitive.
13741 static SDValue lowerShuffleAsZeroOrAnyExtend(
13742     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13743     const APInt &Zeroable, const X86Subtarget &Subtarget,
13744     SelectionDAG &DAG) {
13745   int Bits = VT.getSizeInBits();
13746   int NumLanes = Bits / 128;
13747   int NumElements = VT.getVectorNumElements();
13748   int NumEltsPerLane = NumElements / NumLanes;
13749   assert(VT.getScalarSizeInBits() <= 32 &&
13750          "Exceeds 32-bit integer zero extension limit");
13751   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
13752 
13753   // Define a helper function to check a particular ext-scale and lower to it if
13754   // valid.
13755   auto Lower = [&](int Scale) -> SDValue {
13756     SDValue InputV;
13757     bool AnyExt = true;
13758     int Offset = 0;
13759     int Matches = 0;
13760     for (int i = 0; i < NumElements; ++i) {
13761       int M = Mask[i];
13762       if (M < 0)
13763         continue; // Valid anywhere but doesn't tell us anything.
13764       if (i % Scale != 0) {
13765         // Each of the extended elements need to be zeroable.
13766         if (!Zeroable[i])
13767           return SDValue();
13768 
13769         // We no longer are in the anyext case.
13770         AnyExt = false;
13771         continue;
13772       }
13773 
13774       // Each of the base elements needs to be consecutive indices into the
13775       // same input vector.
13776       SDValue V = M < NumElements ? V1 : V2;
13777       M = M % NumElements;
13778       if (!InputV) {
13779         InputV = V;
13780         Offset = M - (i / Scale);
13781       } else if (InputV != V)
13782         return SDValue(); // Flip-flopping inputs.
13783 
13784       // Offset must start in the lowest 128-bit lane or at the start of an
13785       // upper lane.
13786       // FIXME: Is it ever worth allowing a negative base offset?
13787       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
13788             (Offset % NumEltsPerLane) == 0))
13789         return SDValue();
13790 
13791       // If we are offsetting, all referenced entries must come from the same
13792       // lane.
13793       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
13794         return SDValue();
13795 
13796       if ((M % NumElements) != (Offset + (i / Scale)))
13797         return SDValue(); // Non-consecutive strided elements.
13798       Matches++;
13799     }
13800 
13801     // If we fail to find an input, we have a zero-shuffle which should always
13802     // have already been handled.
13803     // FIXME: Maybe handle this here in case during blending we end up with one?
13804     if (!InputV)
13805       return SDValue();
13806 
13807     // If we are offsetting, don't extend if we only match a single input, we
13808     // can always do better by using a basic PSHUF or PUNPCK.
13809     if (Offset != 0 && Matches < 2)
13810       return SDValue();
13811 
13812     return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
13813                                                  InputV, Mask, Subtarget, DAG);
13814   };
13815 
13816   // The widest scale possible for extending is to a 64-bit integer.
13817   assert(Bits % 64 == 0 &&
13818          "The number of bits in a vector must be divisible by 64 on x86!");
13819   int NumExtElements = Bits / 64;
13820 
13821   // Each iteration, try extending the elements half as much, but into twice as
13822   // many elements.
13823   for (; NumExtElements < NumElements; NumExtElements *= 2) {
13824     assert(NumElements % NumExtElements == 0 &&
13825            "The input vector size must be divisible by the extended size.");
13826     if (SDValue V = Lower(NumElements / NumExtElements))
13827       return V;
13828   }
13829 
13830   // General extends failed, but 128-bit vectors may be able to use MOVQ.
13831   if (Bits != 128)
13832     return SDValue();
13833 
13834   // Returns one of the source operands if the shuffle can be reduced to a
13835   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
13836   auto CanZExtLowHalf = [&]() {
13837     for (int i = NumElements / 2; i != NumElements; ++i)
13838       if (!Zeroable[i])
13839         return SDValue();
13840     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
13841       return V1;
13842     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
13843       return V2;
13844     return SDValue();
13845   };
13846 
13847   if (SDValue V = CanZExtLowHalf()) {
13848     V = DAG.getBitcast(MVT::v2i64, V);
13849     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
13850     return DAG.getBitcast(VT, V);
13851   }
13852 
13853   // No viable ext lowering found.
13854   return SDValue();
13855 }
13856 
13857 /// Try to get a scalar value for a specific element of a vector.
13858 ///
13859 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
13860 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
13861                                               SelectionDAG &DAG) {
13862   MVT VT = V.getSimpleValueType();
13863   MVT EltVT = VT.getVectorElementType();
13864   V = peekThroughBitcasts(V);
13865 
13866   // If the bitcasts shift the element size, we can't extract an equivalent
13867   // element from it.
13868   MVT NewVT = V.getSimpleValueType();
13869   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
13870     return SDValue();
13871 
13872   if (V.getOpcode() == ISD::BUILD_VECTOR ||
13873       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
13874     // Ensure the scalar operand is the same size as the destination.
13875     // FIXME: Add support for scalar truncation where possible.
13876     SDValue S = V.getOperand(Idx);
13877     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
13878       return DAG.getBitcast(EltVT, S);
13879   }
13880 
13881   return SDValue();
13882 }
13883 
13884 /// Helper to test for a load that can be folded with x86 shuffles.
13885 ///
13886 /// This is particularly important because the set of instructions varies
13887 /// significantly based on whether the operand is a load or not.
13888 static bool isShuffleFoldableLoad(SDValue V) {
13889   V = peekThroughBitcasts(V);
13890   return ISD::isNON_EXTLoad(V.getNode());
13891 }
13892 
13893 /// Try to lower insertion of a single element into a zero vector.
13894 ///
13895 /// This is a common pattern that we have especially efficient patterns to lower
13896 /// across all subtarget feature sets.
13897 static SDValue lowerShuffleAsElementInsertion(
13898     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13899     const APInt &Zeroable, const X86Subtarget &Subtarget,
13900     SelectionDAG &DAG) {
13901   MVT ExtVT = VT;
13902   MVT EltVT = VT.getVectorElementType();
13903 
13904   int V2Index =
13905       find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
13906       Mask.begin();
13907   bool IsV1Zeroable = true;
13908   for (int i = 0, Size = Mask.size(); i < Size; ++i)
13909     if (i != V2Index && !Zeroable[i]) {
13910       IsV1Zeroable = false;
13911       break;
13912     }
13913 
13914   // Check for a single input from a SCALAR_TO_VECTOR node.
13915   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
13916   // all the smarts here sunk into that routine. However, the current
13917   // lowering of BUILD_VECTOR makes that nearly impossible until the old
13918   // vector shuffle lowering is dead.
13919   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
13920                                                DAG);
13921   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
13922     // We need to zext the scalar if it is smaller than an i32.
13923     V2S = DAG.getBitcast(EltVT, V2S);
13924     if (EltVT == MVT::i8 || (EltVT == MVT::i16 && !Subtarget.hasFP16())) {
13925       // Using zext to expand a narrow element won't work for non-zero
13926       // insertions.
13927       if (!IsV1Zeroable)
13928         return SDValue();
13929 
13930       // Zero-extend directly to i32.
13931       ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
13932       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
13933     }
13934     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13935   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
13936              EltVT == MVT::i16) {
13937     // Either not inserting from the low element of the input or the input
13938     // element size is too small to use VZEXT_MOVL to clear the high bits.
13939     return SDValue();
13940   }
13941 
13942   if (!IsV1Zeroable) {
13943     // If V1 can't be treated as a zero vector we have fewer options to lower
13944     // this. We can't support integer vectors or non-zero targets cheaply, and
13945     // the V1 elements can't be permuted in any way.
13946     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
13947     if (!VT.isFloatingPoint() || V2Index != 0)
13948       return SDValue();
13949     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
13950     V1Mask[V2Index] = -1;
13951     if (!isNoopShuffleMask(V1Mask))
13952       return SDValue();
13953     if (!VT.is128BitVector())
13954       return SDValue();
13955 
13956     // Otherwise, use MOVSD, MOVSS or MOVSH.
13957     unsigned MovOpc = 0;
13958     if (EltVT == MVT::f16)
13959       MovOpc = X86ISD::MOVSH;
13960     else if (EltVT == MVT::f32)
13961       MovOpc = X86ISD::MOVSS;
13962     else if (EltVT == MVT::f64)
13963       MovOpc = X86ISD::MOVSD;
13964     else
13965       llvm_unreachable("Unsupported floating point element type to handle!");
13966     return DAG.getNode(MovOpc, DL, ExtVT, V1, V2);
13967   }
13968 
13969   // This lowering only works for the low element with floating point vectors.
13970   if (VT.isFloatingPoint() && V2Index != 0)
13971     return SDValue();
13972 
13973   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
13974   if (ExtVT != VT)
13975     V2 = DAG.getBitcast(VT, V2);
13976 
13977   if (V2Index != 0) {
13978     // If we have 4 or fewer lanes we can cheaply shuffle the element into
13979     // the desired position. Otherwise it is more efficient to do a vector
13980     // shift left. We know that we can do a vector shift left because all
13981     // the inputs are zero.
13982     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
13983       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
13984       V2Shuffle[V2Index] = 0;
13985       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
13986     } else {
13987       V2 = DAG.getBitcast(MVT::v16i8, V2);
13988       V2 = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
13989                        DAG.getTargetConstant(
13990                            V2Index * EltVT.getSizeInBits() / 8, DL, MVT::i8));
13991       V2 = DAG.getBitcast(VT, V2);
13992     }
13993   }
13994   return V2;
13995 }
13996 
13997 /// Try to lower broadcast of a single - truncated - integer element,
13998 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
13999 ///
14000 /// This assumes we have AVX2.
14001 static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
14002                                             int BroadcastIdx,
14003                                             const X86Subtarget &Subtarget,
14004                                             SelectionDAG &DAG) {
14005   assert(Subtarget.hasAVX2() &&
14006          "We can only lower integer broadcasts with AVX2!");
14007 
14008   MVT EltVT = VT.getVectorElementType();
14009   MVT V0VT = V0.getSimpleValueType();
14010 
14011   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
14012   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
14013 
14014   MVT V0EltVT = V0VT.getVectorElementType();
14015   if (!V0EltVT.isInteger())
14016     return SDValue();
14017 
14018   const unsigned EltSize = EltVT.getSizeInBits();
14019   const unsigned V0EltSize = V0EltVT.getSizeInBits();
14020 
14021   // This is only a truncation if the original element type is larger.
14022   if (V0EltSize <= EltSize)
14023     return SDValue();
14024 
14025   assert(((V0EltSize % EltSize) == 0) &&
14026          "Scalar type sizes must all be powers of 2 on x86!");
14027 
14028   const unsigned V0Opc = V0.getOpcode();
14029   const unsigned Scale = V0EltSize / EltSize;
14030   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
14031 
14032   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
14033       V0Opc != ISD::BUILD_VECTOR)
14034     return SDValue();
14035 
14036   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
14037 
14038   // If we're extracting non-least-significant bits, shift so we can truncate.
14039   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
14040   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
14041   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
14042   if (const int OffsetIdx = BroadcastIdx % Scale)
14043     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
14044                          DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
14045 
14046   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
14047                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
14048 }
14049 
14050 /// Test whether this can be lowered with a single SHUFPS instruction.
14051 ///
14052 /// This is used to disable more specialized lowerings when the shufps lowering
14053 /// will happen to be efficient.
14054 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
14055   // This routine only handles 128-bit shufps.
14056   assert(Mask.size() == 4 && "Unsupported mask size!");
14057   assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
14058   assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
14059   assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
14060   assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
14061 
14062   // To lower with a single SHUFPS we need to have the low half and high half
14063   // each requiring a single input.
14064   if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
14065     return false;
14066   if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
14067     return false;
14068 
14069   return true;
14070 }
14071 
14072 /// If we are extracting two 128-bit halves of a vector and shuffling the
14073 /// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
14074 /// multi-shuffle lowering.
14075 static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
14076                                              SDValue N1, ArrayRef<int> Mask,
14077                                              SelectionDAG &DAG) {
14078   MVT VT = N0.getSimpleValueType();
14079   assert((VT.is128BitVector() &&
14080           (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
14081          "VPERM* family of shuffles requires 32-bit or 64-bit elements");
14082 
14083   // Check that both sources are extracts of the same source vector.
14084   if (!N0.hasOneUse() || !N1.hasOneUse() ||
14085       N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14086       N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14087       N0.getOperand(0) != N1.getOperand(0))
14088     return SDValue();
14089 
14090   SDValue WideVec = N0.getOperand(0);
14091   MVT WideVT = WideVec.getSimpleValueType();
14092   if (!WideVT.is256BitVector())
14093     return SDValue();
14094 
14095   // Match extracts of each half of the wide source vector. Commute the shuffle
14096   // if the extract of the low half is N1.
14097   unsigned NumElts = VT.getVectorNumElements();
14098   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
14099   const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
14100   const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
14101   if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
14102     ShuffleVectorSDNode::commuteMask(NewMask);
14103   else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
14104     return SDValue();
14105 
14106   // Final bailout: if the mask is simple, we are better off using an extract
14107   // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
14108   // because that avoids a constant load from memory.
14109   if (NumElts == 4 &&
14110       (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask)))
14111     return SDValue();
14112 
14113   // Extend the shuffle mask with undef elements.
14114   NewMask.append(NumElts, -1);
14115 
14116   // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
14117   SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
14118                                       NewMask);
14119   // This is free: ymm -> xmm.
14120   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
14121                      DAG.getIntPtrConstant(0, DL));
14122 }
14123 
14124 /// Try to lower broadcast of a single element.
14125 ///
14126 /// For convenience, this code also bundles all of the subtarget feature set
14127 /// filtering. While a little annoying to re-dispatch on type here, there isn't
14128 /// a convenient way to factor it out.
14129 static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
14130                                        SDValue V2, ArrayRef<int> Mask,
14131                                        const X86Subtarget &Subtarget,
14132                                        SelectionDAG &DAG) {
14133   if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
14134         (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
14135         (Subtarget.hasAVX2() && VT.isInteger())))
14136     return SDValue();
14137 
14138   // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
14139   // we can only broadcast from a register with AVX2.
14140   unsigned NumEltBits = VT.getScalarSizeInBits();
14141   unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
14142                         ? X86ISD::MOVDDUP
14143                         : X86ISD::VBROADCAST;
14144   bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
14145 
14146   // Check that the mask is a broadcast.
14147   int BroadcastIdx = getSplatIndex(Mask);
14148   if (BroadcastIdx < 0)
14149     return SDValue();
14150   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
14151                                             "a sorted mask where the broadcast "
14152                                             "comes from V1.");
14153 
14154   // Go up the chain of (vector) values to find a scalar load that we can
14155   // combine with the broadcast.
14156   // TODO: Combine this logic with findEltLoadSrc() used by
14157   //       EltsFromConsecutiveLoads().
14158   int BitOffset = BroadcastIdx * NumEltBits;
14159   SDValue V = V1;
14160   for (;;) {
14161     switch (V.getOpcode()) {
14162     case ISD::BITCAST: {
14163       V = V.getOperand(0);
14164       continue;
14165     }
14166     case ISD::CONCAT_VECTORS: {
14167       int OpBitWidth = V.getOperand(0).getValueSizeInBits();
14168       int OpIdx = BitOffset / OpBitWidth;
14169       V = V.getOperand(OpIdx);
14170       BitOffset %= OpBitWidth;
14171       continue;
14172     }
14173     case ISD::EXTRACT_SUBVECTOR: {
14174       // The extraction index adds to the existing offset.
14175       unsigned EltBitWidth = V.getScalarValueSizeInBits();
14176       unsigned Idx = V.getConstantOperandVal(1);
14177       unsigned BeginOffset = Idx * EltBitWidth;
14178       BitOffset += BeginOffset;
14179       V = V.getOperand(0);
14180       continue;
14181     }
14182     case ISD::INSERT_SUBVECTOR: {
14183       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
14184       int EltBitWidth = VOuter.getScalarValueSizeInBits();
14185       int Idx = (int)V.getConstantOperandVal(2);
14186       int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
14187       int BeginOffset = Idx * EltBitWidth;
14188       int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
14189       if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
14190         BitOffset -= BeginOffset;
14191         V = VInner;
14192       } else {
14193         V = VOuter;
14194       }
14195       continue;
14196     }
14197     }
14198     break;
14199   }
14200   assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
14201   BroadcastIdx = BitOffset / NumEltBits;
14202 
14203   // Do we need to bitcast the source to retrieve the original broadcast index?
14204   bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
14205 
14206   // Check if this is a broadcast of a scalar. We special case lowering
14207   // for scalars so that we can more effectively fold with loads.
14208   // If the original value has a larger element type than the shuffle, the
14209   // broadcast element is in essence truncated. Make that explicit to ease
14210   // folding.
14211   if (BitCastSrc && VT.isInteger())
14212     if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
14213             DL, VT, V, BroadcastIdx, Subtarget, DAG))
14214       return TruncBroadcast;
14215 
14216   // Also check the simpler case, where we can directly reuse the scalar.
14217   if (!BitCastSrc &&
14218       ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
14219        (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
14220     V = V.getOperand(BroadcastIdx);
14221 
14222     // If we can't broadcast from a register, check that the input is a load.
14223     if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
14224       return SDValue();
14225   } else if (ISD::isNormalLoad(V.getNode()) &&
14226              cast<LoadSDNode>(V)->isSimple()) {
14227     // We do not check for one-use of the vector load because a broadcast load
14228     // is expected to be a win for code size, register pressure, and possibly
14229     // uops even if the original vector load is not eliminated.
14230 
14231     // Reduce the vector load and shuffle to a broadcasted scalar load.
14232     LoadSDNode *Ld = cast<LoadSDNode>(V);
14233     SDValue BaseAddr = Ld->getOperand(1);
14234     MVT SVT = VT.getScalarType();
14235     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
14236     assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
14237     SDValue NewAddr =
14238         DAG.getMemBasePlusOffset(BaseAddr, TypeSize::Fixed(Offset), DL);
14239 
14240     // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
14241     // than MOVDDUP.
14242     // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
14243     if (Opcode == X86ISD::VBROADCAST) {
14244       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
14245       SDValue Ops[] = {Ld->getChain(), NewAddr};
14246       V = DAG.getMemIntrinsicNode(
14247           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
14248           DAG.getMachineFunction().getMachineMemOperand(
14249               Ld->getMemOperand(), Offset, SVT.getStoreSize()));
14250       DAG.makeEquivalentMemoryOrdering(Ld, V);
14251       return DAG.getBitcast(VT, V);
14252     }
14253     assert(SVT == MVT::f64 && "Unexpected VT!");
14254     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
14255                     DAG.getMachineFunction().getMachineMemOperand(
14256                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
14257     DAG.makeEquivalentMemoryOrdering(Ld, V);
14258   } else if (!BroadcastFromReg) {
14259     // We can't broadcast from a vector register.
14260     return SDValue();
14261   } else if (BitOffset != 0) {
14262     // We can only broadcast from the zero-element of a vector register,
14263     // but it can be advantageous to broadcast from the zero-element of a
14264     // subvector.
14265     if (!VT.is256BitVector() && !VT.is512BitVector())
14266       return SDValue();
14267 
14268     // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
14269     if (VT == MVT::v4f64 || VT == MVT::v4i64)
14270       return SDValue();
14271 
14272     // Only broadcast the zero-element of a 128-bit subvector.
14273     if ((BitOffset % 128) != 0)
14274       return SDValue();
14275 
14276     assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
14277            "Unexpected bit-offset");
14278     assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
14279            "Unexpected vector size");
14280     unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
14281     V = extract128BitVector(V, ExtractIdx, DAG, DL);
14282   }
14283 
14284   // On AVX we can use VBROADCAST directly for scalar sources.
14285   if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
14286     V = DAG.getBitcast(MVT::f64, V);
14287     if (Subtarget.hasAVX()) {
14288       V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
14289       return DAG.getBitcast(VT, V);
14290     }
14291     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
14292   }
14293 
14294   // If this is a scalar, do the broadcast on this type and bitcast.
14295   if (!V.getValueType().isVector()) {
14296     assert(V.getScalarValueSizeInBits() == NumEltBits &&
14297            "Unexpected scalar size");
14298     MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
14299                                        VT.getVectorNumElements());
14300     return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
14301   }
14302 
14303   // We only support broadcasting from 128-bit vectors to minimize the
14304   // number of patterns we need to deal with in isel. So extract down to
14305   // 128-bits, removing as many bitcasts as possible.
14306   if (V.getValueSizeInBits() > 128)
14307     V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
14308 
14309   // Otherwise cast V to a vector with the same element type as VT, but
14310   // possibly narrower than VT. Then perform the broadcast.
14311   unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
14312   MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
14313   return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
14314 }
14315 
14316 // Check for whether we can use INSERTPS to perform the shuffle. We only use
14317 // INSERTPS when the V1 elements are already in the correct locations
14318 // because otherwise we can just always use two SHUFPS instructions which
14319 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
14320 // perform INSERTPS if a single V1 element is out of place and all V2
14321 // elements are zeroable.
14322 static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
14323                                    unsigned &InsertPSMask,
14324                                    const APInt &Zeroable,
14325                                    ArrayRef<int> Mask, SelectionDAG &DAG) {
14326   assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
14327   assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
14328   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14329 
14330   // Attempt to match INSERTPS with one element from VA or VB being
14331   // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
14332   // are updated.
14333   auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
14334                              ArrayRef<int> CandidateMask) {
14335     unsigned ZMask = 0;
14336     int VADstIndex = -1;
14337     int VBDstIndex = -1;
14338     bool VAUsedInPlace = false;
14339 
14340     for (int i = 0; i < 4; ++i) {
14341       // Synthesize a zero mask from the zeroable elements (includes undefs).
14342       if (Zeroable[i]) {
14343         ZMask |= 1 << i;
14344         continue;
14345       }
14346 
14347       // Flag if we use any VA inputs in place.
14348       if (i == CandidateMask[i]) {
14349         VAUsedInPlace = true;
14350         continue;
14351       }
14352 
14353       // We can only insert a single non-zeroable element.
14354       if (VADstIndex >= 0 || VBDstIndex >= 0)
14355         return false;
14356 
14357       if (CandidateMask[i] < 4) {
14358         // VA input out of place for insertion.
14359         VADstIndex = i;
14360       } else {
14361         // VB input for insertion.
14362         VBDstIndex = i;
14363       }
14364     }
14365 
14366     // Don't bother if we have no (non-zeroable) element for insertion.
14367     if (VADstIndex < 0 && VBDstIndex < 0)
14368       return false;
14369 
14370     // Determine element insertion src/dst indices. The src index is from the
14371     // start of the inserted vector, not the start of the concatenated vector.
14372     unsigned VBSrcIndex = 0;
14373     if (VADstIndex >= 0) {
14374       // If we have a VA input out of place, we use VA as the V2 element
14375       // insertion and don't use the original V2 at all.
14376       VBSrcIndex = CandidateMask[VADstIndex];
14377       VBDstIndex = VADstIndex;
14378       VB = VA;
14379     } else {
14380       VBSrcIndex = CandidateMask[VBDstIndex] - 4;
14381     }
14382 
14383     // If no V1 inputs are used in place, then the result is created only from
14384     // the zero mask and the V2 insertion - so remove V1 dependency.
14385     if (!VAUsedInPlace)
14386       VA = DAG.getUNDEF(MVT::v4f32);
14387 
14388     // Update V1, V2 and InsertPSMask accordingly.
14389     V1 = VA;
14390     V2 = VB;
14391 
14392     // Insert the V2 element into the desired position.
14393     InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
14394     assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
14395     return true;
14396   };
14397 
14398   if (matchAsInsertPS(V1, V2, Mask))
14399     return true;
14400 
14401   // Commute and try again.
14402   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
14403   ShuffleVectorSDNode::commuteMask(CommutedMask);
14404   if (matchAsInsertPS(V2, V1, CommutedMask))
14405     return true;
14406 
14407   return false;
14408 }
14409 
14410 static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
14411                                       ArrayRef<int> Mask, const APInt &Zeroable,
14412                                       SelectionDAG &DAG) {
14413   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
14414   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
14415 
14416   // Attempt to match the insertps pattern.
14417   unsigned InsertPSMask = 0;
14418   if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
14419     return SDValue();
14420 
14421   // Insert the V2 element into the desired position.
14422   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
14423                      DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
14424 }
14425 
14426 /// Try to lower a shuffle as a permute of the inputs followed by an
14427 /// UNPCK instruction.
14428 ///
14429 /// This specifically targets cases where we end up with alternating between
14430 /// the two inputs, and so can permute them into something that feeds a single
14431 /// UNPCK instruction. Note that this routine only targets integer vectors
14432 /// because for floating point vectors we have a generalized SHUFPS lowering
14433 /// strategy that handles everything that doesn't *exactly* match an unpack,
14434 /// making this clever lowering unnecessary.
14435 static SDValue lowerShuffleAsPermuteAndUnpack(
14436     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14437     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14438   assert(!VT.isFloatingPoint() &&
14439          "This routine only supports integer vectors.");
14440   assert(VT.is128BitVector() &&
14441          "This routine only works on 128-bit vectors.");
14442   assert(!V2.isUndef() &&
14443          "This routine should only be used when blending two inputs.");
14444   assert(Mask.size() >= 2 && "Single element masks are invalid.");
14445 
14446   int Size = Mask.size();
14447 
14448   int NumLoInputs =
14449       count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
14450   int NumHiInputs =
14451       count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
14452 
14453   bool UnpackLo = NumLoInputs >= NumHiInputs;
14454 
14455   auto TryUnpack = [&](int ScalarSize, int Scale) {
14456     SmallVector<int, 16> V1Mask((unsigned)Size, -1);
14457     SmallVector<int, 16> V2Mask((unsigned)Size, -1);
14458 
14459     for (int i = 0; i < Size; ++i) {
14460       if (Mask[i] < 0)
14461         continue;
14462 
14463       // Each element of the unpack contains Scale elements from this mask.
14464       int UnpackIdx = i / Scale;
14465 
14466       // We only handle the case where V1 feeds the first slots of the unpack.
14467       // We rely on canonicalization to ensure this is the case.
14468       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
14469         return SDValue();
14470 
14471       // Setup the mask for this input. The indexing is tricky as we have to
14472       // handle the unpack stride.
14473       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
14474       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
14475           Mask[i] % Size;
14476     }
14477 
14478     // If we will have to shuffle both inputs to use the unpack, check whether
14479     // we can just unpack first and shuffle the result. If so, skip this unpack.
14480     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
14481         !isNoopShuffleMask(V2Mask))
14482       return SDValue();
14483 
14484     // Shuffle the inputs into place.
14485     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
14486     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
14487 
14488     // Cast the inputs to the type we will use to unpack them.
14489     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
14490     V1 = DAG.getBitcast(UnpackVT, V1);
14491     V2 = DAG.getBitcast(UnpackVT, V2);
14492 
14493     // Unpack the inputs and cast the result back to the desired type.
14494     return DAG.getBitcast(
14495         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
14496                         UnpackVT, V1, V2));
14497   };
14498 
14499   // We try each unpack from the largest to the smallest to try and find one
14500   // that fits this mask.
14501   int OrigScalarSize = VT.getScalarSizeInBits();
14502   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
14503     if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
14504       return Unpack;
14505 
14506   // If we're shuffling with a zero vector then we're better off not doing
14507   // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
14508   if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
14509       ISD::isBuildVectorAllZeros(V2.getNode()))
14510     return SDValue();
14511 
14512   // If none of the unpack-rooted lowerings worked (or were profitable) try an
14513   // initial unpack.
14514   if (NumLoInputs == 0 || NumHiInputs == 0) {
14515     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
14516            "We have to have *some* inputs!");
14517     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
14518 
14519     // FIXME: We could consider the total complexity of the permute of each
14520     // possible unpacking. Or at the least we should consider how many
14521     // half-crossings are created.
14522     // FIXME: We could consider commuting the unpacks.
14523 
14524     SmallVector<int, 32> PermMask((unsigned)Size, -1);
14525     for (int i = 0; i < Size; ++i) {
14526       if (Mask[i] < 0)
14527         continue;
14528 
14529       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
14530 
14531       PermMask[i] =
14532           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
14533     }
14534     return DAG.getVectorShuffle(
14535         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
14536                             DL, VT, V1, V2),
14537         DAG.getUNDEF(VT), PermMask);
14538   }
14539 
14540   return SDValue();
14541 }
14542 
14543 /// Handle lowering of 2-lane 64-bit floating point shuffles.
14544 ///
14545 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
14546 /// support for floating point shuffles but not integer shuffles. These
14547 /// instructions will incur a domain crossing penalty on some chips though so
14548 /// it is better to avoid lowering through this for integer vectors where
14549 /// possible.
14550 static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14551                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14552                                  const X86Subtarget &Subtarget,
14553                                  SelectionDAG &DAG) {
14554   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
14555   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
14556   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
14557 
14558   if (V2.isUndef()) {
14559     // Check for being able to broadcast a single element.
14560     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
14561                                                     Mask, Subtarget, DAG))
14562       return Broadcast;
14563 
14564     // Straight shuffle of a single input vector. Simulate this by using the
14565     // single input as both of the "inputs" to this instruction..
14566     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
14567 
14568     if (Subtarget.hasAVX()) {
14569       // If we have AVX, we can use VPERMILPS which will allow folding a load
14570       // into the shuffle.
14571       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
14572                          DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14573     }
14574 
14575     return DAG.getNode(
14576         X86ISD::SHUFP, DL, MVT::v2f64,
14577         Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
14578         Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
14579         DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14580   }
14581   assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
14582   assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
14583   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
14584   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
14585 
14586   if (Subtarget.hasAVX2())
14587     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14588       return Extract;
14589 
14590   // When loading a scalar and then shuffling it into a vector we can often do
14591   // the insertion cheaply.
14592   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14593           DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
14594     return Insertion;
14595   // Try inverting the insertion since for v2 masks it is easy to do and we
14596   // can't reliably sort the mask one way or the other.
14597   int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
14598                         Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
14599   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14600           DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
14601     return Insertion;
14602 
14603   // Try to use one of the special instruction patterns to handle two common
14604   // blend patterns if a zero-blend above didn't work.
14605   if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
14606       isShuffleEquivalent(Mask, {1, 3}, V1, V2))
14607     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
14608       // We can either use a special instruction to load over the low double or
14609       // to move just the low double.
14610       return DAG.getNode(
14611           X86ISD::MOVSD, DL, MVT::v2f64, V2,
14612           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
14613 
14614   if (Subtarget.hasSSE41())
14615     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
14616                                             Zeroable, Subtarget, DAG))
14617       return Blend;
14618 
14619   // Use dedicated unpack instructions for masks that match their pattern.
14620   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
14621     return V;
14622 
14623   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
14624   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
14625                      DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14626 }
14627 
14628 /// Handle lowering of 2-lane 64-bit integer shuffles.
14629 ///
14630 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
14631 /// the integer unit to minimize domain crossing penalties. However, for blends
14632 /// it falls back to the floating point shuffle operation with appropriate bit
14633 /// casting.
14634 static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14635                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14636                                  const X86Subtarget &Subtarget,
14637                                  SelectionDAG &DAG) {
14638   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
14639   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
14640   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
14641 
14642   if (V2.isUndef()) {
14643     // Check for being able to broadcast a single element.
14644     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
14645                                                     Mask, Subtarget, DAG))
14646       return Broadcast;
14647 
14648     // Straight shuffle of a single input vector. For everything from SSE2
14649     // onward this has a single fast instruction with no scary immediates.
14650     // We have to map the mask as it is actually a v4i32 shuffle instruction.
14651     V1 = DAG.getBitcast(MVT::v4i32, V1);
14652     int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
14653                           Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
14654                           Mask[1] < 0 ? -1 : (Mask[1] * 2),
14655                           Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
14656     return DAG.getBitcast(
14657         MVT::v2i64,
14658         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14659                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
14660   }
14661   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
14662   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
14663   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
14664   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
14665 
14666   if (Subtarget.hasAVX2())
14667     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14668       return Extract;
14669 
14670   // Try to use shift instructions.
14671   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
14672                                           Zeroable, Subtarget, DAG))
14673     return Shift;
14674 
14675   // When loading a scalar and then shuffling it into a vector we can often do
14676   // the insertion cheaply.
14677   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14678           DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
14679     return Insertion;
14680   // Try inverting the insertion since for v2 masks it is easy to do and we
14681   // can't reliably sort the mask one way or the other.
14682   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
14683   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14684           DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
14685     return Insertion;
14686 
14687   // We have different paths for blend lowering, but they all must use the
14688   // *exact* same predicate.
14689   bool IsBlendSupported = Subtarget.hasSSE41();
14690   if (IsBlendSupported)
14691     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
14692                                             Zeroable, Subtarget, DAG))
14693       return Blend;
14694 
14695   // Use dedicated unpack instructions for masks that match their pattern.
14696   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
14697     return V;
14698 
14699   // Try to use byte rotation instructions.
14700   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14701   if (Subtarget.hasSSSE3()) {
14702     if (Subtarget.hasVLX())
14703       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
14704                                                 Subtarget, DAG))
14705         return Rotate;
14706 
14707     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
14708                                                   Subtarget, DAG))
14709       return Rotate;
14710   }
14711 
14712   // If we have direct support for blends, we should lower by decomposing into
14713   // a permute. That will be faster than the domain cross.
14714   if (IsBlendSupported)
14715     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
14716                                                 Subtarget, DAG);
14717 
14718   // We implement this with SHUFPD which is pretty lame because it will likely
14719   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
14720   // However, all the alternatives are still more cycles and newer chips don't
14721   // have this problem. It would be really nice if x86 had better shuffles here.
14722   V1 = DAG.getBitcast(MVT::v2f64, V1);
14723   V2 = DAG.getBitcast(MVT::v2f64, V2);
14724   return DAG.getBitcast(MVT::v2i64,
14725                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
14726 }
14727 
14728 /// Lower a vector shuffle using the SHUFPS instruction.
14729 ///
14730 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
14731 /// It makes no assumptions about whether this is the *best* lowering, it simply
14732 /// uses it.
14733 static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
14734                                       ArrayRef<int> Mask, SDValue V1,
14735                                       SDValue V2, SelectionDAG &DAG) {
14736   SDValue LowV = V1, HighV = V2;
14737   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
14738   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14739 
14740   if (NumV2Elements == 1) {
14741     int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
14742 
14743     // Compute the index adjacent to V2Index and in the same half by toggling
14744     // the low bit.
14745     int V2AdjIndex = V2Index ^ 1;
14746 
14747     if (Mask[V2AdjIndex] < 0) {
14748       // Handles all the cases where we have a single V2 element and an undef.
14749       // This will only ever happen in the high lanes because we commute the
14750       // vector otherwise.
14751       if (V2Index < 2)
14752         std::swap(LowV, HighV);
14753       NewMask[V2Index] -= 4;
14754     } else {
14755       // Handle the case where the V2 element ends up adjacent to a V1 element.
14756       // To make this work, blend them together as the first step.
14757       int V1Index = V2AdjIndex;
14758       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
14759       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
14760                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
14761 
14762       // Now proceed to reconstruct the final blend as we have the necessary
14763       // high or low half formed.
14764       if (V2Index < 2) {
14765         LowV = V2;
14766         HighV = V1;
14767       } else {
14768         HighV = V2;
14769       }
14770       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
14771       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
14772     }
14773   } else if (NumV2Elements == 2) {
14774     if (Mask[0] < 4 && Mask[1] < 4) {
14775       // Handle the easy case where we have V1 in the low lanes and V2 in the
14776       // high lanes.
14777       NewMask[2] -= 4;
14778       NewMask[3] -= 4;
14779     } else if (Mask[2] < 4 && Mask[3] < 4) {
14780       // We also handle the reversed case because this utility may get called
14781       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
14782       // arrange things in the right direction.
14783       NewMask[0] -= 4;
14784       NewMask[1] -= 4;
14785       HighV = V1;
14786       LowV = V2;
14787     } else {
14788       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
14789       // trying to place elements directly, just blend them and set up the final
14790       // shuffle to place them.
14791 
14792       // The first two blend mask elements are for V1, the second two are for
14793       // V2.
14794       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
14795                           Mask[2] < 4 ? Mask[2] : Mask[3],
14796                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
14797                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
14798       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
14799                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
14800 
14801       // Now we do a normal shuffle of V1 by giving V1 as both operands to
14802       // a blend.
14803       LowV = HighV = V1;
14804       NewMask[0] = Mask[0] < 4 ? 0 : 2;
14805       NewMask[1] = Mask[0] < 4 ? 2 : 0;
14806       NewMask[2] = Mask[2] < 4 ? 1 : 3;
14807       NewMask[3] = Mask[2] < 4 ? 3 : 1;
14808     }
14809   } else if (NumV2Elements == 3) {
14810     // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
14811     // we can get here due to other paths (e.g repeated mask matching) that we
14812     // don't want to do another round of lowerVECTOR_SHUFFLE.
14813     ShuffleVectorSDNode::commuteMask(NewMask);
14814     return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
14815   }
14816   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
14817                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
14818 }
14819 
14820 /// Lower 4-lane 32-bit floating point shuffles.
14821 ///
14822 /// Uses instructions exclusively from the floating point unit to minimize
14823 /// domain crossing penalties, as these are sufficient to implement all v4f32
14824 /// shuffles.
14825 static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14826                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14827                                  const X86Subtarget &Subtarget,
14828                                  SelectionDAG &DAG) {
14829   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
14830   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
14831   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14832 
14833   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14834 
14835   if (NumV2Elements == 0) {
14836     // Check for being able to broadcast a single element.
14837     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
14838                                                     Mask, Subtarget, DAG))
14839       return Broadcast;
14840 
14841     // Use even/odd duplicate instructions for masks that match their pattern.
14842     if (Subtarget.hasSSE3()) {
14843       if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
14844         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
14845       if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
14846         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
14847     }
14848 
14849     if (Subtarget.hasAVX()) {
14850       // If we have AVX, we can use VPERMILPS which will allow folding a load
14851       // into the shuffle.
14852       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
14853                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14854     }
14855 
14856     // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
14857     // in SSE1 because otherwise they are widened to v2f64 and never get here.
14858     if (!Subtarget.hasSSE2()) {
14859       if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
14860         return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
14861       if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
14862         return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
14863     }
14864 
14865     // Otherwise, use a straight shuffle of a single input vector. We pass the
14866     // input vector to both operands to simulate this with a SHUFPS.
14867     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
14868                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14869   }
14870 
14871   if (Subtarget.hasAVX2())
14872     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14873       return Extract;
14874 
14875   // There are special ways we can lower some single-element blends. However, we
14876   // have custom ways we can lower more complex single-element blends below that
14877   // we defer to if both this and BLENDPS fail to match, so restrict this to
14878   // when the V2 input is targeting element 0 of the mask -- that is the fast
14879   // case here.
14880   if (NumV2Elements == 1 && Mask[0] >= 4)
14881     if (SDValue V = lowerShuffleAsElementInsertion(
14882             DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14883       return V;
14884 
14885   if (Subtarget.hasSSE41()) {
14886     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
14887                                             Zeroable, Subtarget, DAG))
14888       return Blend;
14889 
14890     // Use INSERTPS if we can complete the shuffle efficiently.
14891     if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
14892       return V;
14893 
14894     if (!isSingleSHUFPSMask(Mask))
14895       if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
14896                                                             V2, Mask, DAG))
14897         return BlendPerm;
14898   }
14899 
14900   // Use low/high mov instructions. These are only valid in SSE1 because
14901   // otherwise they are widened to v2f64 and never get here.
14902   if (!Subtarget.hasSSE2()) {
14903     if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
14904       return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
14905     if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
14906       return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
14907   }
14908 
14909   // Use dedicated unpack instructions for masks that match their pattern.
14910   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
14911     return V;
14912 
14913   // Otherwise fall back to a SHUFPS lowering strategy.
14914   return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
14915 }
14916 
14917 /// Lower 4-lane i32 vector shuffles.
14918 ///
14919 /// We try to handle these with integer-domain shuffles where we can, but for
14920 /// blends we use the floating point domain blend instructions.
14921 static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14922                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14923                                  const X86Subtarget &Subtarget,
14924                                  SelectionDAG &DAG) {
14925   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14926   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14927   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14928 
14929   // Whenever we can lower this as a zext, that instruction is strictly faster
14930   // than any alternative. It also allows us to fold memory operands into the
14931   // shuffle in many cases.
14932   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
14933                                                    Zeroable, Subtarget, DAG))
14934     return ZExt;
14935 
14936   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14937 
14938   if (NumV2Elements == 0) {
14939     // Try to use broadcast unless the mask only has one non-undef element.
14940     if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
14941       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
14942                                                       Mask, Subtarget, DAG))
14943         return Broadcast;
14944     }
14945 
14946     // Straight shuffle of a single input vector. For everything from SSE2
14947     // onward this has a single fast instruction with no scary immediates.
14948     // We coerce the shuffle pattern to be compatible with UNPCK instructions
14949     // but we aren't actually going to use the UNPCK instruction because doing
14950     // so prevents folding a load into this instruction or making a copy.
14951     const int UnpackLoMask[] = {0, 0, 1, 1};
14952     const int UnpackHiMask[] = {2, 2, 3, 3};
14953     if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
14954       Mask = UnpackLoMask;
14955     else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
14956       Mask = UnpackHiMask;
14957 
14958     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14959                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14960   }
14961 
14962   if (Subtarget.hasAVX2())
14963     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14964       return Extract;
14965 
14966   // Try to use shift instructions.
14967   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
14968                                           Zeroable, Subtarget, DAG))
14969     return Shift;
14970 
14971   // There are special ways we can lower some single-element blends.
14972   if (NumV2Elements == 1)
14973     if (SDValue V = lowerShuffleAsElementInsertion(
14974             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14975       return V;
14976 
14977   // We have different paths for blend lowering, but they all must use the
14978   // *exact* same predicate.
14979   bool IsBlendSupported = Subtarget.hasSSE41();
14980   if (IsBlendSupported)
14981     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
14982                                             Zeroable, Subtarget, DAG))
14983       return Blend;
14984 
14985   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
14986                                              Zeroable, Subtarget, DAG))
14987     return Masked;
14988 
14989   // Use dedicated unpack instructions for masks that match their pattern.
14990   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
14991     return V;
14992 
14993   // Try to use byte rotation instructions.
14994   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14995   if (Subtarget.hasSSSE3()) {
14996     if (Subtarget.hasVLX())
14997       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
14998                                                 Subtarget, DAG))
14999         return Rotate;
15000 
15001     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
15002                                                   Subtarget, DAG))
15003       return Rotate;
15004   }
15005 
15006   // Assume that a single SHUFPS is faster than an alternative sequence of
15007   // multiple instructions (even if the CPU has a domain penalty).
15008   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
15009   if (!isSingleSHUFPSMask(Mask)) {
15010     // If we have direct support for blends, we should lower by decomposing into
15011     // a permute. That will be faster than the domain cross.
15012     if (IsBlendSupported)
15013       return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
15014                                                   Subtarget, DAG);
15015 
15016     // Try to lower by permuting the inputs into an unpack instruction.
15017     if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
15018                                                         Mask, Subtarget, DAG))
15019       return Unpack;
15020   }
15021 
15022   // We implement this with SHUFPS because it can blend from two vectors.
15023   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
15024   // up the inputs, bypassing domain shift penalties that we would incur if we
15025   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
15026   // relevant.
15027   SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
15028   SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
15029   SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
15030   return DAG.getBitcast(MVT::v4i32, ShufPS);
15031 }
15032 
15033 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
15034 /// shuffle lowering, and the most complex part.
15035 ///
15036 /// The lowering strategy is to try to form pairs of input lanes which are
15037 /// targeted at the same half of the final vector, and then use a dword shuffle
15038 /// to place them onto the right half, and finally unpack the paired lanes into
15039 /// their final position.
15040 ///
15041 /// The exact breakdown of how to form these dword pairs and align them on the
15042 /// correct sides is really tricky. See the comments within the function for
15043 /// more of the details.
15044 ///
15045 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
15046 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
15047 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
15048 /// vector, form the analogous 128-bit 8-element Mask.
15049 static SDValue lowerV8I16GeneralSingleInputShuffle(
15050     const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
15051     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15052   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
15053   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
15054 
15055   assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
15056   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
15057   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
15058 
15059   // Attempt to directly match PSHUFLW or PSHUFHW.
15060   if (isUndefOrInRange(LoMask, 0, 4) &&
15061       isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
15062     return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15063                        getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
15064   }
15065   if (isUndefOrInRange(HiMask, 4, 8) &&
15066       isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
15067     for (int i = 0; i != 4; ++i)
15068       HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
15069     return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15070                        getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
15071   }
15072 
15073   SmallVector<int, 4> LoInputs;
15074   copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
15075   array_pod_sort(LoInputs.begin(), LoInputs.end());
15076   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
15077   SmallVector<int, 4> HiInputs;
15078   copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
15079   array_pod_sort(HiInputs.begin(), HiInputs.end());
15080   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
15081   int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
15082   int NumHToL = LoInputs.size() - NumLToL;
15083   int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
15084   int NumHToH = HiInputs.size() - NumLToH;
15085   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
15086   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
15087   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
15088   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
15089 
15090   // If we are shuffling values from one half - check how many different DWORD
15091   // pairs we need to create. If only 1 or 2 then we can perform this as a
15092   // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
15093   auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
15094                                ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
15095     V = DAG.getNode(ShufWOp, DL, VT, V,
15096                     getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
15097     V = DAG.getBitcast(PSHUFDVT, V);
15098     V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
15099                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
15100     return DAG.getBitcast(VT, V);
15101   };
15102 
15103   if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
15104     int PSHUFDMask[4] = { -1, -1, -1, -1 };
15105     SmallVector<std::pair<int, int>, 4> DWordPairs;
15106     int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
15107 
15108     // Collect the different DWORD pairs.
15109     for (int DWord = 0; DWord != 4; ++DWord) {
15110       int M0 = Mask[2 * DWord + 0];
15111       int M1 = Mask[2 * DWord + 1];
15112       M0 = (M0 >= 0 ? M0 % 4 : M0);
15113       M1 = (M1 >= 0 ? M1 % 4 : M1);
15114       if (M0 < 0 && M1 < 0)
15115         continue;
15116 
15117       bool Match = false;
15118       for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
15119         auto &DWordPair = DWordPairs[j];
15120         if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
15121             (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
15122           DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
15123           DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
15124           PSHUFDMask[DWord] = DOffset + j;
15125           Match = true;
15126           break;
15127         }
15128       }
15129       if (!Match) {
15130         PSHUFDMask[DWord] = DOffset + DWordPairs.size();
15131         DWordPairs.push_back(std::make_pair(M0, M1));
15132       }
15133     }
15134 
15135     if (DWordPairs.size() <= 2) {
15136       DWordPairs.resize(2, std::make_pair(-1, -1));
15137       int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
15138                               DWordPairs[1].first, DWordPairs[1].second};
15139       if ((NumHToL + NumHToH) == 0)
15140         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
15141       if ((NumLToL + NumLToH) == 0)
15142         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
15143     }
15144   }
15145 
15146   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
15147   // such inputs we can swap two of the dwords across the half mark and end up
15148   // with <=2 inputs to each half in each half. Once there, we can fall through
15149   // to the generic code below. For example:
15150   //
15151   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
15152   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
15153   //
15154   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
15155   // and an existing 2-into-2 on the other half. In this case we may have to
15156   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
15157   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
15158   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
15159   // because any other situation (including a 3-into-1 or 1-into-3 in the other
15160   // half than the one we target for fixing) will be fixed when we re-enter this
15161   // path. We will also combine away any sequence of PSHUFD instructions that
15162   // result into a single instruction. Here is an example of the tricky case:
15163   //
15164   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
15165   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
15166   //
15167   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
15168   //
15169   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
15170   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
15171   //
15172   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
15173   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
15174   //
15175   // The result is fine to be handled by the generic logic.
15176   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
15177                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
15178                           int AOffset, int BOffset) {
15179     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
15180            "Must call this with A having 3 or 1 inputs from the A half.");
15181     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
15182            "Must call this with B having 1 or 3 inputs from the B half.");
15183     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
15184            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
15185 
15186     bool ThreeAInputs = AToAInputs.size() == 3;
15187 
15188     // Compute the index of dword with only one word among the three inputs in
15189     // a half by taking the sum of the half with three inputs and subtracting
15190     // the sum of the actual three inputs. The difference is the remaining
15191     // slot.
15192     int ADWord = 0, BDWord = 0;
15193     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
15194     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
15195     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
15196     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
15197     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
15198     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
15199     int TripleNonInputIdx =
15200         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
15201     TripleDWord = TripleNonInputIdx / 2;
15202 
15203     // We use xor with one to compute the adjacent DWord to whichever one the
15204     // OneInput is in.
15205     OneInputDWord = (OneInput / 2) ^ 1;
15206 
15207     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
15208     // and BToA inputs. If there is also such a problem with the BToB and AToB
15209     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
15210     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
15211     // is essential that we don't *create* a 3<-1 as then we might oscillate.
15212     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
15213       // Compute how many inputs will be flipped by swapping these DWords. We
15214       // need
15215       // to balance this to ensure we don't form a 3-1 shuffle in the other
15216       // half.
15217       int NumFlippedAToBInputs = llvm::count(AToBInputs, 2 * ADWord) +
15218                                  llvm::count(AToBInputs, 2 * ADWord + 1);
15219       int NumFlippedBToBInputs = llvm::count(BToBInputs, 2 * BDWord) +
15220                                  llvm::count(BToBInputs, 2 * BDWord + 1);
15221       if ((NumFlippedAToBInputs == 1 &&
15222            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
15223           (NumFlippedBToBInputs == 1 &&
15224            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
15225         // We choose whether to fix the A half or B half based on whether that
15226         // half has zero flipped inputs. At zero, we may not be able to fix it
15227         // with that half. We also bias towards fixing the B half because that
15228         // will more commonly be the high half, and we have to bias one way.
15229         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
15230                                                        ArrayRef<int> Inputs) {
15231           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
15232           bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
15233           // Determine whether the free index is in the flipped dword or the
15234           // unflipped dword based on where the pinned index is. We use this bit
15235           // in an xor to conditionally select the adjacent dword.
15236           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
15237           bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
15238           if (IsFixIdxInput == IsFixFreeIdxInput)
15239             FixFreeIdx += 1;
15240           IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
15241           assert(IsFixIdxInput != IsFixFreeIdxInput &&
15242                  "We need to be changing the number of flipped inputs!");
15243           int PSHUFHalfMask[] = {0, 1, 2, 3};
15244           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
15245           V = DAG.getNode(
15246               FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
15247               MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
15248               getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
15249 
15250           for (int &M : Mask)
15251             if (M >= 0 && M == FixIdx)
15252               M = FixFreeIdx;
15253             else if (M >= 0 && M == FixFreeIdx)
15254               M = FixIdx;
15255         };
15256         if (NumFlippedBToBInputs != 0) {
15257           int BPinnedIdx =
15258               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
15259           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
15260         } else {
15261           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
15262           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
15263           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
15264         }
15265       }
15266     }
15267 
15268     int PSHUFDMask[] = {0, 1, 2, 3};
15269     PSHUFDMask[ADWord] = BDWord;
15270     PSHUFDMask[BDWord] = ADWord;
15271     V = DAG.getBitcast(
15272         VT,
15273         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
15274                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15275 
15276     // Adjust the mask to match the new locations of A and B.
15277     for (int &M : Mask)
15278       if (M >= 0 && M/2 == ADWord)
15279         M = 2 * BDWord + M % 2;
15280       else if (M >= 0 && M/2 == BDWord)
15281         M = 2 * ADWord + M % 2;
15282 
15283     // Recurse back into this routine to re-compute state now that this isn't
15284     // a 3 and 1 problem.
15285     return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
15286   };
15287   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
15288     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
15289   if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
15290     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
15291 
15292   // At this point there are at most two inputs to the low and high halves from
15293   // each half. That means the inputs can always be grouped into dwords and
15294   // those dwords can then be moved to the correct half with a dword shuffle.
15295   // We use at most one low and one high word shuffle to collect these paired
15296   // inputs into dwords, and finally a dword shuffle to place them.
15297   int PSHUFLMask[4] = {-1, -1, -1, -1};
15298   int PSHUFHMask[4] = {-1, -1, -1, -1};
15299   int PSHUFDMask[4] = {-1, -1, -1, -1};
15300 
15301   // First fix the masks for all the inputs that are staying in their
15302   // original halves. This will then dictate the targets of the cross-half
15303   // shuffles.
15304   auto fixInPlaceInputs =
15305       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
15306                     MutableArrayRef<int> SourceHalfMask,
15307                     MutableArrayRef<int> HalfMask, int HalfOffset) {
15308     if (InPlaceInputs.empty())
15309       return;
15310     if (InPlaceInputs.size() == 1) {
15311       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
15312           InPlaceInputs[0] - HalfOffset;
15313       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
15314       return;
15315     }
15316     if (IncomingInputs.empty()) {
15317       // Just fix all of the in place inputs.
15318       for (int Input : InPlaceInputs) {
15319         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
15320         PSHUFDMask[Input / 2] = Input / 2;
15321       }
15322       return;
15323     }
15324 
15325     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
15326     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
15327         InPlaceInputs[0] - HalfOffset;
15328     // Put the second input next to the first so that they are packed into
15329     // a dword. We find the adjacent index by toggling the low bit.
15330     int AdjIndex = InPlaceInputs[0] ^ 1;
15331     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
15332     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
15333     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
15334   };
15335   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
15336   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
15337 
15338   // Now gather the cross-half inputs and place them into a free dword of
15339   // their target half.
15340   // FIXME: This operation could almost certainly be simplified dramatically to
15341   // look more like the 3-1 fixing operation.
15342   auto moveInputsToRightHalf = [&PSHUFDMask](
15343       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
15344       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
15345       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
15346       int DestOffset) {
15347     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
15348       return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
15349     };
15350     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
15351                                                int Word) {
15352       int LowWord = Word & ~1;
15353       int HighWord = Word | 1;
15354       return isWordClobbered(SourceHalfMask, LowWord) ||
15355              isWordClobbered(SourceHalfMask, HighWord);
15356     };
15357 
15358     if (IncomingInputs.empty())
15359       return;
15360 
15361     if (ExistingInputs.empty()) {
15362       // Map any dwords with inputs from them into the right half.
15363       for (int Input : IncomingInputs) {
15364         // If the source half mask maps over the inputs, turn those into
15365         // swaps and use the swapped lane.
15366         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
15367           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
15368             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
15369                 Input - SourceOffset;
15370             // We have to swap the uses in our half mask in one sweep.
15371             for (int &M : HalfMask)
15372               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
15373                 M = Input;
15374               else if (M == Input)
15375                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
15376           } else {
15377             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
15378                        Input - SourceOffset &&
15379                    "Previous placement doesn't match!");
15380           }
15381           // Note that this correctly re-maps both when we do a swap and when
15382           // we observe the other side of the swap above. We rely on that to
15383           // avoid swapping the members of the input list directly.
15384           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
15385         }
15386 
15387         // Map the input's dword into the correct half.
15388         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
15389           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
15390         else
15391           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
15392                      Input / 2 &&
15393                  "Previous placement doesn't match!");
15394       }
15395 
15396       // And just directly shift any other-half mask elements to be same-half
15397       // as we will have mirrored the dword containing the element into the
15398       // same position within that half.
15399       for (int &M : HalfMask)
15400         if (M >= SourceOffset && M < SourceOffset + 4) {
15401           M = M - SourceOffset + DestOffset;
15402           assert(M >= 0 && "This should never wrap below zero!");
15403         }
15404       return;
15405     }
15406 
15407     // Ensure we have the input in a viable dword of its current half. This
15408     // is particularly tricky because the original position may be clobbered
15409     // by inputs being moved and *staying* in that half.
15410     if (IncomingInputs.size() == 1) {
15411       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
15412         int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
15413                          SourceOffset;
15414         SourceHalfMask[InputFixed - SourceOffset] =
15415             IncomingInputs[0] - SourceOffset;
15416         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
15417                      InputFixed);
15418         IncomingInputs[0] = InputFixed;
15419       }
15420     } else if (IncomingInputs.size() == 2) {
15421       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
15422           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
15423         // We have two non-adjacent or clobbered inputs we need to extract from
15424         // the source half. To do this, we need to map them into some adjacent
15425         // dword slot in the source mask.
15426         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
15427                               IncomingInputs[1] - SourceOffset};
15428 
15429         // If there is a free slot in the source half mask adjacent to one of
15430         // the inputs, place the other input in it. We use (Index XOR 1) to
15431         // compute an adjacent index.
15432         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
15433             SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
15434           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
15435           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
15436           InputsFixed[1] = InputsFixed[0] ^ 1;
15437         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
15438                    SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
15439           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
15440           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
15441           InputsFixed[0] = InputsFixed[1] ^ 1;
15442         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
15443                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
15444           // The two inputs are in the same DWord but it is clobbered and the
15445           // adjacent DWord isn't used at all. Move both inputs to the free
15446           // slot.
15447           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
15448           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
15449           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
15450           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
15451         } else {
15452           // The only way we hit this point is if there is no clobbering
15453           // (because there are no off-half inputs to this half) and there is no
15454           // free slot adjacent to one of the inputs. In this case, we have to
15455           // swap an input with a non-input.
15456           for (int i = 0; i < 4; ++i)
15457             assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
15458                    "We can't handle any clobbers here!");
15459           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
15460                  "Cannot have adjacent inputs here!");
15461 
15462           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
15463           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
15464 
15465           // We also have to update the final source mask in this case because
15466           // it may need to undo the above swap.
15467           for (int &M : FinalSourceHalfMask)
15468             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
15469               M = InputsFixed[1] + SourceOffset;
15470             else if (M == InputsFixed[1] + SourceOffset)
15471               M = (InputsFixed[0] ^ 1) + SourceOffset;
15472 
15473           InputsFixed[1] = InputsFixed[0] ^ 1;
15474         }
15475 
15476         // Point everything at the fixed inputs.
15477         for (int &M : HalfMask)
15478           if (M == IncomingInputs[0])
15479             M = InputsFixed[0] + SourceOffset;
15480           else if (M == IncomingInputs[1])
15481             M = InputsFixed[1] + SourceOffset;
15482 
15483         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
15484         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
15485       }
15486     } else {
15487       llvm_unreachable("Unhandled input size!");
15488     }
15489 
15490     // Now hoist the DWord down to the right half.
15491     int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
15492     assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
15493     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
15494     for (int &M : HalfMask)
15495       for (int Input : IncomingInputs)
15496         if (M == Input)
15497           M = FreeDWord * 2 + Input % 2;
15498   };
15499   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
15500                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
15501   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
15502                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
15503 
15504   // Now enact all the shuffles we've computed to move the inputs into their
15505   // target half.
15506   if (!isNoopShuffleMask(PSHUFLMask))
15507     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15508                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
15509   if (!isNoopShuffleMask(PSHUFHMask))
15510     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15511                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
15512   if (!isNoopShuffleMask(PSHUFDMask))
15513     V = DAG.getBitcast(
15514         VT,
15515         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
15516                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15517 
15518   // At this point, each half should contain all its inputs, and we can then
15519   // just shuffle them into their final position.
15520   assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
15521          "Failed to lift all the high half inputs to the low mask!");
15522   assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
15523          "Failed to lift all the low half inputs to the high mask!");
15524 
15525   // Do a half shuffle for the low mask.
15526   if (!isNoopShuffleMask(LoMask))
15527     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15528                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
15529 
15530   // Do a half shuffle with the high mask after shifting its values down.
15531   for (int &M : HiMask)
15532     if (M >= 0)
15533       M -= 4;
15534   if (!isNoopShuffleMask(HiMask))
15535     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15536                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
15537 
15538   return V;
15539 }
15540 
15541 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
15542 /// blend if only one input is used.
15543 static SDValue lowerShuffleAsBlendOfPSHUFBs(
15544     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15545     const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
15546   assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
15547          "Lane crossing shuffle masks not supported");
15548 
15549   int NumBytes = VT.getSizeInBits() / 8;
15550   int Size = Mask.size();
15551   int Scale = NumBytes / Size;
15552 
15553   SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
15554   SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
15555   V1InUse = false;
15556   V2InUse = false;
15557 
15558   for (int i = 0; i < NumBytes; ++i) {
15559     int M = Mask[i / Scale];
15560     if (M < 0)
15561       continue;
15562 
15563     const int ZeroMask = 0x80;
15564     int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
15565     int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
15566     if (Zeroable[i / Scale])
15567       V1Idx = V2Idx = ZeroMask;
15568 
15569     V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
15570     V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
15571     V1InUse |= (ZeroMask != V1Idx);
15572     V2InUse |= (ZeroMask != V2Idx);
15573   }
15574 
15575   MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
15576   if (V1InUse)
15577     V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
15578                      DAG.getBuildVector(ShufVT, DL, V1Mask));
15579   if (V2InUse)
15580     V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
15581                      DAG.getBuildVector(ShufVT, DL, V2Mask));
15582 
15583   // If we need shuffled inputs from both, blend the two.
15584   SDValue V;
15585   if (V1InUse && V2InUse)
15586     V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
15587   else
15588     V = V1InUse ? V1 : V2;
15589 
15590   // Cast the result back to the correct type.
15591   return DAG.getBitcast(VT, V);
15592 }
15593 
15594 /// Generic lowering of 8-lane i16 shuffles.
15595 ///
15596 /// This handles both single-input shuffles and combined shuffle/blends with
15597 /// two inputs. The single input shuffles are immediately delegated to
15598 /// a dedicated lowering routine.
15599 ///
15600 /// The blends are lowered in one of three fundamental ways. If there are few
15601 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
15602 /// of the input is significantly cheaper when lowered as an interleaving of
15603 /// the two inputs, try to interleave them. Otherwise, blend the low and high
15604 /// halves of the inputs separately (making them have relatively few inputs)
15605 /// and then concatenate them.
15606 static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15607                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15608                                  const X86Subtarget &Subtarget,
15609                                  SelectionDAG &DAG) {
15610   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
15611   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
15612   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
15613 
15614   // Whenever we can lower this as a zext, that instruction is strictly faster
15615   // than any alternative.
15616   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
15617                                                    Zeroable, Subtarget, DAG))
15618     return ZExt;
15619 
15620   // Try to use lower using a truncation.
15621   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
15622                                         Subtarget, DAG))
15623     return V;
15624 
15625   int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
15626 
15627   if (NumV2Inputs == 0) {
15628     // Try to use shift instructions.
15629     if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
15630                                             Zeroable, Subtarget, DAG))
15631       return Shift;
15632 
15633     // Check for being able to broadcast a single element.
15634     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
15635                                                     Mask, Subtarget, DAG))
15636       return Broadcast;
15637 
15638     // Try to use bit rotation instructions.
15639     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
15640                                                  Subtarget, DAG))
15641       return Rotate;
15642 
15643     // Use dedicated unpack instructions for masks that match their pattern.
15644     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
15645       return V;
15646 
15647     // Use dedicated pack instructions for masks that match their pattern.
15648     if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
15649                                          Subtarget))
15650       return V;
15651 
15652     // Try to use byte rotation instructions.
15653     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
15654                                                   Subtarget, DAG))
15655       return Rotate;
15656 
15657     // Make a copy of the mask so it can be modified.
15658     SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
15659     return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
15660                                                Subtarget, DAG);
15661   }
15662 
15663   assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
15664          "All single-input shuffles should be canonicalized to be V1-input "
15665          "shuffles.");
15666 
15667   // Try to use shift instructions.
15668   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
15669                                           Zeroable, Subtarget, DAG))
15670     return Shift;
15671 
15672   // See if we can use SSE4A Extraction / Insertion.
15673   if (Subtarget.hasSSE4A())
15674     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
15675                                           Zeroable, DAG))
15676       return V;
15677 
15678   // There are special ways we can lower some single-element blends.
15679   if (NumV2Inputs == 1)
15680     if (SDValue V = lowerShuffleAsElementInsertion(
15681             DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
15682       return V;
15683 
15684   // We have different paths for blend lowering, but they all must use the
15685   // *exact* same predicate.
15686   bool IsBlendSupported = Subtarget.hasSSE41();
15687   if (IsBlendSupported)
15688     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
15689                                             Zeroable, Subtarget, DAG))
15690       return Blend;
15691 
15692   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
15693                                              Zeroable, Subtarget, DAG))
15694     return Masked;
15695 
15696   // Use dedicated unpack instructions for masks that match their pattern.
15697   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
15698     return V;
15699 
15700   // Use dedicated pack instructions for masks that match their pattern.
15701   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
15702                                        Subtarget))
15703     return V;
15704 
15705   // Try to use lower using a truncation.
15706   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
15707                                        Subtarget, DAG))
15708     return V;
15709 
15710   // Try to use byte rotation instructions.
15711   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
15712                                                 Subtarget, DAG))
15713     return Rotate;
15714 
15715   if (SDValue BitBlend =
15716           lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
15717     return BitBlend;
15718 
15719   // Try to use byte shift instructions to mask.
15720   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
15721                                               Zeroable, Subtarget, DAG))
15722     return V;
15723 
15724   // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
15725   // We could use SIGN_EXTEND_INREG+PACKSSDW for older targets but this seems to
15726   // be slower than a PSHUFLW+PSHUFHW+PSHUFD chain.
15727   int NumEvenDrops = canLowerByDroppingEvenElements(Mask, false);
15728   if ((NumEvenDrops == 1 || NumEvenDrops == 2) && Subtarget.hasSSE41() &&
15729       !Subtarget.hasVLX()) {
15730     // Check if this is part of a 256-bit vector truncation.
15731     if (NumEvenDrops == 2 && Subtarget.hasAVX2() &&
15732         peekThroughBitcasts(V1).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15733         peekThroughBitcasts(V2).getOpcode() == ISD::EXTRACT_SUBVECTOR) {
15734       SDValue V1V2 = concatSubVectors(V1, V2, DAG, DL);
15735       V1V2 = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1V2,
15736                          getZeroVector(MVT::v16i16, Subtarget, DAG, DL),
15737                          DAG.getTargetConstant(0xEE, DL, MVT::i8));
15738       V1V2 = DAG.getBitcast(MVT::v8i32, V1V2);
15739       V1 = extract128BitVector(V1V2, 0, DAG, DL);
15740       V2 = extract128BitVector(V1V2, 4, DAG, DL);
15741     } else {
15742       SmallVector<SDValue> DWordClearOps(4, DAG.getConstant(0, DL, MVT::i32));
15743       for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
15744         DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
15745       SDValue DWordClearMask =
15746           DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
15747       V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
15748                        DWordClearMask);
15749       V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
15750                        DWordClearMask);
15751     }
15752     // Now pack things back together.
15753     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, V1, V2);
15754     if (NumEvenDrops == 2) {
15755       Result = DAG.getBitcast(MVT::v4i32, Result);
15756       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, Result, Result);
15757     }
15758     return Result;
15759   }
15760 
15761   // Try to lower by permuting the inputs into an unpack instruction.
15762   if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
15763                                                       Mask, Subtarget, DAG))
15764     return Unpack;
15765 
15766   // If we can't directly blend but can use PSHUFB, that will be better as it
15767   // can both shuffle and set up the inefficient blend.
15768   if (!IsBlendSupported && Subtarget.hasSSSE3()) {
15769     bool V1InUse, V2InUse;
15770     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
15771                                         Zeroable, DAG, V1InUse, V2InUse);
15772   }
15773 
15774   // We can always bit-blend if we have to so the fallback strategy is to
15775   // decompose into single-input permutes and blends/unpacks.
15776   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2,
15777                                               Mask, Subtarget, DAG);
15778 }
15779 
15780 /// Lower 8-lane 16-bit floating point shuffles.
15781 static SDValue lowerV8F16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15782                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15783                                  const X86Subtarget &Subtarget,
15784                                  SelectionDAG &DAG) {
15785   assert(V1.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
15786   assert(V2.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
15787   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
15788   int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
15789 
15790   if (NumV2Elements == 0) {
15791     // Check for being able to broadcast a single element.
15792     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f16, V1, V2,
15793                                                     Mask, Subtarget, DAG))
15794       return Broadcast;
15795   }
15796   if (NumV2Elements == 1 && Mask[0] >= 8)
15797     if (SDValue V = lowerShuffleAsElementInsertion(DL, MVT::v8f16, V1, V2, Mask,
15798                                                    Zeroable, Subtarget, DAG))
15799       return V;
15800 
15801   V1 = DAG.getBitcast(MVT::v8i16, V1);
15802   V2 = DAG.getBitcast(MVT::v8i16, V2);
15803   return DAG.getBitcast(MVT::v8f16,
15804                         DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
15805 }
15806 
15807 // Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
15808 // sub-512-bit shuffles are padded to 512-bits for the shuffle and then
15809 // the active subvector is extracted.
15810 static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
15811                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
15812                                      const X86Subtarget &Subtarget,
15813                                      SelectionDAG &DAG) {
15814   MVT MaskVT = VT.changeTypeToInteger();
15815   SDValue MaskNode;
15816   MVT ShuffleVT = VT;
15817   if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
15818     V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
15819     V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
15820     ShuffleVT = V1.getSimpleValueType();
15821 
15822     // Adjust mask to correct indices for the second input.
15823     int NumElts = VT.getVectorNumElements();
15824     unsigned Scale = 512 / VT.getSizeInBits();
15825     SmallVector<int, 32> AdjustedMask(Mask.begin(), Mask.end());
15826     for (int &M : AdjustedMask)
15827       if (NumElts <= M)
15828         M += (Scale - 1) * NumElts;
15829     MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
15830     MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
15831   } else {
15832     MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
15833   }
15834 
15835   SDValue Result;
15836   if (V2.isUndef())
15837     Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
15838   else
15839     Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
15840 
15841   if (VT != ShuffleVT)
15842     Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
15843 
15844   return Result;
15845 }
15846 
15847 /// Generic lowering of v16i8 shuffles.
15848 ///
15849 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
15850 /// detect any complexity reducing interleaving. If that doesn't help, it uses
15851 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
15852 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
15853 /// back together.
15854 static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15855                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15856                                  const X86Subtarget &Subtarget,
15857                                  SelectionDAG &DAG) {
15858   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15859   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15860   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
15861 
15862   // Try to use shift instructions.
15863   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
15864                                           Zeroable, Subtarget, DAG))
15865     return Shift;
15866 
15867   // Try to use byte rotation instructions.
15868   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
15869                                                 Subtarget, DAG))
15870     return Rotate;
15871 
15872   // Use dedicated pack instructions for masks that match their pattern.
15873   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
15874                                        Subtarget))
15875     return V;
15876 
15877   // Try to use a zext lowering.
15878   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
15879                                                    Zeroable, Subtarget, DAG))
15880     return ZExt;
15881 
15882   // Try to use lower using a truncation.
15883   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15884                                         Subtarget, DAG))
15885     return V;
15886 
15887   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15888                                        Subtarget, DAG))
15889     return V;
15890 
15891   // See if we can use SSE4A Extraction / Insertion.
15892   if (Subtarget.hasSSE4A())
15893     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
15894                                           Zeroable, DAG))
15895       return V;
15896 
15897   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
15898 
15899   // For single-input shuffles, there are some nicer lowering tricks we can use.
15900   if (NumV2Elements == 0) {
15901     // Check for being able to broadcast a single element.
15902     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
15903                                                     Mask, Subtarget, DAG))
15904       return Broadcast;
15905 
15906     // Try to use bit rotation instructions.
15907     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
15908                                                  Subtarget, DAG))
15909       return Rotate;
15910 
15911     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
15912       return V;
15913 
15914     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
15915     // Notably, this handles splat and partial-splat shuffles more efficiently.
15916     // However, it only makes sense if the pre-duplication shuffle simplifies
15917     // things significantly. Currently, this means we need to be able to
15918     // express the pre-duplication shuffle as an i16 shuffle.
15919     //
15920     // FIXME: We should check for other patterns which can be widened into an
15921     // i16 shuffle as well.
15922     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
15923       for (int i = 0; i < 16; i += 2)
15924         if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
15925           return false;
15926 
15927       return true;
15928     };
15929     auto tryToWidenViaDuplication = [&]() -> SDValue {
15930       if (!canWidenViaDuplication(Mask))
15931         return SDValue();
15932       SmallVector<int, 4> LoInputs;
15933       copy_if(Mask, std::back_inserter(LoInputs),
15934               [](int M) { return M >= 0 && M < 8; });
15935       array_pod_sort(LoInputs.begin(), LoInputs.end());
15936       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
15937                      LoInputs.end());
15938       SmallVector<int, 4> HiInputs;
15939       copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
15940       array_pod_sort(HiInputs.begin(), HiInputs.end());
15941       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
15942                      HiInputs.end());
15943 
15944       bool TargetLo = LoInputs.size() >= HiInputs.size();
15945       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
15946       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
15947 
15948       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
15949       SmallDenseMap<int, int, 8> LaneMap;
15950       for (int I : InPlaceInputs) {
15951         PreDupI16Shuffle[I/2] = I/2;
15952         LaneMap[I] = I;
15953       }
15954       int j = TargetLo ? 0 : 4, je = j + 4;
15955       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
15956         // Check if j is already a shuffle of this input. This happens when
15957         // there are two adjacent bytes after we move the low one.
15958         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
15959           // If we haven't yet mapped the input, search for a slot into which
15960           // we can map it.
15961           while (j < je && PreDupI16Shuffle[j] >= 0)
15962             ++j;
15963 
15964           if (j == je)
15965             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
15966             return SDValue();
15967 
15968           // Map this input with the i16 shuffle.
15969           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
15970         }
15971 
15972         // Update the lane map based on the mapping we ended up with.
15973         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
15974       }
15975       V1 = DAG.getBitcast(
15976           MVT::v16i8,
15977           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15978                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
15979 
15980       // Unpack the bytes to form the i16s that will be shuffled into place.
15981       bool EvenInUse = false, OddInUse = false;
15982       for (int i = 0; i < 16; i += 2) {
15983         EvenInUse |= (Mask[i + 0] >= 0);
15984         OddInUse |= (Mask[i + 1] >= 0);
15985         if (EvenInUse && OddInUse)
15986           break;
15987       }
15988       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
15989                        MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
15990                        OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
15991 
15992       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
15993       for (int i = 0; i < 16; ++i)
15994         if (Mask[i] >= 0) {
15995           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
15996           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
15997           if (PostDupI16Shuffle[i / 2] < 0)
15998             PostDupI16Shuffle[i / 2] = MappedMask;
15999           else
16000             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
16001                    "Conflicting entries in the original shuffle!");
16002         }
16003       return DAG.getBitcast(
16004           MVT::v16i8,
16005           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
16006                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
16007     };
16008     if (SDValue V = tryToWidenViaDuplication())
16009       return V;
16010   }
16011 
16012   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
16013                                              Zeroable, Subtarget, DAG))
16014     return Masked;
16015 
16016   // Use dedicated unpack instructions for masks that match their pattern.
16017   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
16018     return V;
16019 
16020   // Try to use byte shift instructions to mask.
16021   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
16022                                               Zeroable, Subtarget, DAG))
16023     return V;
16024 
16025   // Check for compaction patterns.
16026   bool IsSingleInput = V2.isUndef();
16027   int NumEvenDrops = canLowerByDroppingEvenElements(Mask, IsSingleInput);
16028 
16029   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
16030   // with PSHUFB. It is important to do this before we attempt to generate any
16031   // blends but after all of the single-input lowerings. If the single input
16032   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
16033   // want to preserve that and we can DAG combine any longer sequences into
16034   // a PSHUFB in the end. But once we start blending from multiple inputs,
16035   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
16036   // and there are *very* few patterns that would actually be faster than the
16037   // PSHUFB approach because of its ability to zero lanes.
16038   //
16039   // If the mask is a binary compaction, we can more efficiently perform this
16040   // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
16041   //
16042   // FIXME: The only exceptions to the above are blends which are exact
16043   // interleavings with direct instructions supporting them. We currently don't
16044   // handle those well here.
16045   if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
16046     bool V1InUse = false;
16047     bool V2InUse = false;
16048 
16049     SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
16050         DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
16051 
16052     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
16053     // do so. This avoids using them to handle blends-with-zero which is
16054     // important as a single pshufb is significantly faster for that.
16055     if (V1InUse && V2InUse) {
16056       if (Subtarget.hasSSE41())
16057         if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
16058                                                 Zeroable, Subtarget, DAG))
16059           return Blend;
16060 
16061       // We can use an unpack to do the blending rather than an or in some
16062       // cases. Even though the or may be (very minorly) more efficient, we
16063       // preference this lowering because there are common cases where part of
16064       // the complexity of the shuffles goes away when we do the final blend as
16065       // an unpack.
16066       // FIXME: It might be worth trying to detect if the unpack-feeding
16067       // shuffles will both be pshufb, in which case we shouldn't bother with
16068       // this.
16069       if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
16070               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
16071         return Unpack;
16072 
16073       // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
16074       if (Subtarget.hasVBMI())
16075         return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
16076                                      DAG);
16077 
16078       // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
16079       if (Subtarget.hasXOP()) {
16080         SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
16081         return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
16082       }
16083 
16084       // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
16085       // PALIGNR will be cheaper than the second PSHUFB+OR.
16086       if (SDValue V = lowerShuffleAsByteRotateAndPermute(
16087               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
16088         return V;
16089     }
16090 
16091     return PSHUFB;
16092   }
16093 
16094   // There are special ways we can lower some single-element blends.
16095   if (NumV2Elements == 1)
16096     if (SDValue V = lowerShuffleAsElementInsertion(
16097             DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
16098       return V;
16099 
16100   if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
16101     return Blend;
16102 
16103   // Check whether a compaction lowering can be done. This handles shuffles
16104   // which take every Nth element for some even N. See the helper function for
16105   // details.
16106   //
16107   // We special case these as they can be particularly efficiently handled with
16108   // the PACKUSB instruction on x86 and they show up in common patterns of
16109   // rearranging bytes to truncate wide elements.
16110   if (NumEvenDrops) {
16111     // NumEvenDrops is the power of two stride of the elements. Another way of
16112     // thinking about it is that we need to drop the even elements this many
16113     // times to get the original input.
16114 
16115     // First we need to zero all the dropped bytes.
16116     assert(NumEvenDrops <= 3 &&
16117            "No support for dropping even elements more than 3 times.");
16118     SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
16119     for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
16120       WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
16121     SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
16122     V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
16123                      WordClearMask);
16124     if (!IsSingleInput)
16125       V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
16126                        WordClearMask);
16127 
16128     // Now pack things back together.
16129     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
16130                                  IsSingleInput ? V1 : V2);
16131     for (int i = 1; i < NumEvenDrops; ++i) {
16132       Result = DAG.getBitcast(MVT::v8i16, Result);
16133       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
16134     }
16135     return Result;
16136   }
16137 
16138   // Handle multi-input cases by blending/unpacking single-input shuffles.
16139   if (NumV2Elements > 0)
16140     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
16141                                                 Subtarget, DAG);
16142 
16143   // The fallback path for single-input shuffles widens this into two v8i16
16144   // vectors with unpacks, shuffles those, and then pulls them back together
16145   // with a pack.
16146   SDValue V = V1;
16147 
16148   std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
16149   std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
16150   for (int i = 0; i < 16; ++i)
16151     if (Mask[i] >= 0)
16152       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
16153 
16154   SDValue VLoHalf, VHiHalf;
16155   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
16156   // them out and avoid using UNPCK{L,H} to extract the elements of V as
16157   // i16s.
16158   if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
16159       none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
16160     // Use a mask to drop the high bytes.
16161     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
16162     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
16163                           DAG.getConstant(0x00FF, DL, MVT::v8i16));
16164 
16165     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
16166     VHiHalf = DAG.getUNDEF(MVT::v8i16);
16167 
16168     // Squash the masks to point directly into VLoHalf.
16169     for (int &M : LoBlendMask)
16170       if (M >= 0)
16171         M /= 2;
16172     for (int &M : HiBlendMask)
16173       if (M >= 0)
16174         M /= 2;
16175   } else {
16176     // Otherwise just unpack the low half of V into VLoHalf and the high half into
16177     // VHiHalf so that we can blend them as i16s.
16178     SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
16179 
16180     VLoHalf = DAG.getBitcast(
16181         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
16182     VHiHalf = DAG.getBitcast(
16183         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
16184   }
16185 
16186   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
16187   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
16188 
16189   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
16190 }
16191 
16192 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
16193 ///
16194 /// This routine breaks down the specific type of 128-bit shuffle and
16195 /// dispatches to the lowering routines accordingly.
16196 static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
16197                                   MVT VT, SDValue V1, SDValue V2,
16198                                   const APInt &Zeroable,
16199                                   const X86Subtarget &Subtarget,
16200                                   SelectionDAG &DAG) {
16201   switch (VT.SimpleTy) {
16202   case MVT::v2i64:
16203     return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16204   case MVT::v2f64:
16205     return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16206   case MVT::v4i32:
16207     return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16208   case MVT::v4f32:
16209     return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16210   case MVT::v8i16:
16211     return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16212   case MVT::v8f16:
16213     return lowerV8F16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16214   case MVT::v16i8:
16215     return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16216 
16217   default:
16218     llvm_unreachable("Unimplemented!");
16219   }
16220 }
16221 
16222 /// Generic routine to split vector shuffle into half-sized shuffles.
16223 ///
16224 /// This routine just extracts two subvectors, shuffles them independently, and
16225 /// then concatenates them back together. This should work effectively with all
16226 /// AVX vector shuffle types.
16227 static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
16228                                     SDValue V2, ArrayRef<int> Mask,
16229                                     SelectionDAG &DAG) {
16230   assert(VT.getSizeInBits() >= 256 &&
16231          "Only for 256-bit or wider vector shuffles!");
16232   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
16233   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
16234 
16235   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
16236   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
16237 
16238   int NumElements = VT.getVectorNumElements();
16239   int SplitNumElements = NumElements / 2;
16240   MVT ScalarVT = VT.getVectorElementType();
16241   MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
16242 
16243   // Use splitVector/extractSubVector so that split build-vectors just build two
16244   // narrower build vectors. This helps shuffling with splats and zeros.
16245   auto SplitVector = [&](SDValue V) {
16246     SDValue LoV, HiV;
16247     std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
16248     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
16249                           DAG.getBitcast(SplitVT, HiV));
16250   };
16251 
16252   SDValue LoV1, HiV1, LoV2, HiV2;
16253   std::tie(LoV1, HiV1) = SplitVector(V1);
16254   std::tie(LoV2, HiV2) = SplitVector(V2);
16255 
16256   // Now create two 4-way blends of these half-width vectors.
16257   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
16258     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
16259     SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
16260     SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
16261     SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
16262     for (int i = 0; i < SplitNumElements; ++i) {
16263       int M = HalfMask[i];
16264       if (M >= NumElements) {
16265         if (M >= NumElements + SplitNumElements)
16266           UseHiV2 = true;
16267         else
16268           UseLoV2 = true;
16269         V2BlendMask[i] = M - NumElements;
16270         BlendMask[i] = SplitNumElements + i;
16271       } else if (M >= 0) {
16272         if (M >= SplitNumElements)
16273           UseHiV1 = true;
16274         else
16275           UseLoV1 = true;
16276         V1BlendMask[i] = M;
16277         BlendMask[i] = i;
16278       }
16279     }
16280 
16281     // Because the lowering happens after all combining takes place, we need to
16282     // manually combine these blend masks as much as possible so that we create
16283     // a minimal number of high-level vector shuffle nodes.
16284 
16285     // First try just blending the halves of V1 or V2.
16286     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
16287       return DAG.getUNDEF(SplitVT);
16288     if (!UseLoV2 && !UseHiV2)
16289       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
16290     if (!UseLoV1 && !UseHiV1)
16291       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
16292 
16293     SDValue V1Blend, V2Blend;
16294     if (UseLoV1 && UseHiV1) {
16295       V1Blend =
16296         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
16297     } else {
16298       // We only use half of V1 so map the usage down into the final blend mask.
16299       V1Blend = UseLoV1 ? LoV1 : HiV1;
16300       for (int i = 0; i < SplitNumElements; ++i)
16301         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
16302           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
16303     }
16304     if (UseLoV2 && UseHiV2) {
16305       V2Blend =
16306         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
16307     } else {
16308       // We only use half of V2 so map the usage down into the final blend mask.
16309       V2Blend = UseLoV2 ? LoV2 : HiV2;
16310       for (int i = 0; i < SplitNumElements; ++i)
16311         if (BlendMask[i] >= SplitNumElements)
16312           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
16313     }
16314     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
16315   };
16316   SDValue Lo = HalfBlend(LoMask);
16317   SDValue Hi = HalfBlend(HiMask);
16318   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
16319 }
16320 
16321 /// Either split a vector in halves or decompose the shuffles and the
16322 /// blend/unpack.
16323 ///
16324 /// This is provided as a good fallback for many lowerings of non-single-input
16325 /// shuffles with more than one 128-bit lane. In those cases, we want to select
16326 /// between splitting the shuffle into 128-bit components and stitching those
16327 /// back together vs. extracting the single-input shuffles and blending those
16328 /// results.
16329 static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
16330                                           SDValue V2, ArrayRef<int> Mask,
16331                                           const X86Subtarget &Subtarget,
16332                                           SelectionDAG &DAG) {
16333   assert(!V2.isUndef() && "This routine must not be used to lower single-input "
16334          "shuffles as it could then recurse on itself.");
16335   int Size = Mask.size();
16336 
16337   // If this can be modeled as a broadcast of two elements followed by a blend,
16338   // prefer that lowering. This is especially important because broadcasts can
16339   // often fold with memory operands.
16340   auto DoBothBroadcast = [&] {
16341     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
16342     for (int M : Mask)
16343       if (M >= Size) {
16344         if (V2BroadcastIdx < 0)
16345           V2BroadcastIdx = M - Size;
16346         else if (M - Size != V2BroadcastIdx)
16347           return false;
16348       } else if (M >= 0) {
16349         if (V1BroadcastIdx < 0)
16350           V1BroadcastIdx = M;
16351         else if (M != V1BroadcastIdx)
16352           return false;
16353       }
16354     return true;
16355   };
16356   if (DoBothBroadcast())
16357     return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
16358                                                 DAG);
16359 
16360   // If the inputs all stem from a single 128-bit lane of each input, then we
16361   // split them rather than blending because the split will decompose to
16362   // unusually few instructions.
16363   int LaneCount = VT.getSizeInBits() / 128;
16364   int LaneSize = Size / LaneCount;
16365   SmallBitVector LaneInputs[2];
16366   LaneInputs[0].resize(LaneCount, false);
16367   LaneInputs[1].resize(LaneCount, false);
16368   for (int i = 0; i < Size; ++i)
16369     if (Mask[i] >= 0)
16370       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
16371   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
16372     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16373 
16374   // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
16375   // requires that the decomposed single-input shuffles don't end up here.
16376   return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
16377                                               DAG);
16378 }
16379 
16380 // Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16381 // TODO: Extend to support v8f32 (+ 512-bit shuffles).
16382 static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
16383                                                  SDValue V1, SDValue V2,
16384                                                  ArrayRef<int> Mask,
16385                                                  SelectionDAG &DAG) {
16386   assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
16387 
16388   int LHSMask[4] = {-1, -1, -1, -1};
16389   int RHSMask[4] = {-1, -1, -1, -1};
16390   unsigned SHUFPMask = 0;
16391 
16392   // As SHUFPD uses a single LHS/RHS element per lane, we can always
16393   // perform the shuffle once the lanes have been shuffled in place.
16394   for (int i = 0; i != 4; ++i) {
16395     int M = Mask[i];
16396     if (M < 0)
16397       continue;
16398     int LaneBase = i & ~1;
16399     auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
16400     LaneMask[LaneBase + (M & 1)] = M;
16401     SHUFPMask |= (M & 1) << i;
16402   }
16403 
16404   SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
16405   SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
16406   return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
16407                      DAG.getTargetConstant(SHUFPMask, DL, MVT::i8));
16408 }
16409 
16410 /// Lower a vector shuffle crossing multiple 128-bit lanes as
16411 /// a lane permutation followed by a per-lane permutation.
16412 ///
16413 /// This is mainly for cases where we can have non-repeating permutes
16414 /// in each lane.
16415 ///
16416 /// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
16417 /// we should investigate merging them.
16418 static SDValue lowerShuffleAsLanePermuteAndPermute(
16419     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16420     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
16421   int NumElts = VT.getVectorNumElements();
16422   int NumLanes = VT.getSizeInBits() / 128;
16423   int NumEltsPerLane = NumElts / NumLanes;
16424   bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
16425 
16426   /// Attempts to find a sublane permute with the given size
16427   /// that gets all elements into their target lanes.
16428   ///
16429   /// If successful, fills CrossLaneMask and InLaneMask and returns true.
16430   /// If unsuccessful, returns false and may overwrite InLaneMask.
16431   auto getSublanePermute = [&](int NumSublanes) -> SDValue {
16432     int NumSublanesPerLane = NumSublanes / NumLanes;
16433     int NumEltsPerSublane = NumElts / NumSublanes;
16434 
16435     SmallVector<int, 16> CrossLaneMask;
16436     SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
16437     // CrossLaneMask but one entry == one sublane.
16438     SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
16439 
16440     for (int i = 0; i != NumElts; ++i) {
16441       int M = Mask[i];
16442       if (M < 0)
16443         continue;
16444 
16445       int SrcSublane = M / NumEltsPerSublane;
16446       int DstLane = i / NumEltsPerLane;
16447 
16448       // We only need to get the elements into the right lane, not sublane.
16449       // So search all sublanes that make up the destination lane.
16450       bool Found = false;
16451       int DstSubStart = DstLane * NumSublanesPerLane;
16452       int DstSubEnd = DstSubStart + NumSublanesPerLane;
16453       for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
16454         if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
16455           continue;
16456 
16457         Found = true;
16458         CrossLaneMaskLarge[DstSublane] = SrcSublane;
16459         int DstSublaneOffset = DstSublane * NumEltsPerSublane;
16460         InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
16461         break;
16462       }
16463       if (!Found)
16464         return SDValue();
16465     }
16466 
16467     // Fill CrossLaneMask using CrossLaneMaskLarge.
16468     narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
16469 
16470     if (!CanUseSublanes) {
16471       // If we're only shuffling a single lowest lane and the rest are identity
16472       // then don't bother.
16473       // TODO - isShuffleMaskInputInPlace could be extended to something like
16474       // this.
16475       int NumIdentityLanes = 0;
16476       bool OnlyShuffleLowestLane = true;
16477       for (int i = 0; i != NumLanes; ++i) {
16478         int LaneOffset = i * NumEltsPerLane;
16479         if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
16480                                        i * NumEltsPerLane))
16481           NumIdentityLanes++;
16482         else if (CrossLaneMask[LaneOffset] != 0)
16483           OnlyShuffleLowestLane = false;
16484       }
16485       if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
16486         return SDValue();
16487     }
16488 
16489     SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
16490     return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
16491                                 InLaneMask);
16492   };
16493 
16494   // First attempt a solution with full lanes.
16495   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes))
16496     return V;
16497 
16498   // The rest of the solutions use sublanes.
16499   if (!CanUseSublanes)
16500     return SDValue();
16501 
16502   // Then attempt a solution with 64-bit sublanes (vpermq).
16503   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes * 2))
16504     return V;
16505 
16506   // If that doesn't work and we have fast variable cross-lane shuffle,
16507   // attempt 32-bit sublanes (vpermd).
16508   if (!Subtarget.hasFastVariableCrossLaneShuffle())
16509     return SDValue();
16510 
16511   return getSublanePermute(/*NumSublanes=*/NumLanes * 4);
16512 }
16513 
16514 /// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
16515 /// source with a lane permutation.
16516 ///
16517 /// This lowering strategy results in four instructions in the worst case for a
16518 /// single-input cross lane shuffle which is lower than any other fully general
16519 /// cross-lane shuffle strategy I'm aware of. Special cases for each particular
16520 /// shuffle pattern should be handled prior to trying this lowering.
16521 static SDValue lowerShuffleAsLanePermuteAndShuffle(
16522     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16523     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
16524   // FIXME: This should probably be generalized for 512-bit vectors as well.
16525   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
16526   int Size = Mask.size();
16527   int LaneSize = Size / 2;
16528 
16529   // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16530   // Only do this if the elements aren't all from the lower lane,
16531   // otherwise we're (probably) better off doing a split.
16532   if (VT == MVT::v4f64 &&
16533       !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
16534     if (SDValue V =
16535             lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG))
16536       return V;
16537 
16538   // If there are only inputs from one 128-bit lane, splitting will in fact be
16539   // less expensive. The flags track whether the given lane contains an element
16540   // that crosses to another lane.
16541   if (!Subtarget.hasAVX2()) {
16542     bool LaneCrossing[2] = {false, false};
16543     for (int i = 0; i < Size; ++i)
16544       if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
16545         LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
16546     if (!LaneCrossing[0] || !LaneCrossing[1])
16547       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16548   } else {
16549     bool LaneUsed[2] = {false, false};
16550     for (int i = 0; i < Size; ++i)
16551       if (Mask[i] >= 0)
16552         LaneUsed[(Mask[i] % Size) / LaneSize] = true;
16553     if (!LaneUsed[0] || !LaneUsed[1])
16554       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16555   }
16556 
16557   // TODO - we could support shuffling V2 in the Flipped input.
16558   assert(V2.isUndef() &&
16559          "This last part of this routine only works on single input shuffles");
16560 
16561   SmallVector<int, 32> InLaneMask(Mask.begin(), Mask.end());
16562   for (int i = 0; i < Size; ++i) {
16563     int &M = InLaneMask[i];
16564     if (M < 0)
16565       continue;
16566     if (((M % Size) / LaneSize) != (i / LaneSize))
16567       M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
16568   }
16569   assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
16570          "In-lane shuffle mask expected");
16571 
16572   // Flip the lanes, and shuffle the results which should now be in-lane.
16573   MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
16574   SDValue Flipped = DAG.getBitcast(PVT, V1);
16575   Flipped =
16576       DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
16577   Flipped = DAG.getBitcast(VT, Flipped);
16578   return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
16579 }
16580 
16581 /// Handle lowering 2-lane 128-bit shuffles.
16582 static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
16583                                   SDValue V2, ArrayRef<int> Mask,
16584                                   const APInt &Zeroable,
16585                                   const X86Subtarget &Subtarget,
16586                                   SelectionDAG &DAG) {
16587   if (V2.isUndef()) {
16588     // Attempt to match VBROADCAST*128 subvector broadcast load.
16589     bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
16590     bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
16591     if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
16592         X86::mayFoldLoad(peekThroughOneUseBitcasts(V1), Subtarget)) {
16593       MVT MemVT = VT.getHalfNumVectorElementsVT();
16594       unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
16595       auto *Ld = cast<LoadSDNode>(peekThroughOneUseBitcasts(V1));
16596       if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
16597                                              VT, MemVT, Ld, Ofs, DAG))
16598         return BcstLd;
16599     }
16600 
16601     // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
16602     if (Subtarget.hasAVX2())
16603       return SDValue();
16604   }
16605 
16606   bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
16607 
16608   SmallVector<int, 4> WidenedMask;
16609   if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
16610     return SDValue();
16611 
16612   bool IsLowZero = (Zeroable & 0x3) == 0x3;
16613   bool IsHighZero = (Zeroable & 0xc) == 0xc;
16614 
16615   // Try to use an insert into a zero vector.
16616   if (WidenedMask[0] == 0 && IsHighZero) {
16617     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16618     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
16619                               DAG.getIntPtrConstant(0, DL));
16620     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
16621                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
16622                        DAG.getIntPtrConstant(0, DL));
16623   }
16624 
16625   // TODO: If minimizing size and one of the inputs is a zero vector and the
16626   // the zero vector has only one use, we could use a VPERM2X128 to save the
16627   // instruction bytes needed to explicitly generate the zero vector.
16628 
16629   // Blends are faster and handle all the non-lane-crossing cases.
16630   if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
16631                                           Subtarget, DAG))
16632     return Blend;
16633 
16634   // If either input operand is a zero vector, use VPERM2X128 because its mask
16635   // allows us to replace the zero input with an implicit zero.
16636   if (!IsLowZero && !IsHighZero) {
16637     // Check for patterns which can be matched with a single insert of a 128-bit
16638     // subvector.
16639     bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
16640     if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
16641 
16642       // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
16643       // this will likely become vinsertf128 which can't fold a 256-bit memop.
16644       if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
16645         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16646         SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
16647                                      OnlyUsesV1 ? V1 : V2,
16648                                      DAG.getIntPtrConstant(0, DL));
16649         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
16650                            DAG.getIntPtrConstant(2, DL));
16651       }
16652     }
16653 
16654     // Try to use SHUF128 if possible.
16655     if (Subtarget.hasVLX()) {
16656       if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
16657         unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
16658                             ((WidenedMask[1] % 2) << 1);
16659         return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
16660                            DAG.getTargetConstant(PermMask, DL, MVT::i8));
16661       }
16662     }
16663   }
16664 
16665   // Otherwise form a 128-bit permutation. After accounting for undefs,
16666   // convert the 64-bit shuffle mask selection values into 128-bit
16667   // selection bits by dividing the indexes by 2 and shifting into positions
16668   // defined by a vperm2*128 instruction's immediate control byte.
16669 
16670   // The immediate permute control byte looks like this:
16671   //    [1:0] - select 128 bits from sources for low half of destination
16672   //    [2]   - ignore
16673   //    [3]   - zero low half of destination
16674   //    [5:4] - select 128 bits from sources for high half of destination
16675   //    [6]   - ignore
16676   //    [7]   - zero high half of destination
16677 
16678   assert((WidenedMask[0] >= 0 || IsLowZero) &&
16679          (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
16680 
16681   unsigned PermMask = 0;
16682   PermMask |= IsLowZero  ? 0x08 : (WidenedMask[0] << 0);
16683   PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
16684 
16685   // Check the immediate mask and replace unused sources with undef.
16686   if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
16687     V1 = DAG.getUNDEF(VT);
16688   if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
16689     V2 = DAG.getUNDEF(VT);
16690 
16691   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
16692                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
16693 }
16694 
16695 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
16696 /// shuffling each lane.
16697 ///
16698 /// This attempts to create a repeated lane shuffle where each lane uses one
16699 /// or two of the lanes of the inputs. The lanes of the input vectors are
16700 /// shuffled in one or two independent shuffles to get the lanes into the
16701 /// position needed by the final shuffle.
16702 static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
16703     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16704     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16705   assert(!V2.isUndef() && "This is only useful with multiple inputs.");
16706 
16707   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
16708     return SDValue();
16709 
16710   int NumElts = Mask.size();
16711   int NumLanes = VT.getSizeInBits() / 128;
16712   int NumLaneElts = 128 / VT.getScalarSizeInBits();
16713   SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
16714   SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
16715 
16716   // First pass will try to fill in the RepeatMask from lanes that need two
16717   // sources.
16718   for (int Lane = 0; Lane != NumLanes; ++Lane) {
16719     int Srcs[2] = {-1, -1};
16720     SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
16721     for (int i = 0; i != NumLaneElts; ++i) {
16722       int M = Mask[(Lane * NumLaneElts) + i];
16723       if (M < 0)
16724         continue;
16725       // Determine which of the possible input lanes (NumLanes from each source)
16726       // this element comes from. Assign that as one of the sources for this
16727       // lane. We can assign up to 2 sources for this lane. If we run out
16728       // sources we can't do anything.
16729       int LaneSrc = M / NumLaneElts;
16730       int Src;
16731       if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
16732         Src = 0;
16733       else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
16734         Src = 1;
16735       else
16736         return SDValue();
16737 
16738       Srcs[Src] = LaneSrc;
16739       InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
16740     }
16741 
16742     // If this lane has two sources, see if it fits with the repeat mask so far.
16743     if (Srcs[1] < 0)
16744       continue;
16745 
16746     LaneSrcs[Lane][0] = Srcs[0];
16747     LaneSrcs[Lane][1] = Srcs[1];
16748 
16749     auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
16750       assert(M1.size() == M2.size() && "Unexpected mask size");
16751       for (int i = 0, e = M1.size(); i != e; ++i)
16752         if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
16753           return false;
16754       return true;
16755     };
16756 
16757     auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
16758       assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
16759       for (int i = 0, e = MergedMask.size(); i != e; ++i) {
16760         int M = Mask[i];
16761         if (M < 0)
16762           continue;
16763         assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
16764                "Unexpected mask element");
16765         MergedMask[i] = M;
16766       }
16767     };
16768 
16769     if (MatchMasks(InLaneMask, RepeatMask)) {
16770       // Merge this lane mask into the final repeat mask.
16771       MergeMasks(InLaneMask, RepeatMask);
16772       continue;
16773     }
16774 
16775     // Didn't find a match. Swap the operands and try again.
16776     std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
16777     ShuffleVectorSDNode::commuteMask(InLaneMask);
16778 
16779     if (MatchMasks(InLaneMask, RepeatMask)) {
16780       // Merge this lane mask into the final repeat mask.
16781       MergeMasks(InLaneMask, RepeatMask);
16782       continue;
16783     }
16784 
16785     // Couldn't find a match with the operands in either order.
16786     return SDValue();
16787   }
16788 
16789   // Now handle any lanes with only one source.
16790   for (int Lane = 0; Lane != NumLanes; ++Lane) {
16791     // If this lane has already been processed, skip it.
16792     if (LaneSrcs[Lane][0] >= 0)
16793       continue;
16794 
16795     for (int i = 0; i != NumLaneElts; ++i) {
16796       int M = Mask[(Lane * NumLaneElts) + i];
16797       if (M < 0)
16798         continue;
16799 
16800       // If RepeatMask isn't defined yet we can define it ourself.
16801       if (RepeatMask[i] < 0)
16802         RepeatMask[i] = M % NumLaneElts;
16803 
16804       if (RepeatMask[i] < NumElts) {
16805         if (RepeatMask[i] != M % NumLaneElts)
16806           return SDValue();
16807         LaneSrcs[Lane][0] = M / NumLaneElts;
16808       } else {
16809         if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
16810           return SDValue();
16811         LaneSrcs[Lane][1] = M / NumLaneElts;
16812       }
16813     }
16814 
16815     if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
16816       return SDValue();
16817   }
16818 
16819   SmallVector<int, 16> NewMask(NumElts, -1);
16820   for (int Lane = 0; Lane != NumLanes; ++Lane) {
16821     int Src = LaneSrcs[Lane][0];
16822     for (int i = 0; i != NumLaneElts; ++i) {
16823       int M = -1;
16824       if (Src >= 0)
16825         M = Src * NumLaneElts + i;
16826       NewMask[Lane * NumLaneElts + i] = M;
16827     }
16828   }
16829   SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16830   // Ensure we didn't get back the shuffle we started with.
16831   // FIXME: This is a hack to make up for some splat handling code in
16832   // getVectorShuffle.
16833   if (isa<ShuffleVectorSDNode>(NewV1) &&
16834       cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
16835     return SDValue();
16836 
16837   for (int Lane = 0; Lane != NumLanes; ++Lane) {
16838     int Src = LaneSrcs[Lane][1];
16839     for (int i = 0; i != NumLaneElts; ++i) {
16840       int M = -1;
16841       if (Src >= 0)
16842         M = Src * NumLaneElts + i;
16843       NewMask[Lane * NumLaneElts + i] = M;
16844     }
16845   }
16846   SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16847   // Ensure we didn't get back the shuffle we started with.
16848   // FIXME: This is a hack to make up for some splat handling code in
16849   // getVectorShuffle.
16850   if (isa<ShuffleVectorSDNode>(NewV2) &&
16851       cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
16852     return SDValue();
16853 
16854   for (int i = 0; i != NumElts; ++i) {
16855     NewMask[i] = RepeatMask[i % NumLaneElts];
16856     if (NewMask[i] < 0)
16857       continue;
16858 
16859     NewMask[i] += (i / NumLaneElts) * NumLaneElts;
16860   }
16861   return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
16862 }
16863 
16864 /// If the input shuffle mask results in a vector that is undefined in all upper
16865 /// or lower half elements and that mask accesses only 2 halves of the
16866 /// shuffle's operands, return true. A mask of half the width with mask indexes
16867 /// adjusted to access the extracted halves of the original shuffle operands is
16868 /// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
16869 /// lower half of each input operand is accessed.
16870 static bool
16871 getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
16872                    int &HalfIdx1, int &HalfIdx2) {
16873   assert((Mask.size() == HalfMask.size() * 2) &&
16874          "Expected input mask to be twice as long as output");
16875 
16876   // Exactly one half of the result must be undef to allow narrowing.
16877   bool UndefLower = isUndefLowerHalf(Mask);
16878   bool UndefUpper = isUndefUpperHalf(Mask);
16879   if (UndefLower == UndefUpper)
16880     return false;
16881 
16882   unsigned HalfNumElts = HalfMask.size();
16883   unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
16884   HalfIdx1 = -1;
16885   HalfIdx2 = -1;
16886   for (unsigned i = 0; i != HalfNumElts; ++i) {
16887     int M = Mask[i + MaskIndexOffset];
16888     if (M < 0) {
16889       HalfMask[i] = M;
16890       continue;
16891     }
16892 
16893     // Determine which of the 4 half vectors this element is from.
16894     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
16895     int HalfIdx = M / HalfNumElts;
16896 
16897     // Determine the element index into its half vector source.
16898     int HalfElt = M % HalfNumElts;
16899 
16900     // We can shuffle with up to 2 half vectors, set the new 'half'
16901     // shuffle mask accordingly.
16902     if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
16903       HalfMask[i] = HalfElt;
16904       HalfIdx1 = HalfIdx;
16905       continue;
16906     }
16907     if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
16908       HalfMask[i] = HalfElt + HalfNumElts;
16909       HalfIdx2 = HalfIdx;
16910       continue;
16911     }
16912 
16913     // Too many half vectors referenced.
16914     return false;
16915   }
16916 
16917   return true;
16918 }
16919 
16920 /// Given the output values from getHalfShuffleMask(), create a half width
16921 /// shuffle of extracted vectors followed by an insert back to full width.
16922 static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
16923                                      ArrayRef<int> HalfMask, int HalfIdx1,
16924                                      int HalfIdx2, bool UndefLower,
16925                                      SelectionDAG &DAG, bool UseConcat = false) {
16926   assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
16927   assert(V1.getValueType().isSimple() && "Expecting only simple types");
16928 
16929   MVT VT = V1.getSimpleValueType();
16930   MVT HalfVT = VT.getHalfNumVectorElementsVT();
16931   unsigned HalfNumElts = HalfVT.getVectorNumElements();
16932 
16933   auto getHalfVector = [&](int HalfIdx) {
16934     if (HalfIdx < 0)
16935       return DAG.getUNDEF(HalfVT);
16936     SDValue V = (HalfIdx < 2 ? V1 : V2);
16937     HalfIdx = (HalfIdx % 2) * HalfNumElts;
16938     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
16939                        DAG.getIntPtrConstant(HalfIdx, DL));
16940   };
16941 
16942   // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
16943   SDValue Half1 = getHalfVector(HalfIdx1);
16944   SDValue Half2 = getHalfVector(HalfIdx2);
16945   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
16946   if (UseConcat) {
16947     SDValue Op0 = V;
16948     SDValue Op1 = DAG.getUNDEF(HalfVT);
16949     if (UndefLower)
16950       std::swap(Op0, Op1);
16951     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
16952   }
16953 
16954   unsigned Offset = UndefLower ? HalfNumElts : 0;
16955   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
16956                      DAG.getIntPtrConstant(Offset, DL));
16957 }
16958 
16959 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
16960 /// This allows for fast cases such as subvector extraction/insertion
16961 /// or shuffling smaller vector types which can lower more efficiently.
16962 static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
16963                                          SDValue V2, ArrayRef<int> Mask,
16964                                          const X86Subtarget &Subtarget,
16965                                          SelectionDAG &DAG) {
16966   assert((VT.is256BitVector() || VT.is512BitVector()) &&
16967          "Expected 256-bit or 512-bit vector");
16968 
16969   bool UndefLower = isUndefLowerHalf(Mask);
16970   if (!UndefLower && !isUndefUpperHalf(Mask))
16971     return SDValue();
16972 
16973   assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
16974          "Completely undef shuffle mask should have been simplified already");
16975 
16976   // Upper half is undef and lower half is whole upper subvector.
16977   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16978   MVT HalfVT = VT.getHalfNumVectorElementsVT();
16979   unsigned HalfNumElts = HalfVT.getVectorNumElements();
16980   if (!UndefLower &&
16981       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
16982     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16983                              DAG.getIntPtrConstant(HalfNumElts, DL));
16984     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16985                        DAG.getIntPtrConstant(0, DL));
16986   }
16987 
16988   // Lower half is undef and upper half is whole lower subvector.
16989   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16990   if (UndefLower &&
16991       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
16992     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16993                              DAG.getIntPtrConstant(0, DL));
16994     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16995                        DAG.getIntPtrConstant(HalfNumElts, DL));
16996   }
16997 
16998   int HalfIdx1, HalfIdx2;
16999   SmallVector<int, 8> HalfMask(HalfNumElts);
17000   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
17001     return SDValue();
17002 
17003   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
17004 
17005   // Only shuffle the halves of the inputs when useful.
17006   unsigned NumLowerHalves =
17007       (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
17008   unsigned NumUpperHalves =
17009       (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
17010   assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
17011 
17012   // Determine the larger pattern of undef/halves, then decide if it's worth
17013   // splitting the shuffle based on subtarget capabilities and types.
17014   unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
17015   if (!UndefLower) {
17016     // XXXXuuuu: no insert is needed.
17017     // Always extract lowers when setting lower - these are all free subreg ops.
17018     if (NumUpperHalves == 0)
17019       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
17020                                    UndefLower, DAG);
17021 
17022     if (NumUpperHalves == 1) {
17023       // AVX2 has efficient 32/64-bit element cross-lane shuffles.
17024       if (Subtarget.hasAVX2()) {
17025         // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
17026         if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
17027             !is128BitUnpackShuffleMask(HalfMask) &&
17028             (!isSingleSHUFPSMask(HalfMask) ||
17029              Subtarget.hasFastVariableCrossLaneShuffle()))
17030           return SDValue();
17031         // If this is a unary shuffle (assume that the 2nd operand is
17032         // canonicalized to undef), then we can use vpermpd. Otherwise, we
17033         // are better off extracting the upper half of 1 operand and using a
17034         // narrow shuffle.
17035         if (EltWidth == 64 && V2.isUndef())
17036           return SDValue();
17037       }
17038       // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
17039       if (Subtarget.hasAVX512() && VT.is512BitVector())
17040         return SDValue();
17041       // Extract + narrow shuffle is better than the wide alternative.
17042       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
17043                                    UndefLower, DAG);
17044     }
17045 
17046     // Don't extract both uppers, instead shuffle and then extract.
17047     assert(NumUpperHalves == 2 && "Half vector count went wrong");
17048     return SDValue();
17049   }
17050 
17051   // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
17052   if (NumUpperHalves == 0) {
17053     // AVX2 has efficient 64-bit element cross-lane shuffles.
17054     // TODO: Refine to account for unary shuffle, splat, and other masks?
17055     if (Subtarget.hasAVX2() && EltWidth == 64)
17056       return SDValue();
17057     // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
17058     if (Subtarget.hasAVX512() && VT.is512BitVector())
17059       return SDValue();
17060     // Narrow shuffle + insert is better than the wide alternative.
17061     return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
17062                                  UndefLower, DAG);
17063   }
17064 
17065   // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
17066   return SDValue();
17067 }
17068 
17069 /// Test whether the specified input (0 or 1) is in-place blended by the
17070 /// given mask.
17071 ///
17072 /// This returns true if the elements from a particular input are already in the
17073 /// slot required by the given mask and require no permutation.
17074 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
17075   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
17076   int Size = Mask.size();
17077   for (int i = 0; i < Size; ++i)
17078     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
17079       return false;
17080 
17081   return true;
17082 }
17083 
17084 /// Handle case where shuffle sources are coming from the same 128-bit lane and
17085 /// every lane can be represented as the same repeating mask - allowing us to
17086 /// shuffle the sources with the repeating shuffle and then permute the result
17087 /// to the destination lanes.
17088 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
17089     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
17090     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
17091   int NumElts = VT.getVectorNumElements();
17092   int NumLanes = VT.getSizeInBits() / 128;
17093   int NumLaneElts = NumElts / NumLanes;
17094 
17095   // On AVX2 we may be able to just shuffle the lowest elements and then
17096   // broadcast the result.
17097   if (Subtarget.hasAVX2()) {
17098     for (unsigned BroadcastSize : {16, 32, 64}) {
17099       if (BroadcastSize <= VT.getScalarSizeInBits())
17100         continue;
17101       int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
17102 
17103       // Attempt to match a repeating pattern every NumBroadcastElts,
17104       // accounting for UNDEFs but only references the lowest 128-bit
17105       // lane of the inputs.
17106       auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
17107         for (int i = 0; i != NumElts; i += NumBroadcastElts)
17108           for (int j = 0; j != NumBroadcastElts; ++j) {
17109             int M = Mask[i + j];
17110             if (M < 0)
17111               continue;
17112             int &R = RepeatMask[j];
17113             if (0 != ((M % NumElts) / NumLaneElts))
17114               return false;
17115             if (0 <= R && R != M)
17116               return false;
17117             R = M;
17118           }
17119         return true;
17120       };
17121 
17122       SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
17123       if (!FindRepeatingBroadcastMask(RepeatMask))
17124         continue;
17125 
17126       // Shuffle the (lowest) repeated elements in place for broadcast.
17127       SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
17128 
17129       // Shuffle the actual broadcast.
17130       SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
17131       for (int i = 0; i != NumElts; i += NumBroadcastElts)
17132         for (int j = 0; j != NumBroadcastElts; ++j)
17133           BroadcastMask[i + j] = j;
17134       return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
17135                                   BroadcastMask);
17136     }
17137   }
17138 
17139   // Bail if the shuffle mask doesn't cross 128-bit lanes.
17140   if (!is128BitLaneCrossingShuffleMask(VT, Mask))
17141     return SDValue();
17142 
17143   // Bail if we already have a repeated lane shuffle mask.
17144   SmallVector<int, 8> RepeatedShuffleMask;
17145   if (is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedShuffleMask))
17146     return SDValue();
17147 
17148   // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
17149   // (with PERMQ/PERMPD), otherwise we can only permute whole 128-bit lanes.
17150   int SubLaneScale = Subtarget.hasAVX2() && VT.is256BitVector() ? 2 : 1;
17151   int NumSubLanes = NumLanes * SubLaneScale;
17152   int NumSubLaneElts = NumLaneElts / SubLaneScale;
17153 
17154   // Check that all the sources are coming from the same lane and see if we can
17155   // form a repeating shuffle mask (local to each sub-lane). At the same time,
17156   // determine the source sub-lane for each destination sub-lane.
17157   int TopSrcSubLane = -1;
17158   SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
17159   SmallVector<int, 8> RepeatedSubLaneMasks[2] = {
17160       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef),
17161       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef)};
17162 
17163   for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
17164     // Extract the sub-lane mask, check that it all comes from the same lane
17165     // and normalize the mask entries to come from the first lane.
17166     int SrcLane = -1;
17167     SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
17168     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
17169       int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
17170       if (M < 0)
17171         continue;
17172       int Lane = (M % NumElts) / NumLaneElts;
17173       if ((0 <= SrcLane) && (SrcLane != Lane))
17174         return SDValue();
17175       SrcLane = Lane;
17176       int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
17177       SubLaneMask[Elt] = LocalM;
17178     }
17179 
17180     // Whole sub-lane is UNDEF.
17181     if (SrcLane < 0)
17182       continue;
17183 
17184     // Attempt to match against the candidate repeated sub-lane masks.
17185     for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
17186       auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
17187         for (int i = 0; i != NumSubLaneElts; ++i) {
17188           if (M1[i] < 0 || M2[i] < 0)
17189             continue;
17190           if (M1[i] != M2[i])
17191             return false;
17192         }
17193         return true;
17194       };
17195 
17196       auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
17197       if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
17198         continue;
17199 
17200       // Merge the sub-lane mask into the matching repeated sub-lane mask.
17201       for (int i = 0; i != NumSubLaneElts; ++i) {
17202         int M = SubLaneMask[i];
17203         if (M < 0)
17204           continue;
17205         assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
17206                "Unexpected mask element");
17207         RepeatedSubLaneMask[i] = M;
17208       }
17209 
17210       // Track the top most source sub-lane - by setting the remaining to UNDEF
17211       // we can greatly simplify shuffle matching.
17212       int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
17213       TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
17214       Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
17215       break;
17216     }
17217 
17218     // Bail if we failed to find a matching repeated sub-lane mask.
17219     if (Dst2SrcSubLanes[DstSubLane] < 0)
17220       return SDValue();
17221   }
17222   assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
17223          "Unexpected source lane");
17224 
17225   // Create a repeating shuffle mask for the entire vector.
17226   SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
17227   for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
17228     int Lane = SubLane / SubLaneScale;
17229     auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
17230     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
17231       int M = RepeatedSubLaneMask[Elt];
17232       if (M < 0)
17233         continue;
17234       int Idx = (SubLane * NumSubLaneElts) + Elt;
17235       RepeatedMask[Idx] = M + (Lane * NumLaneElts);
17236     }
17237   }
17238   SDValue RepeatedShuffle = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
17239 
17240   // Shuffle each source sub-lane to its destination.
17241   SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
17242   for (int i = 0; i != NumElts; i += NumSubLaneElts) {
17243     int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
17244     if (SrcSubLane < 0)
17245       continue;
17246     for (int j = 0; j != NumSubLaneElts; ++j)
17247       SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
17248   }
17249 
17250   return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
17251                               SubLaneMask);
17252 }
17253 
17254 static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
17255                                    bool &ForceV1Zero, bool &ForceV2Zero,
17256                                    unsigned &ShuffleImm, ArrayRef<int> Mask,
17257                                    const APInt &Zeroable) {
17258   int NumElts = VT.getVectorNumElements();
17259   assert(VT.getScalarSizeInBits() == 64 &&
17260          (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
17261          "Unexpected data type for VSHUFPD");
17262   assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
17263          "Illegal shuffle mask");
17264 
17265   bool ZeroLane[2] = { true, true };
17266   for (int i = 0; i < NumElts; ++i)
17267     ZeroLane[i & 1] &= Zeroable[i];
17268 
17269   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
17270   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
17271   ShuffleImm = 0;
17272   bool ShufpdMask = true;
17273   bool CommutableMask = true;
17274   for (int i = 0; i < NumElts; ++i) {
17275     if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
17276       continue;
17277     if (Mask[i] < 0)
17278       return false;
17279     int Val = (i & 6) + NumElts * (i & 1);
17280     int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
17281     if (Mask[i] < Val || Mask[i] > Val + 1)
17282       ShufpdMask = false;
17283     if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
17284       CommutableMask = false;
17285     ShuffleImm |= (Mask[i] % 2) << i;
17286   }
17287 
17288   if (!ShufpdMask && !CommutableMask)
17289     return false;
17290 
17291   if (!ShufpdMask && CommutableMask)
17292     std::swap(V1, V2);
17293 
17294   ForceV1Zero = ZeroLane[0];
17295   ForceV2Zero = ZeroLane[1];
17296   return true;
17297 }
17298 
17299 static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
17300                                       SDValue V2, ArrayRef<int> Mask,
17301                                       const APInt &Zeroable,
17302                                       const X86Subtarget &Subtarget,
17303                                       SelectionDAG &DAG) {
17304   assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
17305          "Unexpected data type for VSHUFPD");
17306 
17307   unsigned Immediate = 0;
17308   bool ForceV1Zero = false, ForceV2Zero = false;
17309   if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
17310                               Mask, Zeroable))
17311     return SDValue();
17312 
17313   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
17314   if (ForceV1Zero)
17315     V1 = getZeroVector(VT, Subtarget, DAG, DL);
17316   if (ForceV2Zero)
17317     V2 = getZeroVector(VT, Subtarget, DAG, DL);
17318 
17319   return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
17320                      DAG.getTargetConstant(Immediate, DL, MVT::i8));
17321 }
17322 
17323 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
17324 // by zeroable elements in the remaining 24 elements. Turn this into two
17325 // vmovqb instructions shuffled together.
17326 static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
17327                                              SDValue V1, SDValue V2,
17328                                              ArrayRef<int> Mask,
17329                                              const APInt &Zeroable,
17330                                              SelectionDAG &DAG) {
17331   assert(VT == MVT::v32i8 && "Unexpected type!");
17332 
17333   // The first 8 indices should be every 8th element.
17334   if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
17335     return SDValue();
17336 
17337   // Remaining elements need to be zeroable.
17338   if (Zeroable.countLeadingOnes() < (Mask.size() - 8))
17339     return SDValue();
17340 
17341   V1 = DAG.getBitcast(MVT::v4i64, V1);
17342   V2 = DAG.getBitcast(MVT::v4i64, V2);
17343 
17344   V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
17345   V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
17346 
17347   // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
17348   // the upper bits of the result using an unpckldq.
17349   SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
17350                                         { 0, 1, 2, 3, 16, 17, 18, 19,
17351                                           4, 5, 6, 7, 20, 21, 22, 23 });
17352   // Insert the unpckldq into a zero vector to widen to v32i8.
17353   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
17354                      DAG.getConstant(0, DL, MVT::v32i8), Unpack,
17355                      DAG.getIntPtrConstant(0, DL));
17356 }
17357 
17358 
17359 /// Handle lowering of 4-lane 64-bit floating point shuffles.
17360 ///
17361 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
17362 /// isn't available.
17363 static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17364                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17365                                  const X86Subtarget &Subtarget,
17366                                  SelectionDAG &DAG) {
17367   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
17368   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
17369   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
17370 
17371   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
17372                                      Subtarget, DAG))
17373     return V;
17374 
17375   if (V2.isUndef()) {
17376     // Check for being able to broadcast a single element.
17377     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
17378                                                     Mask, Subtarget, DAG))
17379       return Broadcast;
17380 
17381     // Use low duplicate instructions for masks that match their pattern.
17382     if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
17383       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
17384 
17385     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
17386       // Non-half-crossing single input shuffles can be lowered with an
17387       // interleaved permutation.
17388       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
17389                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
17390       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
17391                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
17392     }
17393 
17394     // With AVX2 we have direct support for this permutation.
17395     if (Subtarget.hasAVX2())
17396       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
17397                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
17398 
17399     // Try to create an in-lane repeating shuffle mask and then shuffle the
17400     // results into the target lanes.
17401     if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17402             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
17403       return V;
17404 
17405     // Try to permute the lanes and then use a per-lane permute.
17406     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
17407                                                         Mask, DAG, Subtarget))
17408       return V;
17409 
17410     // Otherwise, fall back.
17411     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
17412                                                DAG, Subtarget);
17413   }
17414 
17415   // Use dedicated unpack instructions for masks that match their pattern.
17416   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
17417     return V;
17418 
17419   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
17420                                           Zeroable, Subtarget, DAG))
17421     return Blend;
17422 
17423   // Check if the blend happens to exactly fit that of SHUFPD.
17424   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
17425                                           Zeroable, Subtarget, DAG))
17426     return Op;
17427 
17428   // If we have lane crossing shuffles AND they don't all come from the lower
17429   // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
17430   // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
17431   // canonicalize to a blend of splat which isn't necessary for this combine.
17432   if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
17433       !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
17434       (V1.getOpcode() != ISD::BUILD_VECTOR) &&
17435       (V2.getOpcode() != ISD::BUILD_VECTOR))
17436     if (SDValue Op = lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2,
17437                                                        Mask, DAG))
17438       return Op;
17439 
17440   // If we have one input in place, then we can permute the other input and
17441   // blend the result.
17442   if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
17443     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
17444                                                 Subtarget, DAG);
17445 
17446   // Try to create an in-lane repeating shuffle mask and then shuffle the
17447   // results into the target lanes.
17448   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17449           DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
17450     return V;
17451 
17452   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17453   // shuffle. However, if we have AVX2 and either inputs are already in place,
17454   // we will be able to shuffle even across lanes the other input in a single
17455   // instruction so skip this pattern.
17456   if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
17457                                 isShuffleMaskInputInPlace(1, Mask))))
17458     if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
17459             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
17460       return V;
17461 
17462   // If we have VLX support, we can use VEXPAND.
17463   if (Subtarget.hasVLX())
17464     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
17465                                          DAG, Subtarget))
17466       return V;
17467 
17468   // If we have AVX2 then we always want to lower with a blend because an v4 we
17469   // can fully permute the elements.
17470   if (Subtarget.hasAVX2())
17471     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
17472                                                 Subtarget, DAG);
17473 
17474   // Otherwise fall back on generic lowering.
17475   return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
17476                                     Subtarget, DAG);
17477 }
17478 
17479 /// Handle lowering of 4-lane 64-bit integer shuffles.
17480 ///
17481 /// This routine is only called when we have AVX2 and thus a reasonable
17482 /// instruction set for v4i64 shuffling..
17483 static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17484                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17485                                  const X86Subtarget &Subtarget,
17486                                  SelectionDAG &DAG) {
17487   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
17488   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
17489   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
17490   assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
17491 
17492   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
17493                                      Subtarget, DAG))
17494     return V;
17495 
17496   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
17497                                           Zeroable, Subtarget, DAG))
17498     return Blend;
17499 
17500   // Check for being able to broadcast a single element.
17501   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
17502                                                   Subtarget, DAG))
17503     return Broadcast;
17504 
17505   if (V2.isUndef()) {
17506     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17507     // can use lower latency instructions that will operate on both lanes.
17508     SmallVector<int, 2> RepeatedMask;
17509     if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
17510       SmallVector<int, 4> PSHUFDMask;
17511       narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
17512       return DAG.getBitcast(
17513           MVT::v4i64,
17514           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
17515                       DAG.getBitcast(MVT::v8i32, V1),
17516                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17517     }
17518 
17519     // AVX2 provides a direct instruction for permuting a single input across
17520     // lanes.
17521     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
17522                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
17523   }
17524 
17525   // Try to use shift instructions.
17526   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
17527                                           Zeroable, Subtarget, DAG))
17528     return Shift;
17529 
17530   // If we have VLX support, we can use VALIGN or VEXPAND.
17531   if (Subtarget.hasVLX()) {
17532     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
17533                                               Subtarget, DAG))
17534       return Rotate;
17535 
17536     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
17537                                          DAG, Subtarget))
17538       return V;
17539   }
17540 
17541   // Try to use PALIGNR.
17542   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
17543                                                 Subtarget, DAG))
17544     return Rotate;
17545 
17546   // Use dedicated unpack instructions for masks that match their pattern.
17547   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
17548     return V;
17549 
17550   // If we have one input in place, then we can permute the other input and
17551   // blend the result.
17552   if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
17553     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17554                                                 Subtarget, DAG);
17555 
17556   // Try to create an in-lane repeating shuffle mask and then shuffle the
17557   // results into the target lanes.
17558   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17559           DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17560     return V;
17561 
17562   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17563   // shuffle. However, if we have AVX2 and either inputs are already in place,
17564   // we will be able to shuffle even across lanes the other input in a single
17565   // instruction so skip this pattern.
17566   if (!isShuffleMaskInputInPlace(0, Mask) &&
17567       !isShuffleMaskInputInPlace(1, Mask))
17568     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17569             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17570       return Result;
17571 
17572   // Otherwise fall back on generic blend lowering.
17573   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17574                                               Subtarget, DAG);
17575 }
17576 
17577 /// Handle lowering of 8-lane 32-bit floating point shuffles.
17578 ///
17579 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
17580 /// isn't available.
17581 static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17582                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17583                                  const X86Subtarget &Subtarget,
17584                                  SelectionDAG &DAG) {
17585   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17586   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17587   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17588 
17589   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
17590                                           Zeroable, Subtarget, DAG))
17591     return Blend;
17592 
17593   // Check for being able to broadcast a single element.
17594   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
17595                                                   Subtarget, DAG))
17596     return Broadcast;
17597 
17598   // If the shuffle mask is repeated in each 128-bit lane, we have many more
17599   // options to efficiently lower the shuffle.
17600   SmallVector<int, 4> RepeatedMask;
17601   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
17602     assert(RepeatedMask.size() == 4 &&
17603            "Repeated masks must be half the mask width!");
17604 
17605     // Use even/odd duplicate instructions for masks that match their pattern.
17606     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17607       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
17608     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17609       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
17610 
17611     if (V2.isUndef())
17612       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
17613                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17614 
17615     // Use dedicated unpack instructions for masks that match their pattern.
17616     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
17617       return V;
17618 
17619     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
17620     // have already handled any direct blends.
17621     return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
17622   }
17623 
17624   // Try to create an in-lane repeating shuffle mask and then shuffle the
17625   // results into the target lanes.
17626   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17627           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17628     return V;
17629 
17630   // If we have a single input shuffle with different shuffle patterns in the
17631   // two 128-bit lanes use the variable mask to VPERMILPS.
17632   if (V2.isUndef()) {
17633     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
17634       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17635       return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
17636     }
17637     if (Subtarget.hasAVX2()) {
17638       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17639       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
17640     }
17641     // Otherwise, fall back.
17642     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
17643                                                DAG, Subtarget);
17644   }
17645 
17646   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17647   // shuffle.
17648   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17649           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17650     return Result;
17651 
17652   // If we have VLX support, we can use VEXPAND.
17653   if (Subtarget.hasVLX())
17654     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
17655                                          DAG, Subtarget))
17656       return V;
17657 
17658   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17659   // since after split we get a more efficient code using vpunpcklwd and
17660   // vpunpckhwd instrs than vblend.
17661   if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32))
17662     return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Subtarget,
17663                                       DAG);
17664 
17665   // If we have AVX2 then we always want to lower with a blend because at v8 we
17666   // can fully permute the elements.
17667   if (Subtarget.hasAVX2())
17668     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
17669                                                 Subtarget, DAG);
17670 
17671   // Otherwise fall back on generic lowering.
17672   return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
17673                                     Subtarget, DAG);
17674 }
17675 
17676 /// Handle lowering of 8-lane 32-bit integer shuffles.
17677 ///
17678 /// This routine is only called when we have AVX2 and thus a reasonable
17679 /// instruction set for v8i32 shuffling..
17680 static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17681                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17682                                  const X86Subtarget &Subtarget,
17683                                  SelectionDAG &DAG) {
17684   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17685   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17686   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17687   assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
17688 
17689   // Whenever we can lower this as a zext, that instruction is strictly faster
17690   // than any alternative. It also allows us to fold memory operands into the
17691   // shuffle in many cases.
17692   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17693                                                    Zeroable, Subtarget, DAG))
17694     return ZExt;
17695 
17696   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17697   // since after split we get a more efficient code than vblend by using
17698   // vpunpcklwd and vpunpckhwd instrs.
17699   if (isUnpackWdShuffleMask(Mask, MVT::v8i32) && !V2.isUndef() &&
17700       !Subtarget.hasAVX512())
17701     return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Subtarget,
17702                                       DAG);
17703 
17704   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
17705                                           Zeroable, Subtarget, DAG))
17706     return Blend;
17707 
17708   // Check for being able to broadcast a single element.
17709   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
17710                                                   Subtarget, DAG))
17711     return Broadcast;
17712 
17713   // If the shuffle mask is repeated in each 128-bit lane we can use more
17714   // efficient instructions that mirror the shuffles across the two 128-bit
17715   // lanes.
17716   SmallVector<int, 4> RepeatedMask;
17717   bool Is128BitLaneRepeatedShuffle =
17718       is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
17719   if (Is128BitLaneRepeatedShuffle) {
17720     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17721     if (V2.isUndef())
17722       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
17723                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17724 
17725     // Use dedicated unpack instructions for masks that match their pattern.
17726     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
17727       return V;
17728   }
17729 
17730   // Try to use shift instructions.
17731   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
17732                                           Zeroable, Subtarget, DAG))
17733     return Shift;
17734 
17735   // If we have VLX support, we can use VALIGN or EXPAND.
17736   if (Subtarget.hasVLX()) {
17737     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
17738                                               Subtarget, DAG))
17739       return Rotate;
17740 
17741     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
17742                                          DAG, Subtarget))
17743       return V;
17744   }
17745 
17746   // Try to use byte rotation instructions.
17747   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
17748                                                 Subtarget, DAG))
17749     return Rotate;
17750 
17751   // Try to create an in-lane repeating shuffle mask and then shuffle the
17752   // results into the target lanes.
17753   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17754           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17755     return V;
17756 
17757   if (V2.isUndef()) {
17758     // Try to produce a fixed cross-128-bit lane permute followed by unpack
17759     // because that should be faster than the variable permute alternatives.
17760     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, Mask, V1, V2, DAG))
17761       return V;
17762 
17763     // If the shuffle patterns aren't repeated but it's a single input, directly
17764     // generate a cross-lane VPERMD instruction.
17765     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17766     return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
17767   }
17768 
17769   // Assume that a single SHUFPS is faster than an alternative sequence of
17770   // multiple instructions (even if the CPU has a domain penalty).
17771   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17772   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17773     SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
17774     SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
17775     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
17776                                             CastV1, CastV2, DAG);
17777     return DAG.getBitcast(MVT::v8i32, ShufPS);
17778   }
17779 
17780   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17781   // shuffle.
17782   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17783           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17784     return Result;
17785 
17786   // Otherwise fall back on generic blend lowering.
17787   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
17788                                               Subtarget, DAG);
17789 }
17790 
17791 /// Handle lowering of 16-lane 16-bit integer shuffles.
17792 ///
17793 /// This routine is only called when we have AVX2 and thus a reasonable
17794 /// instruction set for v16i16 shuffling..
17795 static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17796                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17797                                   const X86Subtarget &Subtarget,
17798                                   SelectionDAG &DAG) {
17799   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17800   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17801   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17802   assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
17803 
17804   // Whenever we can lower this as a zext, that instruction is strictly faster
17805   // than any alternative. It also allows us to fold memory operands into the
17806   // shuffle in many cases.
17807   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17808           DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17809     return ZExt;
17810 
17811   // Check for being able to broadcast a single element.
17812   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
17813                                                   Subtarget, DAG))
17814     return Broadcast;
17815 
17816   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
17817                                           Zeroable, Subtarget, DAG))
17818     return Blend;
17819 
17820   // Use dedicated unpack instructions for masks that match their pattern.
17821   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
17822     return V;
17823 
17824   // Use dedicated pack instructions for masks that match their pattern.
17825   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
17826                                        Subtarget))
17827     return V;
17828 
17829   // Try to use lower using a truncation.
17830   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17831                                        Subtarget, DAG))
17832     return V;
17833 
17834   // Try to use shift instructions.
17835   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
17836                                           Zeroable, Subtarget, DAG))
17837     return Shift;
17838 
17839   // Try to use byte rotation instructions.
17840   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
17841                                                 Subtarget, DAG))
17842     return Rotate;
17843 
17844   // Try to create an in-lane repeating shuffle mask and then shuffle the
17845   // results into the target lanes.
17846   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17847           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17848     return V;
17849 
17850   if (V2.isUndef()) {
17851     // Try to use bit rotation instructions.
17852     if (SDValue Rotate =
17853             lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
17854       return Rotate;
17855 
17856     // Try to produce a fixed cross-128-bit lane permute followed by unpack
17857     // because that should be faster than the variable permute alternatives.
17858     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, Mask, V1, V2, DAG))
17859       return V;
17860 
17861     // There are no generalized cross-lane shuffle operations available on i16
17862     // element types.
17863     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
17864       if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17865               DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17866         return V;
17867 
17868       return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
17869                                                  DAG, Subtarget);
17870     }
17871 
17872     SmallVector<int, 8> RepeatedMask;
17873     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
17874       // As this is a single-input shuffle, the repeated mask should be
17875       // a strictly valid v8i16 mask that we can pass through to the v8i16
17876       // lowering to handle even the v16 case.
17877       return lowerV8I16GeneralSingleInputShuffle(
17878           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
17879     }
17880   }
17881 
17882   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
17883                                               Zeroable, Subtarget, DAG))
17884     return PSHUFB;
17885 
17886   // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
17887   if (Subtarget.hasBWI())
17888     return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
17889 
17890   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17891   // shuffle.
17892   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17893           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17894     return Result;
17895 
17896   // Try to permute the lanes and then use a per-lane permute.
17897   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17898           DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17899     return V;
17900 
17901   // Otherwise fall back on generic lowering.
17902   return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
17903                                     Subtarget, DAG);
17904 }
17905 
17906 /// Handle lowering of 32-lane 8-bit integer shuffles.
17907 ///
17908 /// This routine is only called when we have AVX2 and thus a reasonable
17909 /// instruction set for v32i8 shuffling..
17910 static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17911                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17912                                  const X86Subtarget &Subtarget,
17913                                  SelectionDAG &DAG) {
17914   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17915   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17916   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
17917   assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
17918 
17919   // Whenever we can lower this as a zext, that instruction is strictly faster
17920   // than any alternative. It also allows us to fold memory operands into the
17921   // shuffle in many cases.
17922   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
17923                                                    Zeroable, Subtarget, DAG))
17924     return ZExt;
17925 
17926   // Check for being able to broadcast a single element.
17927   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
17928                                                   Subtarget, DAG))
17929     return Broadcast;
17930 
17931   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
17932                                           Zeroable, Subtarget, DAG))
17933     return Blend;
17934 
17935   // Use dedicated unpack instructions for masks that match their pattern.
17936   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
17937     return V;
17938 
17939   // Use dedicated pack instructions for masks that match their pattern.
17940   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
17941                                        Subtarget))
17942     return V;
17943 
17944   // Try to use lower using a truncation.
17945   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17946                                        Subtarget, DAG))
17947     return V;
17948 
17949   // Try to use shift instructions.
17950   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
17951                                           Zeroable, Subtarget, DAG))
17952     return Shift;
17953 
17954   // Try to use byte rotation instructions.
17955   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
17956                                                 Subtarget, DAG))
17957     return Rotate;
17958 
17959   // Try to use bit rotation instructions.
17960   if (V2.isUndef())
17961     if (SDValue Rotate =
17962             lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
17963       return Rotate;
17964 
17965   // Try to create an in-lane repeating shuffle mask and then shuffle the
17966   // results into the target lanes.
17967   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17968           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17969     return V;
17970 
17971   // There are no generalized cross-lane shuffle operations available on i8
17972   // element types.
17973   if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
17974     // Try to produce a fixed cross-128-bit lane permute followed by unpack
17975     // because that should be faster than the variable permute alternatives.
17976     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, Mask, V1, V2, DAG))
17977       return V;
17978 
17979     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17980             DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17981       return V;
17982 
17983     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
17984                                                DAG, Subtarget);
17985   }
17986 
17987   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
17988                                               Zeroable, Subtarget, DAG))
17989     return PSHUFB;
17990 
17991   // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
17992   if (Subtarget.hasVBMI())
17993     return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
17994 
17995   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17996   // shuffle.
17997   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17998           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17999     return Result;
18000 
18001   // Try to permute the lanes and then use a per-lane permute.
18002   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
18003           DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
18004     return V;
18005 
18006   // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
18007   // by zeroable elements in the remaining 24 elements. Turn this into two
18008   // vmovqb instructions shuffled together.
18009   if (Subtarget.hasVLX())
18010     if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
18011                                                   Mask, Zeroable, DAG))
18012       return V;
18013 
18014   // Otherwise fall back on generic lowering.
18015   return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
18016                                     Subtarget, DAG);
18017 }
18018 
18019 /// High-level routine to lower various 256-bit x86 vector shuffles.
18020 ///
18021 /// This routine either breaks down the specific type of a 256-bit x86 vector
18022 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
18023 /// together based on the available instructions.
18024 static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
18025                                   SDValue V1, SDValue V2, const APInt &Zeroable,
18026                                   const X86Subtarget &Subtarget,
18027                                   SelectionDAG &DAG) {
18028   // If we have a single input to the zero element, insert that into V1 if we
18029   // can do so cheaply.
18030   int NumElts = VT.getVectorNumElements();
18031   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18032 
18033   if (NumV2Elements == 1 && Mask[0] >= NumElts)
18034     if (SDValue Insertion = lowerShuffleAsElementInsertion(
18035             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
18036       return Insertion;
18037 
18038   // Handle special cases where the lower or upper half is UNDEF.
18039   if (SDValue V =
18040           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
18041     return V;
18042 
18043   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
18044   // can check for those subtargets here and avoid much of the subtarget
18045   // querying in the per-vector-type lowering routines. With AVX1 we have
18046   // essentially *zero* ability to manipulate a 256-bit vector with integer
18047   // types. Since we'll use floating point types there eventually, just
18048   // immediately cast everything to a float and operate entirely in that domain.
18049   if (VT.isInteger() && !Subtarget.hasAVX2()) {
18050     int ElementBits = VT.getScalarSizeInBits();
18051     if (ElementBits < 32) {
18052       // No floating point type available, if we can't use the bit operations
18053       // for masking/blending then decompose into 128-bit vectors.
18054       if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
18055                                             Subtarget, DAG))
18056         return V;
18057       if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
18058         return V;
18059       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
18060     }
18061 
18062     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
18063                                 VT.getVectorNumElements());
18064     V1 = DAG.getBitcast(FpVT, V1);
18065     V2 = DAG.getBitcast(FpVT, V2);
18066     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
18067   }
18068 
18069   if (VT == MVT::v16f16) {
18070     V1 = DAG.getBitcast(MVT::v16i16, V1);
18071     V2 = DAG.getBitcast(MVT::v16i16, V2);
18072     return DAG.getBitcast(MVT::v16f16,
18073                           DAG.getVectorShuffle(MVT::v16i16, DL, V1, V2, Mask));
18074   }
18075 
18076   switch (VT.SimpleTy) {
18077   case MVT::v4f64:
18078     return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18079   case MVT::v4i64:
18080     return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18081   case MVT::v8f32:
18082     return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18083   case MVT::v8i32:
18084     return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18085   case MVT::v16i16:
18086     return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18087   case MVT::v32i8:
18088     return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18089 
18090   default:
18091     llvm_unreachable("Not a valid 256-bit x86 vector type!");
18092   }
18093 }
18094 
18095 /// Try to lower a vector shuffle as a 128-bit shuffles.
18096 static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
18097                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18098                                   const X86Subtarget &Subtarget,
18099                                   SelectionDAG &DAG) {
18100   assert(VT.getScalarSizeInBits() == 64 &&
18101          "Unexpected element type size for 128bit shuffle.");
18102 
18103   // To handle 256 bit vector requires VLX and most probably
18104   // function lowerV2X128VectorShuffle() is better solution.
18105   assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
18106 
18107   // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
18108   SmallVector<int, 4> Widened128Mask;
18109   if (!canWidenShuffleElements(Mask, Widened128Mask))
18110     return SDValue();
18111   assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
18112 
18113   // Try to use an insert into a zero vector.
18114   if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
18115       (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
18116     unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
18117     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
18118     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
18119                               DAG.getIntPtrConstant(0, DL));
18120     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
18121                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
18122                        DAG.getIntPtrConstant(0, DL));
18123   }
18124 
18125   // Check for patterns which can be matched with a single insert of a 256-bit
18126   // subvector.
18127   bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
18128   if (OnlyUsesV1 ||
18129       isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
18130     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
18131     SDValue SubVec =
18132         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
18133                     DAG.getIntPtrConstant(0, DL));
18134     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
18135                        DAG.getIntPtrConstant(4, DL));
18136   }
18137 
18138   // See if this is an insertion of the lower 128-bits of V2 into V1.
18139   bool IsInsert = true;
18140   int V2Index = -1;
18141   for (int i = 0; i < 4; ++i) {
18142     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
18143     if (Widened128Mask[i] < 0)
18144       continue;
18145 
18146     // Make sure all V1 subvectors are in place.
18147     if (Widened128Mask[i] < 4) {
18148       if (Widened128Mask[i] != i) {
18149         IsInsert = false;
18150         break;
18151       }
18152     } else {
18153       // Make sure we only have a single V2 index and its the lowest 128-bits.
18154       if (V2Index >= 0 || Widened128Mask[i] != 4) {
18155         IsInsert = false;
18156         break;
18157       }
18158       V2Index = i;
18159     }
18160   }
18161   if (IsInsert && V2Index >= 0) {
18162     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
18163     SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
18164                                  DAG.getIntPtrConstant(0, DL));
18165     return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
18166   }
18167 
18168   // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
18169   // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
18170   // possible we at least ensure the lanes stay sequential to help later
18171   // combines.
18172   SmallVector<int, 2> Widened256Mask;
18173   if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
18174     Widened128Mask.clear();
18175     narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
18176   }
18177 
18178   // Try to lower to vshuf64x2/vshuf32x4.
18179   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
18180   unsigned PermMask = 0;
18181   // Insure elements came from the same Op.
18182   for (int i = 0; i < 4; ++i) {
18183     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
18184     if (Widened128Mask[i] < 0)
18185       continue;
18186 
18187     SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
18188     unsigned OpIndex = i / 2;
18189     if (Ops[OpIndex].isUndef())
18190       Ops[OpIndex] = Op;
18191     else if (Ops[OpIndex] != Op)
18192       return SDValue();
18193 
18194     // Convert the 128-bit shuffle mask selection values into 128-bit selection
18195     // bits defined by a vshuf64x2 instruction's immediate control byte.
18196     PermMask |= (Widened128Mask[i] % 4) << (i * 2);
18197   }
18198 
18199   return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
18200                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
18201 }
18202 
18203 /// Handle lowering of 8-lane 64-bit floating point shuffles.
18204 static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18205                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18206                                  const X86Subtarget &Subtarget,
18207                                  SelectionDAG &DAG) {
18208   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
18209   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
18210   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
18211 
18212   if (V2.isUndef()) {
18213     // Use low duplicate instructions for masks that match their pattern.
18214     if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
18215       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
18216 
18217     if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
18218       // Non-half-crossing single input shuffles can be lowered with an
18219       // interleaved permutation.
18220       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
18221                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
18222                               ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
18223                               ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
18224       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
18225                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
18226     }
18227 
18228     SmallVector<int, 4> RepeatedMask;
18229     if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
18230       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
18231                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18232   }
18233 
18234   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
18235                                            V2, Subtarget, DAG))
18236     return Shuf128;
18237 
18238   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
18239     return Unpck;
18240 
18241   // Check if the blend happens to exactly fit that of SHUFPD.
18242   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
18243                                           Zeroable, Subtarget, DAG))
18244     return Op;
18245 
18246   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
18247                                        DAG, Subtarget))
18248     return V;
18249 
18250   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
18251                                           Zeroable, Subtarget, DAG))
18252     return Blend;
18253 
18254   return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
18255 }
18256 
18257 /// Handle lowering of 16-lane 32-bit floating point shuffles.
18258 static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18259                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18260                                   const X86Subtarget &Subtarget,
18261                                   SelectionDAG &DAG) {
18262   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
18263   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
18264   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
18265 
18266   // If the shuffle mask is repeated in each 128-bit lane, we have many more
18267   // options to efficiently lower the shuffle.
18268   SmallVector<int, 4> RepeatedMask;
18269   if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
18270     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
18271 
18272     // Use even/odd duplicate instructions for masks that match their pattern.
18273     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
18274       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
18275     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
18276       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
18277 
18278     if (V2.isUndef())
18279       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
18280                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18281 
18282     // Use dedicated unpack instructions for masks that match their pattern.
18283     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
18284       return V;
18285 
18286     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
18287                                             Zeroable, Subtarget, DAG))
18288       return Blend;
18289 
18290     // Otherwise, fall back to a SHUFPS sequence.
18291     return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
18292   }
18293 
18294   // Try to create an in-lane repeating shuffle mask and then shuffle the
18295   // results into the target lanes.
18296   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18297           DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
18298     return V;
18299 
18300   // If we have a single input shuffle with different shuffle patterns in the
18301   // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
18302   if (V2.isUndef() &&
18303       !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
18304     SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
18305     return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
18306   }
18307 
18308   // If we have AVX512F support, we can use VEXPAND.
18309   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
18310                                              V1, V2, DAG, Subtarget))
18311     return V;
18312 
18313   return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
18314 }
18315 
18316 /// Handle lowering of 8-lane 64-bit integer shuffles.
18317 static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18318                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18319                                  const X86Subtarget &Subtarget,
18320                                  SelectionDAG &DAG) {
18321   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
18322   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
18323   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
18324 
18325   if (V2.isUndef()) {
18326     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
18327     // can use lower latency instructions that will operate on all four
18328     // 128-bit lanes.
18329     SmallVector<int, 2> Repeated128Mask;
18330     if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
18331       SmallVector<int, 4> PSHUFDMask;
18332       narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
18333       return DAG.getBitcast(
18334           MVT::v8i64,
18335           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
18336                       DAG.getBitcast(MVT::v16i32, V1),
18337                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
18338     }
18339 
18340     SmallVector<int, 4> Repeated256Mask;
18341     if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
18342       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
18343                          getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
18344   }
18345 
18346   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
18347                                            V2, Subtarget, DAG))
18348     return Shuf128;
18349 
18350   // Try to use shift instructions.
18351   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
18352                                           Zeroable, Subtarget, DAG))
18353     return Shift;
18354 
18355   // Try to use VALIGN.
18356   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
18357                                             Subtarget, DAG))
18358     return Rotate;
18359 
18360   // Try to use PALIGNR.
18361   if (Subtarget.hasBWI())
18362     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
18363                                                   Subtarget, DAG))
18364       return Rotate;
18365 
18366   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
18367     return Unpck;
18368 
18369   // If we have AVX512F support, we can use VEXPAND.
18370   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
18371                                        DAG, Subtarget))
18372     return V;
18373 
18374   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
18375                                           Zeroable, Subtarget, DAG))
18376     return Blend;
18377 
18378   return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
18379 }
18380 
18381 /// Handle lowering of 16-lane 32-bit integer shuffles.
18382 static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18383                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18384                                   const X86Subtarget &Subtarget,
18385                                   SelectionDAG &DAG) {
18386   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
18387   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
18388   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
18389 
18390   // Whenever we can lower this as a zext, that instruction is strictly faster
18391   // than any alternative. It also allows us to fold memory operands into the
18392   // shuffle in many cases.
18393   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18394           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
18395     return ZExt;
18396 
18397   // If the shuffle mask is repeated in each 128-bit lane we can use more
18398   // efficient instructions that mirror the shuffles across the four 128-bit
18399   // lanes.
18400   SmallVector<int, 4> RepeatedMask;
18401   bool Is128BitLaneRepeatedShuffle =
18402       is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
18403   if (Is128BitLaneRepeatedShuffle) {
18404     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
18405     if (V2.isUndef())
18406       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
18407                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
18408 
18409     // Use dedicated unpack instructions for masks that match their pattern.
18410     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
18411       return V;
18412   }
18413 
18414   // Try to use shift instructions.
18415   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
18416                                           Zeroable, Subtarget, DAG))
18417     return Shift;
18418 
18419   // Try to use VALIGN.
18420   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
18421                                             Subtarget, DAG))
18422     return Rotate;
18423 
18424   // Try to use byte rotation instructions.
18425   if (Subtarget.hasBWI())
18426     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
18427                                                   Subtarget, DAG))
18428       return Rotate;
18429 
18430   // Assume that a single SHUFPS is faster than using a permv shuffle.
18431   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
18432   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
18433     SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
18434     SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
18435     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
18436                                             CastV1, CastV2, DAG);
18437     return DAG.getBitcast(MVT::v16i32, ShufPS);
18438   }
18439 
18440   // Try to create an in-lane repeating shuffle mask and then shuffle the
18441   // results into the target lanes.
18442   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18443           DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
18444     return V;
18445 
18446   // If we have AVX512F support, we can use VEXPAND.
18447   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
18448                                        DAG, Subtarget))
18449     return V;
18450 
18451   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
18452                                           Zeroable, Subtarget, DAG))
18453     return Blend;
18454 
18455   return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
18456 }
18457 
18458 /// Handle lowering of 32-lane 16-bit integer shuffles.
18459 static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18460                                   const APInt &Zeroable, SDValue V1, SDValue V2,
18461                                   const X86Subtarget &Subtarget,
18462                                   SelectionDAG &DAG) {
18463   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18464   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18465   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
18466   assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
18467 
18468   // Whenever we can lower this as a zext, that instruction is strictly faster
18469   // than any alternative. It also allows us to fold memory operands into the
18470   // shuffle in many cases.
18471   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18472           DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
18473     return ZExt;
18474 
18475   // Use dedicated unpack instructions for masks that match their pattern.
18476   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
18477     return V;
18478 
18479   // Use dedicated pack instructions for masks that match their pattern.
18480   if (SDValue V =
18481           lowerShuffleWithPACK(DL, MVT::v32i16, Mask, V1, V2, DAG, Subtarget))
18482     return V;
18483 
18484   // Try to use shift instructions.
18485   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
18486                                           Zeroable, Subtarget, DAG))
18487     return Shift;
18488 
18489   // Try to use byte rotation instructions.
18490   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
18491                                                 Subtarget, DAG))
18492     return Rotate;
18493 
18494   if (V2.isUndef()) {
18495     // Try to use bit rotation instructions.
18496     if (SDValue Rotate =
18497             lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
18498       return Rotate;
18499 
18500     SmallVector<int, 8> RepeatedMask;
18501     if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
18502       // As this is a single-input shuffle, the repeated mask should be
18503       // a strictly valid v8i16 mask that we can pass through to the v8i16
18504       // lowering to handle even the v32 case.
18505       return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
18506                                                  RepeatedMask, Subtarget, DAG);
18507     }
18508   }
18509 
18510   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
18511                                           Zeroable, Subtarget, DAG))
18512     return Blend;
18513 
18514   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
18515                                               Zeroable, Subtarget, DAG))
18516     return PSHUFB;
18517 
18518   return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
18519 }
18520 
18521 /// Handle lowering of 64-lane 8-bit integer shuffles.
18522 static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18523                                  const APInt &Zeroable, SDValue V1, SDValue V2,
18524                                  const X86Subtarget &Subtarget,
18525                                  SelectionDAG &DAG) {
18526   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18527   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18528   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
18529   assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
18530 
18531   // Whenever we can lower this as a zext, that instruction is strictly faster
18532   // than any alternative. It also allows us to fold memory operands into the
18533   // shuffle in many cases.
18534   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18535           DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
18536     return ZExt;
18537 
18538   // Use dedicated unpack instructions for masks that match their pattern.
18539   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
18540     return V;
18541 
18542   // Use dedicated pack instructions for masks that match their pattern.
18543   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
18544                                        Subtarget))
18545     return V;
18546 
18547   // Try to use shift instructions.
18548   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
18549                                           Zeroable, Subtarget, DAG))
18550     return Shift;
18551 
18552   // Try to use byte rotation instructions.
18553   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
18554                                                 Subtarget, DAG))
18555     return Rotate;
18556 
18557   // Try to use bit rotation instructions.
18558   if (V2.isUndef())
18559     if (SDValue Rotate =
18560             lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
18561       return Rotate;
18562 
18563   // Lower as AND if possible.
18564   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask,
18565                                              Zeroable, Subtarget, DAG))
18566     return Masked;
18567 
18568   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
18569                                               Zeroable, Subtarget, DAG))
18570     return PSHUFB;
18571 
18572   // VBMI can use VPERMV/VPERMV3 byte shuffles.
18573   if (Subtarget.hasVBMI())
18574     return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
18575 
18576   // Try to create an in-lane repeating shuffle mask and then shuffle the
18577   // results into the target lanes.
18578   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18579           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18580     return V;
18581 
18582   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
18583                                           Zeroable, Subtarget, DAG))
18584     return Blend;
18585 
18586   // Try to simplify this by merging 128-bit lanes to enable a lane-based
18587   // shuffle.
18588   if (!V2.isUndef())
18589     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18590             DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18591       return Result;
18592 
18593   // FIXME: Implement direct support for this type!
18594   return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
18595 }
18596 
18597 /// High-level routine to lower various 512-bit x86 vector shuffles.
18598 ///
18599 /// This routine either breaks down the specific type of a 512-bit x86 vector
18600 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
18601 /// together based on the available instructions.
18602 static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
18603                                   MVT VT, SDValue V1, SDValue V2,
18604                                   const APInt &Zeroable,
18605                                   const X86Subtarget &Subtarget,
18606                                   SelectionDAG &DAG) {
18607   assert(Subtarget.hasAVX512() &&
18608          "Cannot lower 512-bit vectors w/ basic ISA!");
18609 
18610   // If we have a single input to the zero element, insert that into V1 if we
18611   // can do so cheaply.
18612   int NumElts = Mask.size();
18613   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18614 
18615   if (NumV2Elements == 1 && Mask[0] >= NumElts)
18616     if (SDValue Insertion = lowerShuffleAsElementInsertion(
18617             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
18618       return Insertion;
18619 
18620   // Handle special cases where the lower or upper half is UNDEF.
18621   if (SDValue V =
18622           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
18623     return V;
18624 
18625   // Check for being able to broadcast a single element.
18626   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
18627                                                   Subtarget, DAG))
18628     return Broadcast;
18629 
18630   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
18631     // Try using bit ops for masking and blending before falling back to
18632     // splitting.
18633     if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
18634                                           Subtarget, DAG))
18635       return V;
18636     if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
18637       return V;
18638 
18639     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
18640   }
18641 
18642   if (VT == MVT::v32f16) {
18643     V1 = DAG.getBitcast(MVT::v32i16, V1);
18644     V2 = DAG.getBitcast(MVT::v32i16, V2);
18645     return DAG.getBitcast(MVT::v32f16,
18646                           DAG.getVectorShuffle(MVT::v32i16, DL, V1, V2, Mask));
18647   }
18648 
18649   // Dispatch to each element type for lowering. If we don't have support for
18650   // specific element type shuffles at 512 bits, immediately split them and
18651   // lower them. Each lowering routine of a given type is allowed to assume that
18652   // the requisite ISA extensions for that element type are available.
18653   switch (VT.SimpleTy) {
18654   case MVT::v8f64:
18655     return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18656   case MVT::v16f32:
18657     return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18658   case MVT::v8i64:
18659     return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18660   case MVT::v16i32:
18661     return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18662   case MVT::v32i16:
18663     return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18664   case MVT::v64i8:
18665     return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18666 
18667   default:
18668     llvm_unreachable("Not a valid 512-bit x86 vector type!");
18669   }
18670 }
18671 
18672 static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
18673                                          MVT VT, SDValue V1, SDValue V2,
18674                                          const X86Subtarget &Subtarget,
18675                                          SelectionDAG &DAG) {
18676   // Shuffle should be unary.
18677   if (!V2.isUndef())
18678     return SDValue();
18679 
18680   int ShiftAmt = -1;
18681   int NumElts = Mask.size();
18682   for (int i = 0; i != NumElts; ++i) {
18683     int M = Mask[i];
18684     assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
18685            "Unexpected mask index.");
18686     if (M < 0)
18687       continue;
18688 
18689     // The first non-undef element determines our shift amount.
18690     if (ShiftAmt < 0) {
18691       ShiftAmt = M - i;
18692       // Need to be shifting right.
18693       if (ShiftAmt <= 0)
18694         return SDValue();
18695     }
18696     // All non-undef elements must shift by the same amount.
18697     if (ShiftAmt != M - i)
18698       return SDValue();
18699   }
18700   assert(ShiftAmt >= 0 && "All undef?");
18701 
18702   // Great we found a shift right.
18703   MVT WideVT = VT;
18704   if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
18705     WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18706   SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
18707                             DAG.getUNDEF(WideVT), V1,
18708                             DAG.getIntPtrConstant(0, DL));
18709   Res = DAG.getNode(X86ISD::KSHIFTR, DL, WideVT, Res,
18710                     DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18711   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18712                      DAG.getIntPtrConstant(0, DL));
18713 }
18714 
18715 // Determine if this shuffle can be implemented with a KSHIFT instruction.
18716 // Returns the shift amount if possible or -1 if not. This is a simplified
18717 // version of matchShuffleAsShift.
18718 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
18719                                     int MaskOffset, const APInt &Zeroable) {
18720   int Size = Mask.size();
18721 
18722   auto CheckZeros = [&](int Shift, bool Left) {
18723     for (int j = 0; j < Shift; ++j)
18724       if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
18725         return false;
18726 
18727     return true;
18728   };
18729 
18730   auto MatchShift = [&](int Shift, bool Left) {
18731     unsigned Pos = Left ? Shift : 0;
18732     unsigned Low = Left ? 0 : Shift;
18733     unsigned Len = Size - Shift;
18734     return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
18735   };
18736 
18737   for (int Shift = 1; Shift != Size; ++Shift)
18738     for (bool Left : {true, false})
18739       if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
18740         Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
18741         return Shift;
18742       }
18743 
18744   return -1;
18745 }
18746 
18747 
18748 // Lower vXi1 vector shuffles.
18749 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
18750 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
18751 // vector, shuffle and then truncate it back.
18752 static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
18753                                 MVT VT, SDValue V1, SDValue V2,
18754                                 const APInt &Zeroable,
18755                                 const X86Subtarget &Subtarget,
18756                                 SelectionDAG &DAG) {
18757   assert(Subtarget.hasAVX512() &&
18758          "Cannot lower 512-bit vectors w/o basic ISA!");
18759 
18760   int NumElts = Mask.size();
18761 
18762   // Try to recognize shuffles that are just padding a subvector with zeros.
18763   int SubvecElts = 0;
18764   int Src = -1;
18765   for (int i = 0; i != NumElts; ++i) {
18766     if (Mask[i] >= 0) {
18767       // Grab the source from the first valid mask. All subsequent elements need
18768       // to use this same source.
18769       if (Src < 0)
18770         Src = Mask[i] / NumElts;
18771       if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
18772         break;
18773     }
18774 
18775     ++SubvecElts;
18776   }
18777   assert(SubvecElts != NumElts && "Identity shuffle?");
18778 
18779   // Clip to a power 2.
18780   SubvecElts = PowerOf2Floor(SubvecElts);
18781 
18782   // Make sure the number of zeroable bits in the top at least covers the bits
18783   // not covered by the subvector.
18784   if ((int)Zeroable.countLeadingOnes() >= (NumElts - SubvecElts)) {
18785     assert(Src >= 0 && "Expected a source!");
18786     MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
18787     SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
18788                                   Src == 0 ? V1 : V2,
18789                                   DAG.getIntPtrConstant(0, DL));
18790     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
18791                        DAG.getConstant(0, DL, VT),
18792                        Extract, DAG.getIntPtrConstant(0, DL));
18793   }
18794 
18795   // Try a simple shift right with undef elements. Later we'll try with zeros.
18796   if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
18797                                                 DAG))
18798     return Shift;
18799 
18800   // Try to match KSHIFTs.
18801   unsigned Offset = 0;
18802   for (SDValue V : { V1, V2 }) {
18803     unsigned Opcode;
18804     int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
18805     if (ShiftAmt >= 0) {
18806       MVT WideVT = VT;
18807       if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
18808         WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18809       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
18810                                 DAG.getUNDEF(WideVT), V,
18811                                 DAG.getIntPtrConstant(0, DL));
18812       // Widened right shifts need two shifts to ensure we shift in zeroes.
18813       if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
18814         int WideElts = WideVT.getVectorNumElements();
18815         // Shift left to put the original vector in the MSBs of the new size.
18816         Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
18817                           DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
18818         // Increase the shift amount to account for the left shift.
18819         ShiftAmt += WideElts - NumElts;
18820       }
18821 
18822       Res = DAG.getNode(Opcode, DL, WideVT, Res,
18823                         DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18824       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18825                          DAG.getIntPtrConstant(0, DL));
18826     }
18827     Offset += NumElts; // Increment for next iteration.
18828   }
18829 
18830 
18831 
18832   MVT ExtVT;
18833   switch (VT.SimpleTy) {
18834   default:
18835     llvm_unreachable("Expected a vector of i1 elements");
18836   case MVT::v2i1:
18837     ExtVT = MVT::v2i64;
18838     break;
18839   case MVT::v4i1:
18840     ExtVT = MVT::v4i32;
18841     break;
18842   case MVT::v8i1:
18843     // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
18844     // shuffle.
18845     ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
18846     break;
18847   case MVT::v16i1:
18848     // Take 512-bit type, unless we are avoiding 512-bit types and have the
18849     // 256-bit operation available.
18850     ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
18851     break;
18852   case MVT::v32i1:
18853     // Take 512-bit type, unless we are avoiding 512-bit types and have the
18854     // 256-bit operation available.
18855     assert(Subtarget.hasBWI() && "Expected AVX512BW support");
18856     ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
18857     break;
18858   case MVT::v64i1:
18859     // Fall back to scalarization. FIXME: We can do better if the shuffle
18860     // can be partitioned cleanly.
18861     if (!Subtarget.useBWIRegs())
18862       return SDValue();
18863     ExtVT = MVT::v64i8;
18864     break;
18865   }
18866 
18867   V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
18868   V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
18869 
18870   SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
18871   // i1 was sign extended we can use X86ISD::CVT2MASK.
18872   int NumElems = VT.getVectorNumElements();
18873   if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
18874       (Subtarget.hasDQI() && (NumElems < 32)))
18875     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
18876                        Shuffle, ISD::SETGT);
18877 
18878   return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
18879 }
18880 
18881 /// Helper function that returns true if the shuffle mask should be
18882 /// commuted to improve canonicalization.
18883 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
18884   int NumElements = Mask.size();
18885 
18886   int NumV1Elements = 0, NumV2Elements = 0;
18887   for (int M : Mask)
18888     if (M < 0)
18889       continue;
18890     else if (M < NumElements)
18891       ++NumV1Elements;
18892     else
18893       ++NumV2Elements;
18894 
18895   // Commute the shuffle as needed such that more elements come from V1 than
18896   // V2. This allows us to match the shuffle pattern strictly on how many
18897   // elements come from V1 without handling the symmetric cases.
18898   if (NumV2Elements > NumV1Elements)
18899     return true;
18900 
18901   assert(NumV1Elements > 0 && "No V1 indices");
18902 
18903   if (NumV2Elements == 0)
18904     return false;
18905 
18906   // When the number of V1 and V2 elements are the same, try to minimize the
18907   // number of uses of V2 in the low half of the vector. When that is tied,
18908   // ensure that the sum of indices for V1 is equal to or lower than the sum
18909   // indices for V2. When those are equal, try to ensure that the number of odd
18910   // indices for V1 is lower than the number of odd indices for V2.
18911   if (NumV1Elements == NumV2Elements) {
18912     int LowV1Elements = 0, LowV2Elements = 0;
18913     for (int M : Mask.slice(0, NumElements / 2))
18914       if (M >= NumElements)
18915         ++LowV2Elements;
18916       else if (M >= 0)
18917         ++LowV1Elements;
18918     if (LowV2Elements > LowV1Elements)
18919       return true;
18920     if (LowV2Elements == LowV1Elements) {
18921       int SumV1Indices = 0, SumV2Indices = 0;
18922       for (int i = 0, Size = Mask.size(); i < Size; ++i)
18923         if (Mask[i] >= NumElements)
18924           SumV2Indices += i;
18925         else if (Mask[i] >= 0)
18926           SumV1Indices += i;
18927       if (SumV2Indices < SumV1Indices)
18928         return true;
18929       if (SumV2Indices == SumV1Indices) {
18930         int NumV1OddIndices = 0, NumV2OddIndices = 0;
18931         for (int i = 0, Size = Mask.size(); i < Size; ++i)
18932           if (Mask[i] >= NumElements)
18933             NumV2OddIndices += i % 2;
18934           else if (Mask[i] >= 0)
18935             NumV1OddIndices += i % 2;
18936         if (NumV2OddIndices < NumV1OddIndices)
18937           return true;
18938       }
18939     }
18940   }
18941 
18942   return false;
18943 }
18944 
18945 // Forward declaration.
18946 static SDValue canonicalizeShuffleMaskWithHorizOp(
18947     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
18948     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
18949     const X86Subtarget &Subtarget);
18950 
18951     /// Top-level lowering for x86 vector shuffles.
18952 ///
18953 /// This handles decomposition, canonicalization, and lowering of all x86
18954 /// vector shuffles. Most of the specific lowering strategies are encapsulated
18955 /// above in helper routines. The canonicalization attempts to widen shuffles
18956 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
18957 /// s.t. only one of the two inputs needs to be tested, etc.
18958 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
18959                                    SelectionDAG &DAG) {
18960   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
18961   ArrayRef<int> OrigMask = SVOp->getMask();
18962   SDValue V1 = Op.getOperand(0);
18963   SDValue V2 = Op.getOperand(1);
18964   MVT VT = Op.getSimpleValueType();
18965   int NumElements = VT.getVectorNumElements();
18966   SDLoc DL(Op);
18967   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
18968 
18969   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
18970          "Can't lower MMX shuffles");
18971 
18972   bool V1IsUndef = V1.isUndef();
18973   bool V2IsUndef = V2.isUndef();
18974   if (V1IsUndef && V2IsUndef)
18975     return DAG.getUNDEF(VT);
18976 
18977   // When we create a shuffle node we put the UNDEF node to second operand,
18978   // but in some cases the first operand may be transformed to UNDEF.
18979   // In this case we should just commute the node.
18980   if (V1IsUndef)
18981     return DAG.getCommutedVectorShuffle(*SVOp);
18982 
18983   // Check for non-undef masks pointing at an undef vector and make the masks
18984   // undef as well. This makes it easier to match the shuffle based solely on
18985   // the mask.
18986   if (V2IsUndef &&
18987       any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
18988     SmallVector<int, 8> NewMask(OrigMask.begin(), OrigMask.end());
18989     for (int &M : NewMask)
18990       if (M >= NumElements)
18991         M = -1;
18992     return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
18993   }
18994 
18995   // Check for illegal shuffle mask element index values.
18996   int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
18997   (void)MaskUpperLimit;
18998   assert(llvm::all_of(OrigMask,
18999                       [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
19000          "Out of bounds shuffle index");
19001 
19002   // We actually see shuffles that are entirely re-arrangements of a set of
19003   // zero inputs. This mostly happens while decomposing complex shuffles into
19004   // simple ones. Directly lower these as a buildvector of zeros.
19005   APInt KnownUndef, KnownZero;
19006   computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
19007 
19008   APInt Zeroable = KnownUndef | KnownZero;
19009   if (Zeroable.isAllOnes())
19010     return getZeroVector(VT, Subtarget, DAG, DL);
19011 
19012   bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
19013 
19014   // Try to collapse shuffles into using a vector type with fewer elements but
19015   // wider element types. We cap this to not form integers or floating point
19016   // elements wider than 64 bits. It does not seem beneficial to form i128
19017   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
19018   SmallVector<int, 16> WidenedMask;
19019   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
19020       canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
19021     // Shuffle mask widening should not interfere with a broadcast opportunity
19022     // by obfuscating the operands with bitcasts.
19023     // TODO: Avoid lowering directly from this top-level function: make this
19024     // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
19025     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
19026                                                     Subtarget, DAG))
19027       return Broadcast;
19028 
19029     MVT NewEltVT = VT.isFloatingPoint()
19030                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
19031                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
19032     int NewNumElts = NumElements / 2;
19033     MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
19034     // Make sure that the new vector type is legal. For example, v2f64 isn't
19035     // legal on SSE1.
19036     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
19037       if (V2IsZero) {
19038         // Modify the new Mask to take all zeros from the all-zero vector.
19039         // Choose indices that are blend-friendly.
19040         bool UsedZeroVector = false;
19041         assert(is_contained(WidenedMask, SM_SentinelZero) &&
19042                "V2's non-undef elements are used?!");
19043         for (int i = 0; i != NewNumElts; ++i)
19044           if (WidenedMask[i] == SM_SentinelZero) {
19045             WidenedMask[i] = i + NewNumElts;
19046             UsedZeroVector = true;
19047           }
19048         // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
19049         // some elements to be undef.
19050         if (UsedZeroVector)
19051           V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
19052       }
19053       V1 = DAG.getBitcast(NewVT, V1);
19054       V2 = DAG.getBitcast(NewVT, V2);
19055       return DAG.getBitcast(
19056           VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
19057     }
19058   }
19059 
19060   SmallVector<SDValue> Ops = {V1, V2};
19061   SmallVector<int> Mask(OrigMask.begin(), OrigMask.end());
19062 
19063   // Canonicalize the shuffle with any horizontal ops inputs.
19064   // NOTE: This may update Ops and Mask.
19065   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
19066           Ops, Mask, VT.getSizeInBits(), DL, DAG, Subtarget))
19067     return DAG.getBitcast(VT, HOp);
19068 
19069   V1 = DAG.getBitcast(VT, Ops[0]);
19070   V2 = DAG.getBitcast(VT, Ops[1]);
19071   assert(NumElements == (int)Mask.size() &&
19072          "canonicalizeShuffleMaskWithHorizOp "
19073          "shouldn't alter the shuffle mask size");
19074 
19075   // Commute the shuffle if it will improve canonicalization.
19076   if (canonicalizeShuffleMaskWithCommute(Mask)) {
19077     ShuffleVectorSDNode::commuteMask(Mask);
19078     std::swap(V1, V2);
19079   }
19080 
19081   // For each vector width, delegate to a specialized lowering routine.
19082   if (VT.is128BitVector())
19083     return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
19084 
19085   if (VT.is256BitVector())
19086     return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
19087 
19088   if (VT.is512BitVector())
19089     return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
19090 
19091   if (Is1BitVector)
19092     return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
19093 
19094   llvm_unreachable("Unimplemented!");
19095 }
19096 
19097 /// Try to lower a VSELECT instruction to a vector shuffle.
19098 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
19099                                            const X86Subtarget &Subtarget,
19100                                            SelectionDAG &DAG) {
19101   SDValue Cond = Op.getOperand(0);
19102   SDValue LHS = Op.getOperand(1);
19103   SDValue RHS = Op.getOperand(2);
19104   MVT VT = Op.getSimpleValueType();
19105 
19106   // Only non-legal VSELECTs reach this lowering, convert those into generic
19107   // shuffles and re-use the shuffle lowering path for blends.
19108   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
19109     SmallVector<int, 32> Mask;
19110     if (createShuffleMaskFromVSELECT(Mask, Cond))
19111       return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
19112   }
19113 
19114   return SDValue();
19115 }
19116 
19117 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
19118   SDValue Cond = Op.getOperand(0);
19119   SDValue LHS = Op.getOperand(1);
19120   SDValue RHS = Op.getOperand(2);
19121 
19122   // A vselect where all conditions and data are constants can be optimized into
19123   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
19124   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
19125       ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
19126       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
19127     return SDValue();
19128 
19129   // Try to lower this to a blend-style vector shuffle. This can handle all
19130   // constant condition cases.
19131   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
19132     return BlendOp;
19133 
19134   // If this VSELECT has a vector if i1 as a mask, it will be directly matched
19135   // with patterns on the mask registers on AVX-512.
19136   MVT CondVT = Cond.getSimpleValueType();
19137   unsigned CondEltSize = Cond.getScalarValueSizeInBits();
19138   if (CondEltSize == 1)
19139     return Op;
19140 
19141   // Variable blends are only legal from SSE4.1 onward.
19142   if (!Subtarget.hasSSE41())
19143     return SDValue();
19144 
19145   SDLoc dl(Op);
19146   MVT VT = Op.getSimpleValueType();
19147   unsigned EltSize = VT.getScalarSizeInBits();
19148   unsigned NumElts = VT.getVectorNumElements();
19149 
19150   // Expand v32i16/v64i8 without BWI.
19151   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
19152     return SDValue();
19153 
19154   // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
19155   // into an i1 condition so that we can use the mask-based 512-bit blend
19156   // instructions.
19157   if (VT.getSizeInBits() == 512) {
19158     // Build a mask by testing the condition against zero.
19159     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
19160     SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
19161                                 DAG.getConstant(0, dl, CondVT),
19162                                 ISD::SETNE);
19163     // Now return a new VSELECT using the mask.
19164     return DAG.getSelect(dl, VT, Mask, LHS, RHS);
19165   }
19166 
19167   // SEXT/TRUNC cases where the mask doesn't match the destination size.
19168   if (CondEltSize != EltSize) {
19169     // If we don't have a sign splat, rely on the expansion.
19170     if (CondEltSize != DAG.ComputeNumSignBits(Cond))
19171       return SDValue();
19172 
19173     MVT NewCondSVT = MVT::getIntegerVT(EltSize);
19174     MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
19175     Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
19176     return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
19177   }
19178 
19179   // Only some types will be legal on some subtargets. If we can emit a legal
19180   // VSELECT-matching blend, return Op, and but if we need to expand, return
19181   // a null value.
19182   switch (VT.SimpleTy) {
19183   default:
19184     // Most of the vector types have blends past SSE4.1.
19185     return Op;
19186 
19187   case MVT::v32i8:
19188     // The byte blends for AVX vectors were introduced only in AVX2.
19189     if (Subtarget.hasAVX2())
19190       return Op;
19191 
19192     return SDValue();
19193 
19194   case MVT::v8i16:
19195   case MVT::v16i16: {
19196     // Bitcast everything to the vXi8 type and use a vXi8 vselect.
19197     MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
19198     Cond = DAG.getBitcast(CastVT, Cond);
19199     LHS = DAG.getBitcast(CastVT, LHS);
19200     RHS = DAG.getBitcast(CastVT, RHS);
19201     SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
19202     return DAG.getBitcast(VT, Select);
19203   }
19204   }
19205 }
19206 
19207 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
19208   MVT VT = Op.getSimpleValueType();
19209   SDValue Vec = Op.getOperand(0);
19210   SDValue Idx = Op.getOperand(1);
19211   assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
19212   SDLoc dl(Op);
19213 
19214   if (!Vec.getSimpleValueType().is128BitVector())
19215     return SDValue();
19216 
19217   if (VT.getSizeInBits() == 8) {
19218     // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
19219     // we're going to zero extend the register or fold the store.
19220     if (llvm::isNullConstant(Idx) && !X86::mayFoldIntoZeroExtend(Op) &&
19221         !X86::mayFoldIntoStore(Op))
19222       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
19223                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19224                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
19225 
19226     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
19227     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
19228                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19229     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19230   }
19231 
19232   if (VT == MVT::f32) {
19233     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
19234     // the result back to FR32 register. It's only worth matching if the
19235     // result has a single use which is a store or a bitcast to i32.  And in
19236     // the case of a store, it's not worth it if the index is a constant 0,
19237     // because a MOVSSmr can be used instead, which is smaller and faster.
19238     if (!Op.hasOneUse())
19239       return SDValue();
19240     SDNode *User = *Op.getNode()->use_begin();
19241     if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
19242         (User->getOpcode() != ISD::BITCAST ||
19243          User->getValueType(0) != MVT::i32))
19244       return SDValue();
19245     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19246                                   DAG.getBitcast(MVT::v4i32, Vec), Idx);
19247     return DAG.getBitcast(MVT::f32, Extract);
19248   }
19249 
19250   if (VT == MVT::i32 || VT == MVT::i64)
19251       return Op;
19252 
19253   return SDValue();
19254 }
19255 
19256 /// Extract one bit from mask vector, like v16i1 or v8i1.
19257 /// AVX-512 feature.
19258 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
19259                                         const X86Subtarget &Subtarget) {
19260   SDValue Vec = Op.getOperand(0);
19261   SDLoc dl(Vec);
19262   MVT VecVT = Vec.getSimpleValueType();
19263   SDValue Idx = Op.getOperand(1);
19264   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19265   MVT EltVT = Op.getSimpleValueType();
19266 
19267   assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
19268          "Unexpected vector type in ExtractBitFromMaskVector");
19269 
19270   // variable index can't be handled in mask registers,
19271   // extend vector to VR512/128
19272   if (!IdxC) {
19273     unsigned NumElts = VecVT.getVectorNumElements();
19274     // Extending v8i1/v16i1 to 512-bit get better performance on KNL
19275     // than extending to 128/256bit.
19276     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19277     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19278     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
19279     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
19280     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
19281   }
19282 
19283   unsigned IdxVal = IdxC->getZExtValue();
19284   if (IdxVal == 0) // the operation is legal
19285     return Op;
19286 
19287   // Extend to natively supported kshift.
19288   unsigned NumElems = VecVT.getVectorNumElements();
19289   MVT WideVecVT = VecVT;
19290   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
19291     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19292     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
19293                       DAG.getUNDEF(WideVecVT), Vec,
19294                       DAG.getIntPtrConstant(0, dl));
19295   }
19296 
19297   // Use kshiftr instruction to move to the lower element.
19298   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
19299                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19300 
19301   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19302                      DAG.getIntPtrConstant(0, dl));
19303 }
19304 
19305 SDValue
19306 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
19307                                            SelectionDAG &DAG) const {
19308   SDLoc dl(Op);
19309   SDValue Vec = Op.getOperand(0);
19310   MVT VecVT = Vec.getSimpleValueType();
19311   SDValue Idx = Op.getOperand(1);
19312   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19313 
19314   if (VecVT.getVectorElementType() == MVT::i1)
19315     return ExtractBitFromMaskVector(Op, DAG, Subtarget);
19316 
19317   if (!IdxC) {
19318     // Its more profitable to go through memory (1 cycles throughput)
19319     // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
19320     // IACA tool was used to get performance estimation
19321     // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
19322     //
19323     // example : extractelement <16 x i8> %a, i32 %i
19324     //
19325     // Block Throughput: 3.00 Cycles
19326     // Throughput Bottleneck: Port5
19327     //
19328     // | Num Of |   Ports pressure in cycles  |    |
19329     // |  Uops  |  0  - DV  |  5  |  6  |  7  |    |
19330     // ---------------------------------------------
19331     // |   1    |           | 1.0 |     |     | CP | vmovd xmm1, edi
19332     // |   1    |           | 1.0 |     |     | CP | vpshufb xmm0, xmm0, xmm1
19333     // |   2    | 1.0       | 1.0 |     |     | CP | vpextrb eax, xmm0, 0x0
19334     // Total Num Of Uops: 4
19335     //
19336     //
19337     // Block Throughput: 1.00 Cycles
19338     // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
19339     //
19340     // |    |  Ports pressure in cycles   |  |
19341     // |Uops| 1 | 2 - D  |3 -  D  | 4 | 5 |  |
19342     // ---------------------------------------------------------
19343     // |2^  |   | 0.5    | 0.5    |1.0|   |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
19344     // |1   |0.5|        |        |   |0.5|  | lea rax, ptr [rsp-0x18]
19345     // |1   |   |0.5, 0.5|0.5, 0.5|   |   |CP| mov al, byte ptr [rdi+rax*1]
19346     // Total Num Of Uops: 4
19347 
19348     return SDValue();
19349   }
19350 
19351   unsigned IdxVal = IdxC->getZExtValue();
19352 
19353   // If this is a 256-bit vector result, first extract the 128-bit vector and
19354   // then extract the element from the 128-bit vector.
19355   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
19356     // Get the 128-bit vector.
19357     Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
19358     MVT EltVT = VecVT.getVectorElementType();
19359 
19360     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
19361     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
19362 
19363     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
19364     // this can be done with a mask.
19365     IdxVal &= ElemsPerChunk - 1;
19366     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19367                        DAG.getIntPtrConstant(IdxVal, dl));
19368   }
19369 
19370   assert(VecVT.is128BitVector() && "Unexpected vector length");
19371 
19372   MVT VT = Op.getSimpleValueType();
19373 
19374   if (VT == MVT::i16) {
19375     // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
19376     // we're going to zero extend the register or fold the store (SSE41 only).
19377     if (IdxVal == 0 && !X86::mayFoldIntoZeroExtend(Op) &&
19378         !(Subtarget.hasSSE41() && X86::mayFoldIntoStore(Op))) {
19379       if (Subtarget.hasFP16())
19380         return Op;
19381 
19382       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
19383                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19384                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
19385     }
19386 
19387     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
19388                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19389     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19390   }
19391 
19392   if (Subtarget.hasSSE41())
19393     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
19394       return Res;
19395 
19396   // TODO: We only extract a single element from v16i8, we can probably afford
19397   // to be more aggressive here before using the default approach of spilling to
19398   // stack.
19399   if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
19400     // Extract either the lowest i32 or any i16, and extract the sub-byte.
19401     int DWordIdx = IdxVal / 4;
19402     if (DWordIdx == 0) {
19403       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19404                                 DAG.getBitcast(MVT::v4i32, Vec),
19405                                 DAG.getIntPtrConstant(DWordIdx, dl));
19406       int ShiftVal = (IdxVal % 4) * 8;
19407       if (ShiftVal != 0)
19408         Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
19409                           DAG.getConstant(ShiftVal, dl, MVT::i8));
19410       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19411     }
19412 
19413     int WordIdx = IdxVal / 2;
19414     SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
19415                               DAG.getBitcast(MVT::v8i16, Vec),
19416                               DAG.getIntPtrConstant(WordIdx, dl));
19417     int ShiftVal = (IdxVal % 2) * 8;
19418     if (ShiftVal != 0)
19419       Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
19420                         DAG.getConstant(ShiftVal, dl, MVT::i8));
19421     return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19422   }
19423 
19424   if (VT == MVT::f16 || VT.getSizeInBits() == 32) {
19425     if (IdxVal == 0)
19426       return Op;
19427 
19428     // Shuffle the element to the lowest element, then movss or movsh.
19429     SmallVector<int, 8> Mask(VecVT.getVectorNumElements(), -1);
19430     Mask[0] = static_cast<int>(IdxVal);
19431     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19432     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19433                        DAG.getIntPtrConstant(0, dl));
19434   }
19435 
19436   if (VT.getSizeInBits() == 64) {
19437     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
19438     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
19439     //        to match extract_elt for f64.
19440     if (IdxVal == 0)
19441       return Op;
19442 
19443     // UNPCKHPD the element to the lowest double word, then movsd.
19444     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
19445     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
19446     int Mask[2] = { 1, -1 };
19447     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19448     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19449                        DAG.getIntPtrConstant(0, dl));
19450   }
19451 
19452   return SDValue();
19453 }
19454 
19455 /// Insert one bit to mask vector, like v16i1 or v8i1.
19456 /// AVX-512 feature.
19457 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
19458                                      const X86Subtarget &Subtarget) {
19459   SDLoc dl(Op);
19460   SDValue Vec = Op.getOperand(0);
19461   SDValue Elt = Op.getOperand(1);
19462   SDValue Idx = Op.getOperand(2);
19463   MVT VecVT = Vec.getSimpleValueType();
19464 
19465   if (!isa<ConstantSDNode>(Idx)) {
19466     // Non constant index. Extend source and destination,
19467     // insert element and then truncate the result.
19468     unsigned NumElts = VecVT.getVectorNumElements();
19469     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19470     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19471     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
19472       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
19473       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
19474     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
19475   }
19476 
19477   // Copy into a k-register, extract to v1i1 and insert_subvector.
19478   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
19479   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
19480 }
19481 
19482 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
19483                                                   SelectionDAG &DAG) const {
19484   MVT VT = Op.getSimpleValueType();
19485   MVT EltVT = VT.getVectorElementType();
19486   unsigned NumElts = VT.getVectorNumElements();
19487   unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
19488 
19489   if (EltVT == MVT::i1)
19490     return InsertBitToMaskVector(Op, DAG, Subtarget);
19491 
19492   SDLoc dl(Op);
19493   SDValue N0 = Op.getOperand(0);
19494   SDValue N1 = Op.getOperand(1);
19495   SDValue N2 = Op.getOperand(2);
19496   auto *N2C = dyn_cast<ConstantSDNode>(N2);
19497 
19498   if (!N2C) {
19499     // Variable insertion indices, usually we're better off spilling to stack,
19500     // but AVX512 can use a variable compare+select by comparing against all
19501     // possible vector indices, and FP insertion has less gpr->simd traffic.
19502     if (!(Subtarget.hasBWI() ||
19503           (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
19504           (Subtarget.hasSSE41() && VT.isFloatingPoint())))
19505       return SDValue();
19506 
19507     MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
19508     MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
19509     if (!isTypeLegal(IdxSVT) || !isTypeLegal(IdxVT))
19510       return SDValue();
19511 
19512     SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
19513     SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
19514     SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
19515 
19516     SmallVector<SDValue, 16> RawIndices;
19517     for (unsigned I = 0; I != NumElts; ++I)
19518       RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
19519     SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
19520 
19521     // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
19522     return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
19523                            ISD::CondCode::SETEQ);
19524   }
19525 
19526   if (N2C->getAPIntValue().uge(NumElts))
19527     return SDValue();
19528   uint64_t IdxVal = N2C->getZExtValue();
19529 
19530   bool IsZeroElt = X86::isZeroNode(N1);
19531   bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
19532 
19533   if (IsZeroElt || IsAllOnesElt) {
19534     // Lower insertion of i8 -1 as an 'OR' blend.
19535     // We don't deal with i8 0 since it appears to be handled elsewhere.
19536     if (IsAllOnesElt && EltSizeInBits == 8 && !Subtarget.hasSSE41()) {
19537       SDValue ZeroCst = DAG.getConstant(0, dl, VT.getScalarType());
19538       SDValue OnesCst = DAG.getAllOnesConstant(dl, VT.getScalarType());
19539       SmallVector<SDValue, 8> CstVectorElts(NumElts, ZeroCst);
19540       CstVectorElts[IdxVal] = OnesCst;
19541       SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
19542       return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
19543     }
19544     // See if we can do this more efficiently with a blend shuffle with a
19545     // rematerializable vector.
19546     if (Subtarget.hasSSE41() &&
19547         (EltSizeInBits >= 16 || (IsZeroElt && !VT.is128BitVector()))) {
19548       SmallVector<int, 8> BlendMask;
19549       for (unsigned i = 0; i != NumElts; ++i)
19550         BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19551       SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
19552                                     : getOnesVector(VT, DAG, dl);
19553       return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
19554     }
19555   }
19556 
19557   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
19558   // into that, and then insert the subvector back into the result.
19559   if (VT.is256BitVector() || VT.is512BitVector()) {
19560     // With a 256-bit vector, we can insert into the zero element efficiently
19561     // using a blend if we have AVX or AVX2 and the right data type.
19562     if (VT.is256BitVector() && IdxVal == 0) {
19563       // TODO: It is worthwhile to cast integer to floating point and back
19564       // and incur a domain crossing penalty if that's what we'll end up
19565       // doing anyway after extracting to a 128-bit vector.
19566       if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
19567           (Subtarget.hasAVX2() && EltVT == MVT::i32)) {
19568         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19569         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
19570                            DAG.getTargetConstant(1, dl, MVT::i8));
19571       }
19572     }
19573 
19574     unsigned NumEltsIn128 = 128 / EltSizeInBits;
19575     assert(isPowerOf2_32(NumEltsIn128) &&
19576            "Vectors will always have power-of-two number of elements.");
19577 
19578     // If we are not inserting into the low 128-bit vector chunk,
19579     // then prefer the broadcast+blend sequence.
19580     // FIXME: relax the profitability check iff all N1 uses are insertions.
19581     if (!VT.is128BitVector() && IdxVal >= NumEltsIn128 &&
19582         ((Subtarget.hasAVX2() && EltSizeInBits != 8) ||
19583          (Subtarget.hasAVX() && (EltSizeInBits >= 32) &&
19584           X86::mayFoldLoad(N1, Subtarget)))) {
19585       SDValue N1SplatVec = DAG.getSplatBuildVector(VT, dl, N1);
19586       SmallVector<int, 8> BlendMask;
19587       for (unsigned i = 0; i != NumElts; ++i)
19588         BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19589       return DAG.getVectorShuffle(VT, dl, N0, N1SplatVec, BlendMask);
19590     }
19591 
19592     // Get the desired 128-bit vector chunk.
19593     SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
19594 
19595     // Insert the element into the desired chunk.
19596     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
19597     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
19598 
19599     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
19600                     DAG.getIntPtrConstant(IdxIn128, dl));
19601 
19602     // Insert the changed part back into the bigger vector
19603     return insert128BitVector(N0, V, IdxVal, DAG, dl);
19604   }
19605   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
19606 
19607   // This will be just movw/movd/movq/movsh/movss/movsd.
19608   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
19609     if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
19610         EltVT == MVT::f16 || EltVT == MVT::i64) {
19611       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19612       return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19613     }
19614 
19615     // We can't directly insert an i8 or i16 into a vector, so zero extend
19616     // it to i32 first.
19617     if (EltVT == MVT::i16 || EltVT == MVT::i8) {
19618       N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
19619       MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
19620       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
19621       N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19622       return DAG.getBitcast(VT, N1);
19623     }
19624   }
19625 
19626   // Transform it so it match pinsr{b,w} which expects a GR32 as its second
19627   // argument. SSE41 required for pinsrb.
19628   if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
19629     unsigned Opc;
19630     if (VT == MVT::v8i16) {
19631       assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
19632       Opc = X86ISD::PINSRW;
19633     } else {
19634       assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
19635       assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
19636       Opc = X86ISD::PINSRB;
19637     }
19638 
19639     assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
19640     N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
19641     N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
19642     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
19643   }
19644 
19645   if (Subtarget.hasSSE41()) {
19646     if (EltVT == MVT::f32) {
19647       // Bits [7:6] of the constant are the source select. This will always be
19648       //   zero here. The DAG Combiner may combine an extract_elt index into
19649       //   these bits. For example (insert (extract, 3), 2) could be matched by
19650       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
19651       // Bits [5:4] of the constant are the destination select. This is the
19652       //   value of the incoming immediate.
19653       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
19654       //   combine either bitwise AND or insert of float 0.0 to set these bits.
19655 
19656       bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
19657       if (IdxVal == 0 && (!MinSize || !X86::mayFoldLoad(N1, Subtarget))) {
19658         // If this is an insertion of 32-bits into the low 32-bits of
19659         // a vector, we prefer to generate a blend with immediate rather
19660         // than an insertps. Blends are simpler operations in hardware and so
19661         // will always have equal or better performance than insertps.
19662         // But if optimizing for size and there's a load folding opportunity,
19663         // generate insertps because blendps does not have a 32-bit memory
19664         // operand form.
19665         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19666         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
19667                            DAG.getTargetConstant(1, dl, MVT::i8));
19668       }
19669       // Create this as a scalar to vector..
19670       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19671       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
19672                          DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
19673     }
19674 
19675     // PINSR* works with constant index.
19676     if (EltVT == MVT::i32 || EltVT == MVT::i64)
19677       return Op;
19678   }
19679 
19680   return SDValue();
19681 }
19682 
19683 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
19684                                      SelectionDAG &DAG) {
19685   SDLoc dl(Op);
19686   MVT OpVT = Op.getSimpleValueType();
19687 
19688   // It's always cheaper to replace a xor+movd with xorps and simplifies further
19689   // combines.
19690   if (X86::isZeroNode(Op.getOperand(0)))
19691     return getZeroVector(OpVT, Subtarget, DAG, dl);
19692 
19693   // If this is a 256-bit vector result, first insert into a 128-bit
19694   // vector and then insert into the 256-bit vector.
19695   if (!OpVT.is128BitVector()) {
19696     // Insert into a 128-bit vector.
19697     unsigned SizeFactor = OpVT.getSizeInBits() / 128;
19698     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
19699                                  OpVT.getVectorNumElements() / SizeFactor);
19700 
19701     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
19702 
19703     // Insert the 128-bit vector.
19704     return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
19705   }
19706   assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
19707          "Expected an SSE type!");
19708 
19709   // Pass through a v4i32 or V8i16 SCALAR_TO_VECTOR as that's what we use in
19710   // tblgen.
19711   if (OpVT == MVT::v4i32 || (OpVT == MVT::v8i16 && Subtarget.hasFP16()))
19712     return Op;
19713 
19714   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
19715   return DAG.getBitcast(
19716       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
19717 }
19718 
19719 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
19720 // simple superregister reference or explicit instructions to insert
19721 // the upper bits of a vector.
19722 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
19723                                      SelectionDAG &DAG) {
19724   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
19725 
19726   return insert1BitVector(Op, DAG, Subtarget);
19727 }
19728 
19729 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
19730                                       SelectionDAG &DAG) {
19731   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
19732          "Only vXi1 extract_subvectors need custom lowering");
19733 
19734   SDLoc dl(Op);
19735   SDValue Vec = Op.getOperand(0);
19736   uint64_t IdxVal = Op.getConstantOperandVal(1);
19737 
19738   if (IdxVal == 0) // the operation is legal
19739     return Op;
19740 
19741   MVT VecVT = Vec.getSimpleValueType();
19742   unsigned NumElems = VecVT.getVectorNumElements();
19743 
19744   // Extend to natively supported kshift.
19745   MVT WideVecVT = VecVT;
19746   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
19747     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19748     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
19749                       DAG.getUNDEF(WideVecVT), Vec,
19750                       DAG.getIntPtrConstant(0, dl));
19751   }
19752 
19753   // Shift to the LSB.
19754   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
19755                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19756 
19757   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
19758                      DAG.getIntPtrConstant(0, dl));
19759 }
19760 
19761 // Returns the appropriate wrapper opcode for a global reference.
19762 unsigned X86TargetLowering::getGlobalWrapperKind(
19763     const GlobalValue *GV, const unsigned char OpFlags) const {
19764   // References to absolute symbols are never PC-relative.
19765   if (GV && GV->isAbsoluteSymbolRef())
19766     return X86ISD::Wrapper;
19767 
19768   CodeModel::Model M = getTargetMachine().getCodeModel();
19769   if (Subtarget.isPICStyleRIPRel() &&
19770       (M == CodeModel::Small || M == CodeModel::Kernel))
19771     return X86ISD::WrapperRIP;
19772 
19773   // GOTPCREL references must always use RIP.
19774   if (OpFlags == X86II::MO_GOTPCREL || OpFlags == X86II::MO_GOTPCREL_NORELAX)
19775     return X86ISD::WrapperRIP;
19776 
19777   return X86ISD::Wrapper;
19778 }
19779 
19780 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
19781 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
19782 // one of the above mentioned nodes. It has to be wrapped because otherwise
19783 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
19784 // be used to form addressing mode. These wrapped nodes will be selected
19785 // into MOV32ri.
19786 SDValue
19787 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
19788   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
19789 
19790   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19791   // global base reg.
19792   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19793 
19794   auto PtrVT = getPointerTy(DAG.getDataLayout());
19795   SDValue Result = DAG.getTargetConstantPool(
19796       CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
19797   SDLoc DL(CP);
19798   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
19799   // With PIC, the address is actually $g + Offset.
19800   if (OpFlag) {
19801     Result =
19802         DAG.getNode(ISD::ADD, DL, PtrVT,
19803                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19804   }
19805 
19806   return Result;
19807 }
19808 
19809 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
19810   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
19811 
19812   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19813   // global base reg.
19814   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19815 
19816   auto PtrVT = getPointerTy(DAG.getDataLayout());
19817   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
19818   SDLoc DL(JT);
19819   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
19820 
19821   // With PIC, the address is actually $g + Offset.
19822   if (OpFlag)
19823     Result =
19824         DAG.getNode(ISD::ADD, DL, PtrVT,
19825                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19826 
19827   return Result;
19828 }
19829 
19830 SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
19831                                                SelectionDAG &DAG) const {
19832   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
19833 }
19834 
19835 SDValue
19836 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
19837   // Create the TargetBlockAddressAddress node.
19838   unsigned char OpFlags =
19839     Subtarget.classifyBlockAddressReference();
19840   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
19841   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
19842   SDLoc dl(Op);
19843   auto PtrVT = getPointerTy(DAG.getDataLayout());
19844   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
19845   Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
19846 
19847   // With PIC, the address is actually $g + Offset.
19848   if (isGlobalRelativeToPICBase(OpFlags)) {
19849     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19850                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19851   }
19852 
19853   return Result;
19854 }
19855 
19856 /// Creates target global address or external symbol nodes for calls or
19857 /// other uses.
19858 SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
19859                                                  bool ForCall) const {
19860   // Unpack the global address or external symbol.
19861   const SDLoc &dl = SDLoc(Op);
19862   const GlobalValue *GV = nullptr;
19863   int64_t Offset = 0;
19864   const char *ExternalSym = nullptr;
19865   if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
19866     GV = G->getGlobal();
19867     Offset = G->getOffset();
19868   } else {
19869     const auto *ES = cast<ExternalSymbolSDNode>(Op);
19870     ExternalSym = ES->getSymbol();
19871   }
19872 
19873   // Calculate some flags for address lowering.
19874   const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
19875   unsigned char OpFlags;
19876   if (ForCall)
19877     OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
19878   else
19879     OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
19880   bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
19881   bool NeedsLoad = isGlobalStubReference(OpFlags);
19882 
19883   CodeModel::Model M = DAG.getTarget().getCodeModel();
19884   auto PtrVT = getPointerTy(DAG.getDataLayout());
19885   SDValue Result;
19886 
19887   if (GV) {
19888     // Create a target global address if this is a global. If possible, fold the
19889     // offset into the global address reference. Otherwise, ADD it on later.
19890     // Suppress the folding if Offset is negative: movl foo-1, %eax is not
19891     // allowed because if the address of foo is 0, the ELF R_X86_64_32
19892     // relocation will compute to a negative value, which is invalid.
19893     int64_t GlobalOffset = 0;
19894     if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
19895         X86::isOffsetSuitableForCodeModel(Offset, M, true)) {
19896       std::swap(GlobalOffset, Offset);
19897     }
19898     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
19899   } else {
19900     // If this is not a global address, this must be an external symbol.
19901     Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
19902   }
19903 
19904   // If this is a direct call, avoid the wrapper if we don't need to do any
19905   // loads or adds. This allows SDAG ISel to match direct calls.
19906   if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
19907     return Result;
19908 
19909   Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
19910 
19911   // With PIC, the address is actually $g + Offset.
19912   if (HasPICReg) {
19913     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19914                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19915   }
19916 
19917   // For globals that require a load from a stub to get the address, emit the
19918   // load.
19919   if (NeedsLoad)
19920     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
19921                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
19922 
19923   // If there was a non-zero offset that we didn't fold, create an explicit
19924   // addition for it.
19925   if (Offset != 0)
19926     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
19927                          DAG.getConstant(Offset, dl, PtrVT));
19928 
19929   return Result;
19930 }
19931 
19932 SDValue
19933 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
19934   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
19935 }
19936 
19937 static SDValue
19938 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
19939            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
19940            unsigned char OperandFlags, bool LocalDynamic = false) {
19941   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
19942   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19943   SDLoc dl(GA);
19944   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19945                                            GA->getValueType(0),
19946                                            GA->getOffset(),
19947                                            OperandFlags);
19948 
19949   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
19950                                            : X86ISD::TLSADDR;
19951 
19952   if (InFlag) {
19953     SDValue Ops[] = { Chain,  TGA, *InFlag };
19954     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
19955   } else {
19956     SDValue Ops[]  = { Chain, TGA };
19957     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
19958   }
19959 
19960   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
19961   MFI.setAdjustsStack(true);
19962   MFI.setHasCalls(true);
19963 
19964   SDValue Flag = Chain.getValue(1);
19965   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
19966 }
19967 
19968 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
19969 static SDValue
19970 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19971                                 const EVT PtrVT) {
19972   SDValue InFlag;
19973   SDLoc dl(GA);  // ? function entry point might be better
19974   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
19975                                    DAG.getNode(X86ISD::GlobalBaseReg,
19976                                                SDLoc(), PtrVT), InFlag);
19977   InFlag = Chain.getValue(1);
19978 
19979   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
19980 }
19981 
19982 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
19983 static SDValue
19984 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19985                                 const EVT PtrVT) {
19986   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
19987                     X86::RAX, X86II::MO_TLSGD);
19988 }
19989 
19990 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
19991 static SDValue
19992 LowerToTLSGeneralDynamicModelX32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19993                                  const EVT PtrVT) {
19994   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
19995                     X86::EAX, X86II::MO_TLSGD);
19996 }
19997 
19998 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
19999                                            SelectionDAG &DAG, const EVT PtrVT,
20000                                            bool Is64Bit, bool Is64BitLP64) {
20001   SDLoc dl(GA);
20002 
20003   // Get the start address of the TLS block for this module.
20004   X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
20005       .getInfo<X86MachineFunctionInfo>();
20006   MFI->incNumLocalDynamicTLSAccesses();
20007 
20008   SDValue Base;
20009   if (Is64Bit) {
20010     unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
20011     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, ReturnReg,
20012                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
20013   } else {
20014     SDValue InFlag;
20015     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
20016         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
20017     InFlag = Chain.getValue(1);
20018     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
20019                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
20020   }
20021 
20022   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
20023   // of Base.
20024 
20025   // Build x@dtpoff.
20026   unsigned char OperandFlags = X86II::MO_DTPOFF;
20027   unsigned WrapperKind = X86ISD::Wrapper;
20028   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
20029                                            GA->getValueType(0),
20030                                            GA->getOffset(), OperandFlags);
20031   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
20032 
20033   // Add x@dtpoff with the base.
20034   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
20035 }
20036 
20037 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
20038 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
20039                                    const EVT PtrVT, TLSModel::Model model,
20040                                    bool is64Bit, bool isPIC) {
20041   SDLoc dl(GA);
20042 
20043   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
20044   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
20045                                                          is64Bit ? 257 : 256));
20046 
20047   SDValue ThreadPointer =
20048       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
20049                   MachinePointerInfo(Ptr));
20050 
20051   unsigned char OperandFlags = 0;
20052   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
20053   // initialexec.
20054   unsigned WrapperKind = X86ISD::Wrapper;
20055   if (model == TLSModel::LocalExec) {
20056     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
20057   } else if (model == TLSModel::InitialExec) {
20058     if (is64Bit) {
20059       OperandFlags = X86II::MO_GOTTPOFF;
20060       WrapperKind = X86ISD::WrapperRIP;
20061     } else {
20062       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
20063     }
20064   } else {
20065     llvm_unreachable("Unexpected model");
20066   }
20067 
20068   // emit "addl x@ntpoff,%eax" (local exec)
20069   // or "addl x@indntpoff,%eax" (initial exec)
20070   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
20071   SDValue TGA =
20072       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
20073                                  GA->getOffset(), OperandFlags);
20074   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
20075 
20076   if (model == TLSModel::InitialExec) {
20077     if (isPIC && !is64Bit) {
20078       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
20079                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20080                            Offset);
20081     }
20082 
20083     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
20084                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
20085   }
20086 
20087   // The address of the thread local variable is the add of the thread
20088   // pointer with the offset of the variable.
20089   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
20090 }
20091 
20092 SDValue
20093 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
20094 
20095   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
20096 
20097   if (DAG.getTarget().useEmulatedTLS())
20098     return LowerToTLSEmulatedModel(GA, DAG);
20099 
20100   const GlobalValue *GV = GA->getGlobal();
20101   auto PtrVT = getPointerTy(DAG.getDataLayout());
20102   bool PositionIndependent = isPositionIndependent();
20103 
20104   if (Subtarget.isTargetELF()) {
20105     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
20106     switch (model) {
20107       case TLSModel::GeneralDynamic:
20108         if (Subtarget.is64Bit()) {
20109           if (Subtarget.isTarget64BitLP64())
20110             return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
20111           return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
20112         }
20113         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
20114       case TLSModel::LocalDynamic:
20115         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
20116                                            Subtarget.isTarget64BitLP64());
20117       case TLSModel::InitialExec:
20118       case TLSModel::LocalExec:
20119         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
20120                                    PositionIndependent);
20121     }
20122     llvm_unreachable("Unknown TLS model.");
20123   }
20124 
20125   if (Subtarget.isTargetDarwin()) {
20126     // Darwin only has one model of TLS.  Lower to that.
20127     unsigned char OpFlag = 0;
20128     unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
20129                            X86ISD::WrapperRIP : X86ISD::Wrapper;
20130 
20131     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
20132     // global base reg.
20133     bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
20134     if (PIC32)
20135       OpFlag = X86II::MO_TLVP_PIC_BASE;
20136     else
20137       OpFlag = X86II::MO_TLVP;
20138     SDLoc DL(Op);
20139     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
20140                                                 GA->getValueType(0),
20141                                                 GA->getOffset(), OpFlag);
20142     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
20143 
20144     // With PIC32, the address is actually $g + Offset.
20145     if (PIC32)
20146       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
20147                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20148                            Offset);
20149 
20150     // Lowering the machine isd will make sure everything is in the right
20151     // location.
20152     SDValue Chain = DAG.getEntryNode();
20153     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20154     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
20155     SDValue Args[] = { Chain, Offset };
20156     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
20157     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
20158                                DAG.getIntPtrConstant(0, DL, true),
20159                                Chain.getValue(1), DL);
20160 
20161     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
20162     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
20163     MFI.setAdjustsStack(true);
20164 
20165     // And our return value (tls address) is in the standard call return value
20166     // location.
20167     unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
20168     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
20169   }
20170 
20171   if (Subtarget.isOSWindows()) {
20172     // Just use the implicit TLS architecture
20173     // Need to generate something similar to:
20174     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
20175     //                                  ; from TEB
20176     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
20177     //   mov     rcx, qword [rdx+rcx*8]
20178     //   mov     eax, .tls$:tlsvar
20179     //   [rax+rcx] contains the address
20180     // Windows 64bit: gs:0x58
20181     // Windows 32bit: fs:__tls_array
20182 
20183     SDLoc dl(GA);
20184     SDValue Chain = DAG.getEntryNode();
20185 
20186     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
20187     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
20188     // use its literal value of 0x2C.
20189     Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
20190                                         ? Type::getInt8PtrTy(*DAG.getContext(),
20191                                                              256)
20192                                         : Type::getInt32PtrTy(*DAG.getContext(),
20193                                                               257));
20194 
20195     SDValue TlsArray = Subtarget.is64Bit()
20196                            ? DAG.getIntPtrConstant(0x58, dl)
20197                            : (Subtarget.isTargetWindowsGNU()
20198                                   ? DAG.getIntPtrConstant(0x2C, dl)
20199                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
20200 
20201     SDValue ThreadPointer =
20202         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
20203 
20204     SDValue res;
20205     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
20206       res = ThreadPointer;
20207     } else {
20208       // Load the _tls_index variable
20209       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
20210       if (Subtarget.is64Bit())
20211         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
20212                              MachinePointerInfo(), MVT::i32);
20213       else
20214         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
20215 
20216       const DataLayout &DL = DAG.getDataLayout();
20217       SDValue Scale =
20218           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
20219       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
20220 
20221       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
20222     }
20223 
20224     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
20225 
20226     // Get the offset of start of .tls section
20227     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
20228                                              GA->getValueType(0),
20229                                              GA->getOffset(), X86II::MO_SECREL);
20230     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
20231 
20232     // The address of the thread local variable is the add of the thread
20233     // pointer with the offset of the variable.
20234     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
20235   }
20236 
20237   llvm_unreachable("TLS not implemented for this target.");
20238 }
20239 
20240 /// Lower SRA_PARTS and friends, which return two i32 values
20241 /// and take a 2 x i32 value to shift plus a shift amount.
20242 /// TODO: Can this be moved to general expansion code?
20243 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
20244   SDValue Lo, Hi;
20245   DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
20246   return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
20247 }
20248 
20249 // Try to use a packed vector operation to handle i64 on 32-bit targets when
20250 // AVX512DQ is enabled.
20251 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
20252                                         const X86Subtarget &Subtarget) {
20253   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20254           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20255           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20256           Op.getOpcode() == ISD::UINT_TO_FP) &&
20257          "Unexpected opcode!");
20258   bool IsStrict = Op->isStrictFPOpcode();
20259   unsigned OpNo = IsStrict ? 1 : 0;
20260   SDValue Src = Op.getOperand(OpNo);
20261   MVT SrcVT = Src.getSimpleValueType();
20262   MVT VT = Op.getSimpleValueType();
20263 
20264    if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
20265        (VT != MVT::f32 && VT != MVT::f64))
20266     return SDValue();
20267 
20268   // Pack the i64 into a vector, do the operation and extract.
20269 
20270   // Using 256-bit to ensure result is 128-bits for f32 case.
20271   unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
20272   MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
20273   MVT VecVT = MVT::getVectorVT(VT, NumElts);
20274 
20275   SDLoc dl(Op);
20276   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
20277   if (IsStrict) {
20278     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
20279                                  {Op.getOperand(0), InVec});
20280     SDValue Chain = CvtVec.getValue(1);
20281     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20282                                 DAG.getIntPtrConstant(0, dl));
20283     return DAG.getMergeValues({Value, Chain}, dl);
20284   }
20285 
20286   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
20287 
20288   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20289                      DAG.getIntPtrConstant(0, dl));
20290 }
20291 
20292 // Try to use a packed vector operation to handle i64 on 32-bit targets.
20293 static SDValue LowerI64IntToFP16(SDValue Op, SelectionDAG &DAG,
20294                                  const X86Subtarget &Subtarget) {
20295   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20296           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20297           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20298           Op.getOpcode() == ISD::UINT_TO_FP) &&
20299          "Unexpected opcode!");
20300   bool IsStrict = Op->isStrictFPOpcode();
20301   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20302   MVT SrcVT = Src.getSimpleValueType();
20303   MVT VT = Op.getSimpleValueType();
20304 
20305   if (SrcVT != MVT::i64 || Subtarget.is64Bit() || VT != MVT::f16)
20306     return SDValue();
20307 
20308   // Pack the i64 into a vector, do the operation and extract.
20309 
20310   assert(Subtarget.hasFP16() && "Expected FP16");
20311 
20312   SDLoc dl(Op);
20313   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
20314   if (IsStrict) {
20315     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {MVT::v2f16, MVT::Other},
20316                                  {Op.getOperand(0), InVec});
20317     SDValue Chain = CvtVec.getValue(1);
20318     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20319                                 DAG.getIntPtrConstant(0, dl));
20320     return DAG.getMergeValues({Value, Chain}, dl);
20321   }
20322 
20323   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, MVT::v2f16, InVec);
20324 
20325   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20326                      DAG.getIntPtrConstant(0, dl));
20327 }
20328 
20329 static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
20330                           const X86Subtarget &Subtarget) {
20331   switch (Opcode) {
20332     case ISD::SINT_TO_FP:
20333       // TODO: Handle wider types with AVX/AVX512.
20334       if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
20335         return false;
20336       // CVTDQ2PS or (V)CVTDQ2PD
20337       return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
20338 
20339     case ISD::UINT_TO_FP:
20340       // TODO: Handle wider types and i64 elements.
20341       if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
20342         return false;
20343       // VCVTUDQ2PS or VCVTUDQ2PD
20344       return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
20345 
20346     default:
20347       return false;
20348   }
20349 }
20350 
20351 /// Given a scalar cast operation that is extracted from a vector, try to
20352 /// vectorize the cast op followed by extraction. This will avoid an expensive
20353 /// round-trip between XMM and GPR.
20354 static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
20355                                       const X86Subtarget &Subtarget) {
20356   // TODO: This could be enhanced to handle smaller integer types by peeking
20357   // through an extend.
20358   SDValue Extract = Cast.getOperand(0);
20359   MVT DestVT = Cast.getSimpleValueType();
20360   if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
20361       !isa<ConstantSDNode>(Extract.getOperand(1)))
20362     return SDValue();
20363 
20364   // See if we have a 128-bit vector cast op for this type of cast.
20365   SDValue VecOp = Extract.getOperand(0);
20366   MVT FromVT = VecOp.getSimpleValueType();
20367   unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
20368   MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
20369   MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
20370   if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
20371     return SDValue();
20372 
20373   // If we are extracting from a non-zero element, first shuffle the source
20374   // vector to allow extracting from element zero.
20375   SDLoc DL(Cast);
20376   if (!isNullConstant(Extract.getOperand(1))) {
20377     SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
20378     Mask[0] = Extract.getConstantOperandVal(1);
20379     VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
20380   }
20381   // If the source vector is wider than 128-bits, extract the low part. Do not
20382   // create an unnecessarily wide vector cast op.
20383   if (FromVT != Vec128VT)
20384     VecOp = extract128BitVector(VecOp, 0, DAG, DL);
20385 
20386   // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
20387   // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
20388   SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
20389   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
20390                      DAG.getIntPtrConstant(0, DL));
20391 }
20392 
20393 /// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
20394 /// try to vectorize the cast ops. This will avoid an expensive round-trip
20395 /// between XMM and GPR.
20396 static SDValue lowerFPToIntToFP(SDValue CastToFP, SelectionDAG &DAG,
20397                                 const X86Subtarget &Subtarget) {
20398   // TODO: Allow FP_TO_UINT.
20399   SDValue CastToInt = CastToFP.getOperand(0);
20400   MVT VT = CastToFP.getSimpleValueType();
20401   if (CastToInt.getOpcode() != ISD::FP_TO_SINT || VT.isVector())
20402     return SDValue();
20403 
20404   MVT IntVT = CastToInt.getSimpleValueType();
20405   SDValue X = CastToInt.getOperand(0);
20406   MVT SrcVT = X.getSimpleValueType();
20407   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
20408     return SDValue();
20409 
20410   // See if we have 128-bit vector cast instructions for this type of cast.
20411   // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
20412   if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
20413       IntVT != MVT::i32)
20414     return SDValue();
20415 
20416   unsigned SrcSize = SrcVT.getSizeInBits();
20417   unsigned IntSize = IntVT.getSizeInBits();
20418   unsigned VTSize = VT.getSizeInBits();
20419   MVT VecSrcVT = MVT::getVectorVT(SrcVT, 128 / SrcSize);
20420   MVT VecIntVT = MVT::getVectorVT(IntVT, 128 / IntSize);
20421   MVT VecVT = MVT::getVectorVT(VT, 128 / VTSize);
20422 
20423   // We need target-specific opcodes if this is v2f64 -> v4i32 -> v2f64.
20424   unsigned ToIntOpcode =
20425       SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
20426   unsigned ToFPOpcode =
20427       IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
20428 
20429   // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
20430   //
20431   // We are not defining the high elements (for example, zero them) because
20432   // that could nullify any performance advantage that we hoped to gain from
20433   // this vector op hack. We do not expect any adverse effects (like denorm
20434   // penalties) with cast ops.
20435   SDLoc DL(CastToFP);
20436   SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
20437   SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
20438   SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
20439   SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
20440   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
20441 }
20442 
20443 static SDValue lowerINT_TO_FP_vXi64(SDValue Op, SelectionDAG &DAG,
20444                                     const X86Subtarget &Subtarget) {
20445   SDLoc DL(Op);
20446   bool IsStrict = Op->isStrictFPOpcode();
20447   MVT VT = Op->getSimpleValueType(0);
20448   SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
20449 
20450   if (Subtarget.hasDQI()) {
20451     assert(!Subtarget.hasVLX() && "Unexpected features");
20452 
20453     assert((Src.getSimpleValueType() == MVT::v2i64 ||
20454             Src.getSimpleValueType() == MVT::v4i64) &&
20455            "Unsupported custom type");
20456 
20457     // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
20458     assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
20459            "Unexpected VT!");
20460     MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
20461 
20462     // Need to concat with zero vector for strict fp to avoid spurious
20463     // exceptions.
20464     SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
20465                            : DAG.getUNDEF(MVT::v8i64);
20466     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
20467                       DAG.getIntPtrConstant(0, DL));
20468     SDValue Res, Chain;
20469     if (IsStrict) {
20470       Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
20471                         {Op->getOperand(0), Src});
20472       Chain = Res.getValue(1);
20473     } else {
20474       Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
20475     }
20476 
20477     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20478                       DAG.getIntPtrConstant(0, DL));
20479 
20480     if (IsStrict)
20481       return DAG.getMergeValues({Res, Chain}, DL);
20482     return Res;
20483   }
20484 
20485   bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
20486                   Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
20487   if (VT != MVT::v4f32 || IsSigned)
20488     return SDValue();
20489 
20490   SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
20491   SDValue One  = DAG.getConstant(1, DL, MVT::v4i64);
20492   SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
20493                              DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
20494                              DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
20495   SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
20496   SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
20497   SmallVector<SDValue, 4> SignCvts(4);
20498   SmallVector<SDValue, 4> Chains(4);
20499   for (int i = 0; i != 4; ++i) {
20500     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
20501                               DAG.getIntPtrConstant(i, DL));
20502     if (IsStrict) {
20503       SignCvts[i] =
20504           DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
20505                       {Op.getOperand(0), Elt});
20506       Chains[i] = SignCvts[i].getValue(1);
20507     } else {
20508       SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
20509     }
20510   }
20511   SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
20512 
20513   SDValue Slow, Chain;
20514   if (IsStrict) {
20515     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
20516     Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
20517                        {Chain, SignCvt, SignCvt});
20518     Chain = Slow.getValue(1);
20519   } else {
20520     Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
20521   }
20522 
20523   IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
20524   SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
20525 
20526   if (IsStrict)
20527     return DAG.getMergeValues({Cvt, Chain}, DL);
20528 
20529   return Cvt;
20530 }
20531 
20532 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
20533                                            SelectionDAG &DAG) const {
20534   bool IsStrict = Op->isStrictFPOpcode();
20535   unsigned OpNo = IsStrict ? 1 : 0;
20536   SDValue Src = Op.getOperand(OpNo);
20537   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20538   MVT SrcVT = Src.getSimpleValueType();
20539   MVT VT = Op.getSimpleValueType();
20540   SDLoc dl(Op);
20541 
20542   if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
20543     return LowerWin64_INT128_TO_FP(Op, DAG);
20544 
20545   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
20546     return Extract;
20547 
20548   if (SDValue R = lowerFPToIntToFP(Op, DAG, Subtarget))
20549     return R;
20550 
20551   if (SrcVT.isVector()) {
20552     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
20553       // Note: Since v2f64 is a legal type. We don't need to zero extend the
20554       // source for strict FP.
20555       if (IsStrict)
20556         return DAG.getNode(
20557             X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
20558             {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
20559                                 DAG.getUNDEF(SrcVT))});
20560       return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
20561                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
20562                                      DAG.getUNDEF(SrcVT)));
20563     }
20564     if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
20565       return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
20566 
20567     return SDValue();
20568   }
20569 
20570   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
20571          "Unknown SINT_TO_FP to lower!");
20572 
20573   bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
20574 
20575   // These are really Legal; return the operand so the caller accepts it as
20576   // Legal.
20577   if (SrcVT == MVT::i32 && UseSSEReg)
20578     return Op;
20579   if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
20580     return Op;
20581 
20582   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
20583     return V;
20584   if (SDValue V = LowerI64IntToFP16(Op, DAG, Subtarget))
20585     return V;
20586 
20587   // SSE doesn't have an i16 conversion so we need to promote.
20588   if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
20589     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
20590     if (IsStrict)
20591       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
20592                          {Chain, Ext});
20593 
20594     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
20595   }
20596 
20597   if (VT == MVT::f128)
20598     return SDValue();
20599 
20600   SDValue ValueToStore = Src;
20601   if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
20602     // Bitcasting to f64 here allows us to do a single 64-bit store from
20603     // an SSE register, avoiding the store forwarding penalty that would come
20604     // with two 32-bit stores.
20605     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
20606 
20607   unsigned Size = SrcVT.getStoreSize();
20608   Align Alignment(Size);
20609   MachineFunction &MF = DAG.getMachineFunction();
20610   auto PtrVT = getPointerTy(MF.getDataLayout());
20611   int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
20612   MachinePointerInfo MPI =
20613       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
20614   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20615   Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
20616   std::pair<SDValue, SDValue> Tmp =
20617       BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
20618 
20619   if (IsStrict)
20620     return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
20621 
20622   return Tmp.first;
20623 }
20624 
20625 std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
20626     EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
20627     MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
20628   // Build the FILD
20629   SDVTList Tys;
20630   bool useSSE = isScalarFPTypeInSSEReg(DstVT);
20631   if (useSSE)
20632     Tys = DAG.getVTList(MVT::f80, MVT::Other);
20633   else
20634     Tys = DAG.getVTList(DstVT, MVT::Other);
20635 
20636   SDValue FILDOps[] = {Chain, Pointer};
20637   SDValue Result =
20638       DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
20639                               Alignment, MachineMemOperand::MOLoad);
20640   Chain = Result.getValue(1);
20641 
20642   if (useSSE) {
20643     MachineFunction &MF = DAG.getMachineFunction();
20644     unsigned SSFISize = DstVT.getStoreSize();
20645     int SSFI =
20646         MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
20647     auto PtrVT = getPointerTy(MF.getDataLayout());
20648     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20649     Tys = DAG.getVTList(MVT::Other);
20650     SDValue FSTOps[] = {Chain, Result, StackSlot};
20651     MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
20652         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
20653         MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
20654 
20655     Chain =
20656         DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
20657     Result = DAG.getLoad(
20658         DstVT, DL, Chain, StackSlot,
20659         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
20660     Chain = Result.getValue(1);
20661   }
20662 
20663   return { Result, Chain };
20664 }
20665 
20666 /// Horizontal vector math instructions may be slower than normal math with
20667 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
20668 /// implementation, and likely shuffle complexity of the alternate sequence.
20669 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
20670                                   const X86Subtarget &Subtarget) {
20671   bool IsOptimizingSize = DAG.shouldOptForSize();
20672   bool HasFastHOps = Subtarget.hasFastHorizontalOps();
20673   return !IsSingleSource || IsOptimizingSize || HasFastHOps;
20674 }
20675 
20676 /// 64-bit unsigned integer to double expansion.
20677 static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
20678                                    const X86Subtarget &Subtarget) {
20679   // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
20680   // when converting 0 when rounding toward negative infinity. Caller will
20681   // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
20682   assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!");
20683   // This algorithm is not obvious. Here it is what we're trying to output:
20684   /*
20685      movq       %rax,  %xmm0
20686      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
20687      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
20688      #ifdef __SSE3__
20689        haddpd   %xmm0, %xmm0
20690      #else
20691        pshufd   $0x4e, %xmm0, %xmm1
20692        addpd    %xmm1, %xmm0
20693      #endif
20694   */
20695 
20696   SDLoc dl(Op);
20697   LLVMContext *Context = DAG.getContext();
20698 
20699   // Build some magic constants.
20700   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
20701   Constant *C0 = ConstantDataVector::get(*Context, CV0);
20702   auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20703   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
20704 
20705   SmallVector<Constant*,2> CV1;
20706   CV1.push_back(
20707     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20708                                       APInt(64, 0x4330000000000000ULL))));
20709   CV1.push_back(
20710     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20711                                       APInt(64, 0x4530000000000000ULL))));
20712   Constant *C1 = ConstantVector::get(CV1);
20713   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
20714 
20715   // Load the 64-bit value into an XMM register.
20716   SDValue XR1 =
20717       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
20718   SDValue CLod0 = DAG.getLoad(
20719       MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
20720       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
20721   SDValue Unpck1 =
20722       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
20723 
20724   SDValue CLod1 = DAG.getLoad(
20725       MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
20726       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
20727   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
20728   // TODO: Are there any fast-math-flags to propagate here?
20729   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
20730   SDValue Result;
20731 
20732   if (Subtarget.hasSSE3() &&
20733       shouldUseHorizontalOp(true, DAG, Subtarget)) {
20734     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
20735   } else {
20736     SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
20737     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
20738   }
20739   Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
20740                        DAG.getIntPtrConstant(0, dl));
20741   return Result;
20742 }
20743 
20744 /// 32-bit unsigned integer to float expansion.
20745 static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
20746                                    const X86Subtarget &Subtarget) {
20747   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
20748   SDLoc dl(Op);
20749   // FP constant to bias correct the final result.
20750   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20751                                    MVT::f64);
20752 
20753   // Load the 32-bit value into an XMM register.
20754   SDValue Load =
20755       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
20756 
20757   // Zero out the upper parts of the register.
20758   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
20759 
20760   // Or the load with the bias.
20761   SDValue Or = DAG.getNode(
20762       ISD::OR, dl, MVT::v2i64,
20763       DAG.getBitcast(MVT::v2i64, Load),
20764       DAG.getBitcast(MVT::v2i64,
20765                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
20766   Or =
20767       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
20768                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
20769 
20770   if (Op.getNode()->isStrictFPOpcode()) {
20771     // Subtract the bias.
20772     // TODO: Are there any fast-math-flags to propagate here?
20773     SDValue Chain = Op.getOperand(0);
20774     SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
20775                               {Chain, Or, Bias});
20776 
20777     if (Op.getValueType() == Sub.getValueType())
20778       return Sub;
20779 
20780     // Handle final rounding.
20781     std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
20782         Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
20783 
20784     return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
20785   }
20786 
20787   // Subtract the bias.
20788   // TODO: Are there any fast-math-flags to propagate here?
20789   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
20790 
20791   // Handle final rounding.
20792   return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
20793 }
20794 
20795 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
20796                                      const X86Subtarget &Subtarget,
20797                                      const SDLoc &DL) {
20798   if (Op.getSimpleValueType() != MVT::v2f64)
20799     return SDValue();
20800 
20801   bool IsStrict = Op->isStrictFPOpcode();
20802 
20803   SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
20804   assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
20805 
20806   if (Subtarget.hasAVX512()) {
20807     if (!Subtarget.hasVLX()) {
20808       // Let generic type legalization widen this.
20809       if (!IsStrict)
20810         return SDValue();
20811       // Otherwise pad the integer input with 0s and widen the operation.
20812       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20813                        DAG.getConstant(0, DL, MVT::v2i32));
20814       SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
20815                                 {Op.getOperand(0), N0});
20816       SDValue Chain = Res.getValue(1);
20817       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
20818                         DAG.getIntPtrConstant(0, DL));
20819       return DAG.getMergeValues({Res, Chain}, DL);
20820     }
20821 
20822     // Legalize to v4i32 type.
20823     N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20824                      DAG.getUNDEF(MVT::v2i32));
20825     if (IsStrict)
20826       return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
20827                          {Op.getOperand(0), N0});
20828     return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
20829   }
20830 
20831   // Zero extend to 2i64, OR with the floating point representation of 2^52.
20832   // This gives us the floating point equivalent of 2^52 + the i32 integer
20833   // since double has 52-bits of mantissa. Then subtract 2^52 in floating
20834   // point leaving just our i32 integers in double format.
20835   SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
20836   SDValue VBias =
20837       DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), DL, MVT::v2f64);
20838   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
20839                            DAG.getBitcast(MVT::v2i64, VBias));
20840   Or = DAG.getBitcast(MVT::v2f64, Or);
20841 
20842   if (IsStrict)
20843     return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
20844                        {Op.getOperand(0), Or, VBias});
20845   return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
20846 }
20847 
20848 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
20849                                      const X86Subtarget &Subtarget) {
20850   SDLoc DL(Op);
20851   bool IsStrict = Op->isStrictFPOpcode();
20852   SDValue V = Op->getOperand(IsStrict ? 1 : 0);
20853   MVT VecIntVT = V.getSimpleValueType();
20854   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
20855          "Unsupported custom type");
20856 
20857   if (Subtarget.hasAVX512()) {
20858     // With AVX512, but not VLX we need to widen to get a 512-bit result type.
20859     assert(!Subtarget.hasVLX() && "Unexpected features");
20860     MVT VT = Op->getSimpleValueType(0);
20861 
20862     // v8i32->v8f64 is legal with AVX512 so just return it.
20863     if (VT == MVT::v8f64)
20864       return Op;
20865 
20866     assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&
20867            "Unexpected VT!");
20868     MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
20869     MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
20870     // Need to concat with zero vector for strict fp to avoid spurious
20871     // exceptions.
20872     SDValue Tmp =
20873         IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
20874     V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
20875                     DAG.getIntPtrConstant(0, DL));
20876     SDValue Res, Chain;
20877     if (IsStrict) {
20878       Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
20879                         {Op->getOperand(0), V});
20880       Chain = Res.getValue(1);
20881     } else {
20882       Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
20883     }
20884 
20885     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20886                       DAG.getIntPtrConstant(0, DL));
20887 
20888     if (IsStrict)
20889       return DAG.getMergeValues({Res, Chain}, DL);
20890     return Res;
20891   }
20892 
20893   if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
20894       Op->getSimpleValueType(0) == MVT::v4f64) {
20895     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
20896     Constant *Bias = ConstantFP::get(
20897         *DAG.getContext(),
20898         APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
20899     auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20900     SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
20901     SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
20902     SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
20903     SDValue VBias = DAG.getMemIntrinsicNode(
20904         X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
20905         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(8),
20906         MachineMemOperand::MOLoad);
20907 
20908     SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
20909                              DAG.getBitcast(MVT::v4i64, VBias));
20910     Or = DAG.getBitcast(MVT::v4f64, Or);
20911 
20912     if (IsStrict)
20913       return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
20914                          {Op.getOperand(0), Or, VBias});
20915     return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
20916   }
20917 
20918   // The algorithm is the following:
20919   // #ifdef __SSE4_1__
20920   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20921   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20922   //                                 (uint4) 0x53000000, 0xaa);
20923   // #else
20924   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20925   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
20926   // #endif
20927   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20928   //     return (float4) lo + fhi;
20929 
20930   bool Is128 = VecIntVT == MVT::v4i32;
20931   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
20932   // If we convert to something else than the supported type, e.g., to v4f64,
20933   // abort early.
20934   if (VecFloatVT != Op->getSimpleValueType(0))
20935     return SDValue();
20936 
20937   // In the #idef/#else code, we have in common:
20938   // - The vector of constants:
20939   // -- 0x4b000000
20940   // -- 0x53000000
20941   // - A shift:
20942   // -- v >> 16
20943 
20944   // Create the splat vector for 0x4b000000.
20945   SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
20946   // Create the splat vector for 0x53000000.
20947   SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
20948 
20949   // Create the right shift.
20950   SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
20951   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
20952 
20953   SDValue Low, High;
20954   if (Subtarget.hasSSE41()) {
20955     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
20956     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20957     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
20958     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
20959     // Low will be bitcasted right away, so do not bother bitcasting back to its
20960     // original type.
20961     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
20962                       VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
20963     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20964     //                                 (uint4) 0x53000000, 0xaa);
20965     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
20966     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
20967     // High will be bitcasted right away, so do not bother bitcasting back to
20968     // its original type.
20969     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
20970                        VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
20971   } else {
20972     SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
20973     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20974     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
20975     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
20976 
20977     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
20978     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
20979   }
20980 
20981   // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
20982   SDValue VecCstFSub = DAG.getConstantFP(
20983       APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
20984 
20985   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20986   // NOTE: By using fsub of a positive constant instead of fadd of a negative
20987   // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
20988   // enabled. See PR24512.
20989   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
20990   // TODO: Are there any fast-math-flags to propagate here?
20991   //     (float4) lo;
20992   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
20993   //     return (float4) lo + fhi;
20994   if (IsStrict) {
20995     SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
20996                                 {Op.getOperand(0), HighBitcast, VecCstFSub});
20997     return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
20998                        {FHigh.getValue(1), LowBitcast, FHigh});
20999   }
21000 
21001   SDValue FHigh =
21002       DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
21003   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
21004 }
21005 
21006 static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
21007                                    const X86Subtarget &Subtarget) {
21008   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
21009   SDValue N0 = Op.getOperand(OpNo);
21010   MVT SrcVT = N0.getSimpleValueType();
21011   SDLoc dl(Op);
21012 
21013   switch (SrcVT.SimpleTy) {
21014   default:
21015     llvm_unreachable("Custom UINT_TO_FP is not supported!");
21016   case MVT::v2i32:
21017     return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
21018   case MVT::v4i32:
21019   case MVT::v8i32:
21020     return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
21021   case MVT::v2i64:
21022   case MVT::v4i64:
21023     return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
21024   }
21025 }
21026 
21027 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
21028                                            SelectionDAG &DAG) const {
21029   bool IsStrict = Op->isStrictFPOpcode();
21030   unsigned OpNo = IsStrict ? 1 : 0;
21031   SDValue Src = Op.getOperand(OpNo);
21032   SDLoc dl(Op);
21033   auto PtrVT = getPointerTy(DAG.getDataLayout());
21034   MVT SrcVT = Src.getSimpleValueType();
21035   MVT DstVT = Op->getSimpleValueType(0);
21036   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21037 
21038   if (DstVT == MVT::f128)
21039     return SDValue();
21040 
21041   if (DstVT.isVector())
21042     return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
21043 
21044   if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
21045     return LowerWin64_INT128_TO_FP(Op, DAG);
21046 
21047   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
21048     return Extract;
21049 
21050   if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
21051       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
21052     // Conversions from unsigned i32 to f32/f64 are legal,
21053     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
21054     return Op;
21055   }
21056 
21057   // Promote i32 to i64 and use a signed conversion on 64-bit targets.
21058   if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
21059     Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
21060     if (IsStrict)
21061       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
21062                          {Chain, Src});
21063     return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
21064   }
21065 
21066   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
21067     return V;
21068   if (SDValue V = LowerI64IntToFP16(Op, DAG, Subtarget))
21069     return V;
21070 
21071   // The transform for i64->f64 isn't correct for 0 when rounding to negative
21072   // infinity. It produces -0.0, so disable under strictfp.
21073   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64 && !IsStrict)
21074     return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
21075   if (SrcVT == MVT::i32 && X86ScalarSSEf64 && DstVT != MVT::f80)
21076     return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
21077   if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
21078       (DstVT == MVT::f32 || DstVT == MVT::f64))
21079     return SDValue();
21080 
21081   // Make a 64-bit buffer, and use it to build an FILD.
21082   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
21083   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
21084   Align SlotAlign(8);
21085   MachinePointerInfo MPI =
21086     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
21087   if (SrcVT == MVT::i32) {
21088     SDValue OffsetSlot =
21089         DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl);
21090     SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
21091     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
21092                                   OffsetSlot, MPI.getWithOffset(4), SlotAlign);
21093     std::pair<SDValue, SDValue> Tmp =
21094         BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
21095     if (IsStrict)
21096       return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
21097 
21098     return Tmp.first;
21099   }
21100 
21101   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
21102   SDValue ValueToStore = Src;
21103   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
21104     // Bitcasting to f64 here allows us to do a single 64-bit store from
21105     // an SSE register, avoiding the store forwarding penalty that would come
21106     // with two 32-bit stores.
21107     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
21108   }
21109   SDValue Store =
21110       DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
21111   // For i64 source, we need to add the appropriate power of 2 if the input
21112   // was negative. We must be careful to do the computation in x87 extended
21113   // precision, not in SSE.
21114   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21115   SDValue Ops[] = { Store, StackSlot };
21116   SDValue Fild =
21117       DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
21118                               SlotAlign, MachineMemOperand::MOLoad);
21119   Chain = Fild.getValue(1);
21120 
21121 
21122   // Check whether the sign bit is set.
21123   SDValue SignSet = DAG.getSetCC(
21124       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
21125       Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
21126 
21127   // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
21128   APInt FF(64, 0x5F80000000000000ULL);
21129   SDValue FudgePtr = DAG.getConstantPool(
21130       ConstantInt::get(*DAG.getContext(), FF), PtrVT);
21131   Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
21132 
21133   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
21134   SDValue Zero = DAG.getIntPtrConstant(0, dl);
21135   SDValue Four = DAG.getIntPtrConstant(4, dl);
21136   SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
21137   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
21138 
21139   // Load the value out, extending it from f32 to f80.
21140   SDValue Fudge = DAG.getExtLoad(
21141       ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
21142       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
21143       CPAlignment);
21144   Chain = Fudge.getValue(1);
21145   // Extend everything to 80 bits to force it to be done on x87.
21146   // TODO: Are there any fast-math-flags to propagate here?
21147   if (IsStrict) {
21148     SDValue Add = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::f80, MVT::Other},
21149                               {Chain, Fild, Fudge});
21150     // STRICT_FP_ROUND can't handle equal types.
21151     if (DstVT == MVT::f80)
21152       return Add;
21153     return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
21154                        {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
21155   }
21156   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
21157   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
21158                      DAG.getIntPtrConstant(0, dl));
21159 }
21160 
21161 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
21162 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
21163 // just return an SDValue().
21164 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
21165 // to i16, i32 or i64, and we lower it to a legal sequence and return the
21166 // result.
21167 SDValue
21168 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
21169                                    bool IsSigned, SDValue &Chain) const {
21170   bool IsStrict = Op->isStrictFPOpcode();
21171   SDLoc DL(Op);
21172 
21173   EVT DstTy = Op.getValueType();
21174   SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
21175   EVT TheVT = Value.getValueType();
21176   auto PtrVT = getPointerTy(DAG.getDataLayout());
21177 
21178   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
21179     // f16 must be promoted before using the lowering in this routine.
21180     // fp128 does not use this lowering.
21181     return SDValue();
21182   }
21183 
21184   // If using FIST to compute an unsigned i64, we'll need some fixup
21185   // to handle values above the maximum signed i64.  A FIST is always
21186   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
21187   bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
21188 
21189   // FIXME: This does not generate an invalid exception if the input does not
21190   // fit in i32. PR44019
21191   if (!IsSigned && DstTy != MVT::i64) {
21192     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
21193     // The low 32 bits of the fist result will have the correct uint32 result.
21194     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
21195     DstTy = MVT::i64;
21196   }
21197 
21198   assert(DstTy.getSimpleVT() <= MVT::i64 &&
21199          DstTy.getSimpleVT() >= MVT::i16 &&
21200          "Unknown FP_TO_INT to lower!");
21201 
21202   // We lower FP->int64 into FISTP64 followed by a load from a temporary
21203   // stack slot.
21204   MachineFunction &MF = DAG.getMachineFunction();
21205   unsigned MemSize = DstTy.getStoreSize();
21206   int SSFI =
21207       MF.getFrameInfo().CreateStackObject(MemSize, Align(MemSize), false);
21208   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
21209 
21210   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21211 
21212   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
21213 
21214   if (UnsignedFixup) {
21215     //
21216     // Conversion to unsigned i64 is implemented with a select,
21217     // depending on whether the source value fits in the range
21218     // of a signed i64.  Let Thresh be the FP equivalent of
21219     // 0x8000000000000000ULL.
21220     //
21221     //  Adjust = (Value >= Thresh) ? 0x80000000 : 0;
21222     //  FltOfs = (Value >= Thresh) ? 0x80000000 : 0;
21223     //  FistSrc = (Value - FltOfs);
21224     //  Fist-to-mem64 FistSrc
21225     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
21226     //  to XOR'ing the high 32 bits with Adjust.
21227     //
21228     // Being a power of 2, Thresh is exactly representable in all FP formats.
21229     // For X87 we'd like to use the smallest FP type for this constant, but
21230     // for DAG type consistency we have to match the FP operand type.
21231 
21232     APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
21233     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
21234     bool LosesInfo = false;
21235     if (TheVT == MVT::f64)
21236       // The rounding mode is irrelevant as the conversion should be exact.
21237       Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
21238                               &LosesInfo);
21239     else if (TheVT == MVT::f80)
21240       Status = Thresh.convert(APFloat::x87DoubleExtended(),
21241                               APFloat::rmNearestTiesToEven, &LosesInfo);
21242 
21243     assert(Status == APFloat::opOK && !LosesInfo &&
21244            "FP conversion should have been exact");
21245 
21246     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
21247 
21248     EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
21249                                    *DAG.getContext(), TheVT);
21250     SDValue Cmp;
21251     if (IsStrict) {
21252       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE, Chain,
21253                          /*IsSignaling*/ true);
21254       Chain = Cmp.getValue(1);
21255     } else {
21256       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE);
21257     }
21258 
21259     // Our preferred lowering of
21260     //
21261     // (Value >= Thresh) ? 0x8000000000000000ULL : 0
21262     //
21263     // is
21264     //
21265     // (Value >= Thresh) << 63
21266     //
21267     // but since we can get here after LegalOperations, DAGCombine might do the
21268     // wrong thing if we create a select. So, directly create the preferred
21269     // version.
21270     SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Cmp);
21271     SDValue Const63 = DAG.getConstant(63, DL, MVT::i8);
21272     Adjust = DAG.getNode(ISD::SHL, DL, MVT::i64, Zext, Const63);
21273 
21274     SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp, ThreshVal,
21275                                    DAG.getConstantFP(0.0, DL, TheVT));
21276 
21277     if (IsStrict) {
21278       Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
21279                           { Chain, Value, FltOfs });
21280       Chain = Value.getValue(1);
21281     } else
21282       Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
21283   }
21284 
21285   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
21286 
21287   // FIXME This causes a redundant load/store if the SSE-class value is already
21288   // in memory, such as if it is on the callstack.
21289   if (isScalarFPTypeInSSEReg(TheVT)) {
21290     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
21291     Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
21292     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21293     SDValue Ops[] = { Chain, StackSlot };
21294 
21295     unsigned FLDSize = TheVT.getStoreSize();
21296     assert(FLDSize <= MemSize && "Stack slot not big enough");
21297     MachineMemOperand *MMO = MF.getMachineMemOperand(
21298         MPI, MachineMemOperand::MOLoad, FLDSize, Align(FLDSize));
21299     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
21300     Chain = Value.getValue(1);
21301   }
21302 
21303   // Build the FP_TO_INT*_IN_MEM
21304   MachineMemOperand *MMO = MF.getMachineMemOperand(
21305       MPI, MachineMemOperand::MOStore, MemSize, Align(MemSize));
21306   SDValue Ops[] = { Chain, Value, StackSlot };
21307   SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
21308                                          DAG.getVTList(MVT::Other),
21309                                          Ops, DstTy, MMO);
21310 
21311   SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
21312   Chain = Res.getValue(1);
21313 
21314   // If we need an unsigned fixup, XOR the result with adjust.
21315   if (UnsignedFixup)
21316     Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
21317 
21318   return Res;
21319 }
21320 
21321 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
21322                               const X86Subtarget &Subtarget) {
21323   MVT VT = Op.getSimpleValueType();
21324   SDValue In = Op.getOperand(0);
21325   MVT InVT = In.getSimpleValueType();
21326   SDLoc dl(Op);
21327   unsigned Opc = Op.getOpcode();
21328 
21329   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
21330   assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&
21331          "Unexpected extension opcode");
21332   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
21333          "Expected same number of elements");
21334   assert((VT.getVectorElementType() == MVT::i16 ||
21335           VT.getVectorElementType() == MVT::i32 ||
21336           VT.getVectorElementType() == MVT::i64) &&
21337          "Unexpected element type");
21338   assert((InVT.getVectorElementType() == MVT::i8 ||
21339           InVT.getVectorElementType() == MVT::i16 ||
21340           InVT.getVectorElementType() == MVT::i32) &&
21341          "Unexpected element type");
21342 
21343   unsigned ExtendInVecOpc = getOpcode_EXTEND_VECTOR_INREG(Opc);
21344 
21345   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
21346     assert(InVT == MVT::v32i8 && "Unexpected VT!");
21347     return splitVectorIntUnary(Op, DAG);
21348   }
21349 
21350   if (Subtarget.hasInt256())
21351     return Op;
21352 
21353   // Optimize vectors in AVX mode:
21354   //
21355   //   v8i16 -> v8i32
21356   //   Use vpmovzwd for 4 lower elements  v8i16 -> v4i32.
21357   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
21358   //   Concat upper and lower parts.
21359   //
21360   //   v4i32 -> v4i64
21361   //   Use vpmovzdq for 4 lower elements  v4i32 -> v2i64.
21362   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
21363   //   Concat upper and lower parts.
21364   //
21365   MVT HalfVT = VT.getHalfNumVectorElementsVT();
21366   SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
21367 
21368   // Short-circuit if we can determine that each 128-bit half is the same value.
21369   // Otherwise, this is difficult to match and optimize.
21370   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
21371     if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
21372       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
21373 
21374   SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
21375   SDValue Undef = DAG.getUNDEF(InVT);
21376   bool NeedZero = Opc == ISD::ZERO_EXTEND;
21377   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
21378   OpHi = DAG.getBitcast(HalfVT, OpHi);
21379 
21380   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
21381 }
21382 
21383 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
21384 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
21385                                    const SDLoc &dl, SelectionDAG &DAG) {
21386   assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
21387   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
21388                            DAG.getIntPtrConstant(0, dl));
21389   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
21390                            DAG.getIntPtrConstant(8, dl));
21391   Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
21392   Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
21393   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
21394   return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21395 }
21396 
21397 static  SDValue LowerZERO_EXTEND_Mask(SDValue Op,
21398                                       const X86Subtarget &Subtarget,
21399                                       SelectionDAG &DAG) {
21400   MVT VT = Op->getSimpleValueType(0);
21401   SDValue In = Op->getOperand(0);
21402   MVT InVT = In.getSimpleValueType();
21403   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
21404   SDLoc DL(Op);
21405   unsigned NumElts = VT.getVectorNumElements();
21406 
21407   // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
21408   // avoids a constant pool load.
21409   if (VT.getVectorElementType() != MVT::i8) {
21410     SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
21411     return DAG.getNode(ISD::SRL, DL, VT, Extend,
21412                        DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
21413   }
21414 
21415   // Extend VT if BWI is not supported.
21416   MVT ExtVT = VT;
21417   if (!Subtarget.hasBWI()) {
21418     // If v16i32 is to be avoided, we'll need to split and concatenate.
21419     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
21420       return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
21421 
21422     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
21423   }
21424 
21425   // Widen to 512-bits if VLX is not supported.
21426   MVT WideVT = ExtVT;
21427   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
21428     NumElts *= 512 / ExtVT.getSizeInBits();
21429     InVT = MVT::getVectorVT(MVT::i1, NumElts);
21430     In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
21431                      In, DAG.getIntPtrConstant(0, DL));
21432     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
21433                               NumElts);
21434   }
21435 
21436   SDValue One = DAG.getConstant(1, DL, WideVT);
21437   SDValue Zero = DAG.getConstant(0, DL, WideVT);
21438 
21439   SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
21440 
21441   // Truncate if we had to extend above.
21442   if (VT != ExtVT) {
21443     WideVT = MVT::getVectorVT(MVT::i8, NumElts);
21444     SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
21445   }
21446 
21447   // Extract back to 128/256-bit if we widened.
21448   if (WideVT != VT)
21449     SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
21450                               DAG.getIntPtrConstant(0, DL));
21451 
21452   return SelectedVal;
21453 }
21454 
21455 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
21456                                 SelectionDAG &DAG) {
21457   SDValue In = Op.getOperand(0);
21458   MVT SVT = In.getSimpleValueType();
21459 
21460   if (SVT.getVectorElementType() == MVT::i1)
21461     return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
21462 
21463   assert(Subtarget.hasAVX() && "Expected AVX support");
21464   return LowerAVXExtend(Op, DAG, Subtarget);
21465 }
21466 
21467 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
21468 /// It makes use of the fact that vectors with enough leading sign/zero bits
21469 /// prevent the PACKSS/PACKUS from saturating the results.
21470 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
21471 /// within each 128-bit lane.
21472 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
21473                                       const SDLoc &DL, SelectionDAG &DAG,
21474                                       const X86Subtarget &Subtarget) {
21475   assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
21476          "Unexpected PACK opcode");
21477   assert(DstVT.isVector() && "VT not a vector?");
21478 
21479   // Requires SSE2 for PACKSS (SSE41 PACKUSDW is handled below).
21480   if (!Subtarget.hasSSE2())
21481     return SDValue();
21482 
21483   EVT SrcVT = In.getValueType();
21484 
21485   // No truncation required, we might get here due to recursive calls.
21486   if (SrcVT == DstVT)
21487     return In;
21488 
21489   // We only support vector truncation to 64bits or greater from a
21490   // 128bits or greater source.
21491   unsigned DstSizeInBits = DstVT.getSizeInBits();
21492   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
21493   if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
21494     return SDValue();
21495 
21496   unsigned NumElems = SrcVT.getVectorNumElements();
21497   if (!isPowerOf2_32(NumElems))
21498     return SDValue();
21499 
21500   LLVMContext &Ctx = *DAG.getContext();
21501   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
21502   assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
21503 
21504   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
21505 
21506   // Pack to the largest type possible:
21507   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
21508   EVT InVT = MVT::i16, OutVT = MVT::i8;
21509   if (SrcVT.getScalarSizeInBits() > 16 &&
21510       (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
21511     InVT = MVT::i32;
21512     OutVT = MVT::i16;
21513   }
21514 
21515   // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
21516   if (SrcVT.is128BitVector()) {
21517     InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
21518     OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
21519     In = DAG.getBitcast(InVT, In);
21520     SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, DAG.getUNDEF(InVT));
21521     Res = extractSubVector(Res, 0, DAG, DL, 64);
21522     return DAG.getBitcast(DstVT, Res);
21523   }
21524 
21525   // Split lower/upper subvectors.
21526   SDValue Lo, Hi;
21527   std::tie(Lo, Hi) = splitVector(In, DAG, DL);
21528 
21529   unsigned SubSizeInBits = SrcSizeInBits / 2;
21530   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
21531   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
21532 
21533   // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
21534   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
21535     Lo = DAG.getBitcast(InVT, Lo);
21536     Hi = DAG.getBitcast(InVT, Hi);
21537     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
21538     return DAG.getBitcast(DstVT, Res);
21539   }
21540 
21541   // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
21542   // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
21543   if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
21544     Lo = DAG.getBitcast(InVT, Lo);
21545     Hi = DAG.getBitcast(InVT, Hi);
21546     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
21547 
21548     // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
21549     // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
21550     // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
21551     SmallVector<int, 64> Mask;
21552     int Scale = 64 / OutVT.getScalarSizeInBits();
21553     narrowShuffleMaskElts(Scale, { 0, 2, 1, 3 }, Mask);
21554     Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
21555 
21556     if (DstVT.is256BitVector())
21557       return DAG.getBitcast(DstVT, Res);
21558 
21559     // If 512bit -> 128bit truncate another stage.
21560     EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
21561     Res = DAG.getBitcast(PackedVT, Res);
21562     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
21563   }
21564 
21565   // Recursively pack lower/upper subvectors, concat result and pack again.
21566   assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
21567   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
21568   Lo = truncateVectorWithPACK(Opcode, PackedVT, Lo, DL, DAG, Subtarget);
21569   Hi = truncateVectorWithPACK(Opcode, PackedVT, Hi, DL, DAG, Subtarget);
21570 
21571   PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
21572   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
21573   return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
21574 }
21575 
21576 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
21577                                   const X86Subtarget &Subtarget) {
21578 
21579   SDLoc DL(Op);
21580   MVT VT = Op.getSimpleValueType();
21581   SDValue In = Op.getOperand(0);
21582   MVT InVT = In.getSimpleValueType();
21583 
21584   assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
21585 
21586   // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
21587   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
21588   if (InVT.getScalarSizeInBits() <= 16) {
21589     if (Subtarget.hasBWI()) {
21590       // legal, will go to VPMOVB2M, VPMOVW2M
21591       if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
21592         // We need to shift to get the lsb into sign position.
21593         // Shift packed bytes not supported natively, bitcast to word
21594         MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
21595         In = DAG.getNode(ISD::SHL, DL, ExtVT,
21596                          DAG.getBitcast(ExtVT, In),
21597                          DAG.getConstant(ShiftInx, DL, ExtVT));
21598         In = DAG.getBitcast(InVT, In);
21599       }
21600       return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
21601                           In, ISD::SETGT);
21602     }
21603     // Use TESTD/Q, extended vector to packed dword/qword.
21604     assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
21605            "Unexpected vector type.");
21606     unsigned NumElts = InVT.getVectorNumElements();
21607     assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
21608     // We need to change to a wider element type that we have support for.
21609     // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
21610     // For 16 element vectors we extend to v16i32 unless we are explicitly
21611     // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
21612     // we need to split into two 8 element vectors which we can extend to v8i32,
21613     // truncate and concat the results. There's an additional complication if
21614     // the original type is v16i8. In that case we can't split the v16i8
21615     // directly, so we need to shuffle high elements to low and use
21616     // sign_extend_vector_inreg.
21617     if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
21618       SDValue Lo, Hi;
21619       if (InVT == MVT::v16i8) {
21620         Lo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, In);
21621         Hi = DAG.getVectorShuffle(
21622             InVT, DL, In, In,
21623             {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
21624         Hi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, Hi);
21625       } else {
21626         assert(InVT == MVT::v16i16 && "Unexpected VT!");
21627         Lo = extract128BitVector(In, 0, DAG, DL);
21628         Hi = extract128BitVector(In, 8, DAG, DL);
21629       }
21630       // We're split now, just emit two truncates and a concat. The two
21631       // truncates will trigger legalization to come back to this function.
21632       Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
21633       Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
21634       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
21635     }
21636     // We either have 8 elements or we're allowed to use 512-bit vectors.
21637     // If we have VLX, we want to use the narrowest vector that can get the
21638     // job done so we use vXi32.
21639     MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
21640     MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
21641     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
21642     InVT = ExtVT;
21643     ShiftInx = InVT.getScalarSizeInBits() - 1;
21644   }
21645 
21646   if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
21647     // We need to shift to get the lsb into sign position.
21648     In = DAG.getNode(ISD::SHL, DL, InVT, In,
21649                      DAG.getConstant(ShiftInx, DL, InVT));
21650   }
21651   // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
21652   if (Subtarget.hasDQI())
21653     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
21654   return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
21655 }
21656 
21657 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
21658   SDLoc DL(Op);
21659   MVT VT = Op.getSimpleValueType();
21660   SDValue In = Op.getOperand(0);
21661   MVT InVT = In.getSimpleValueType();
21662   unsigned InNumEltBits = InVT.getScalarSizeInBits();
21663 
21664   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
21665          "Invalid TRUNCATE operation");
21666 
21667   // If we're called by the type legalizer, handle a few cases.
21668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21669   if (!TLI.isTypeLegal(InVT)) {
21670     if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
21671         VT.is128BitVector()) {
21672       assert((InVT == MVT::v16i64 || Subtarget.hasVLX()) &&
21673              "Unexpected subtarget!");
21674       // The default behavior is to truncate one step, concatenate, and then
21675       // truncate the remainder. We'd rather produce two 64-bit results and
21676       // concatenate those.
21677       SDValue Lo, Hi;
21678       std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
21679 
21680       EVT LoVT, HiVT;
21681       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
21682 
21683       Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
21684       Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
21685       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
21686     }
21687 
21688     // Otherwise let default legalization handle it.
21689     return SDValue();
21690   }
21691 
21692   if (VT.getVectorElementType() == MVT::i1)
21693     return LowerTruncateVecI1(Op, DAG, Subtarget);
21694 
21695   // vpmovqb/w/d, vpmovdb/w, vpmovwb
21696   if (Subtarget.hasAVX512()) {
21697     if (InVT == MVT::v32i16 && !Subtarget.hasBWI()) {
21698       assert(VT == MVT::v32i8 && "Unexpected VT!");
21699       return splitVectorIntUnary(Op, DAG);
21700     }
21701 
21702     // word to byte only under BWI. Otherwise we have to promoted to v16i32
21703     // and then truncate that. But we should only do that if we haven't been
21704     // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
21705     // handled by isel patterns.
21706     if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
21707         Subtarget.canExtendTo512DQ())
21708       return Op;
21709   }
21710 
21711   unsigned NumPackedSignBits = std::min<unsigned>(VT.getScalarSizeInBits(), 16);
21712   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
21713 
21714   // Truncate with PACKUS if we are truncating a vector with leading zero bits
21715   // that extend all the way to the packed/truncated value.
21716   // Pre-SSE41 we can only use PACKUSWB.
21717   KnownBits Known = DAG.computeKnownBits(In);
21718   if ((InNumEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
21719     if (SDValue V =
21720             truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget))
21721       return V;
21722 
21723   // Truncate with PACKSS if we are truncating a vector with sign-bits that
21724   // extend all the way to the packed/truncated value.
21725   if ((InNumEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
21726     if (SDValue V =
21727             truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget))
21728       return V;
21729 
21730   // Handle truncation of V256 to V128 using shuffles.
21731   assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
21732 
21733   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
21734     In = DAG.getBitcast(MVT::v8i32, In);
21735 
21736     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
21737     if (Subtarget.hasInt256()) {
21738       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
21739       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
21740       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
21741                          DAG.getIntPtrConstant(0, DL));
21742     }
21743 
21744     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
21745                                DAG.getIntPtrConstant(0, DL));
21746     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
21747                                DAG.getIntPtrConstant(4, DL));
21748     static const int ShufMask[] = {0, 2, 4, 6};
21749     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
21750   }
21751 
21752   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
21753     In = DAG.getBitcast(MVT::v32i8, In);
21754 
21755     // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
21756     if (Subtarget.hasInt256()) {
21757       // The PSHUFB mask:
21758       static const int ShufMask1[] = { 0,  1,  4,  5,  8,  9, 12, 13,
21759                                       -1, -1, -1, -1, -1, -1, -1, -1,
21760                                       16, 17, 20, 21, 24, 25, 28, 29,
21761                                       -1, -1, -1, -1, -1, -1, -1, -1 };
21762       In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
21763       In = DAG.getBitcast(MVT::v4i64, In);
21764 
21765       static const int ShufMask2[] = {0, 2, -1, -1};
21766       In = DAG.getVectorShuffle(MVT::v4i64, DL, In, In, ShufMask2);
21767       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16,
21768                          DAG.getBitcast(MVT::v16i16, In),
21769                          DAG.getIntPtrConstant(0, DL));
21770     }
21771 
21772     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v16i8, In,
21773                                DAG.getIntPtrConstant(0, DL));
21774     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v16i8, In,
21775                                DAG.getIntPtrConstant(16, DL));
21776 
21777     // The PSHUFB mask:
21778     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
21779                                    -1, -1, -1, -1, -1, -1, -1, -1};
21780 
21781     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, OpLo, ShufMask1);
21782     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, OpHi, ShufMask1);
21783 
21784     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
21785     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
21786 
21787     // The MOVLHPS Mask:
21788     static const int ShufMask2[] = {0, 1, 4, 5};
21789     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
21790     return DAG.getBitcast(MVT::v8i16, res);
21791   }
21792 
21793   if (VT == MVT::v16i8 && InVT == MVT::v16i16) {
21794     // Use an AND to zero uppper bits for PACKUS.
21795     In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(255, DL, InVT));
21796 
21797     SDValue InLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
21798                                DAG.getIntPtrConstant(0, DL));
21799     SDValue InHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
21800                                DAG.getIntPtrConstant(8, DL));
21801     return DAG.getNode(X86ISD::PACKUS, DL, VT, InLo, InHi);
21802   }
21803 
21804   llvm_unreachable("All 256->128 cases should have been handled above!");
21805 }
21806 
21807 // We can leverage the specific way the "cvttps2dq/cvttpd2dq" instruction
21808 // behaves on out of range inputs to generate optimized conversions.
21809 static SDValue expandFP_TO_UINT_SSE(MVT VT, SDValue Src, const SDLoc &dl,
21810                                     SelectionDAG &DAG,
21811                                     const X86Subtarget &Subtarget) {
21812   MVT SrcVT = Src.getSimpleValueType();
21813   unsigned DstBits = VT.getScalarSizeInBits();
21814   assert(DstBits == 32 && "expandFP_TO_UINT_SSE - only vXi32 supported");
21815 
21816   // Calculate the converted result for values in the range 0 to
21817   // 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
21818   SDValue Small = DAG.getNode(X86ISD::CVTTP2SI, dl, VT, Src);
21819   SDValue Big =
21820       DAG.getNode(X86ISD::CVTTP2SI, dl, VT,
21821                   DAG.getNode(ISD::FSUB, dl, SrcVT, Src,
21822                               DAG.getConstantFP(2147483648.0f, dl, SrcVT)));
21823 
21824   // The "CVTTP2SI" instruction conveniently sets the sign bit if
21825   // and only if the value was out of range. So we can use that
21826   // as our indicator that we rather use "Big" instead of "Small".
21827   //
21828   // Use "Small" if "IsOverflown" has all bits cleared
21829   // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
21830 
21831   // AVX1 can't use the signsplat masking for 256-bit vectors - we have to
21832   // use the slightly slower blendv select instead.
21833   if (VT == MVT::v8i32 && !Subtarget.hasAVX2()) {
21834     SDValue Overflow = DAG.getNode(ISD::OR, dl, VT, Small, Big);
21835     return DAG.getNode(X86ISD::BLENDV, dl, VT, Small, Overflow, Small);
21836   }
21837 
21838   SDValue IsOverflown =
21839       DAG.getNode(X86ISD::VSRAI, dl, VT, Small,
21840                   DAG.getTargetConstant(DstBits - 1, dl, MVT::i8));
21841   return DAG.getNode(ISD::OR, dl, VT, Small,
21842                      DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
21843 }
21844 
21845 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
21846   bool IsStrict = Op->isStrictFPOpcode();
21847   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
21848                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
21849   MVT VT = Op->getSimpleValueType(0);
21850   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21851   SDValue Chain = IsStrict ? Op->getOperand(0) : SDValue();
21852   MVT SrcVT = Src.getSimpleValueType();
21853   SDLoc dl(Op);
21854 
21855   SDValue Res;
21856   if (VT.isVector()) {
21857     if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
21858       MVT ResVT = MVT::v4i32;
21859       MVT TruncVT = MVT::v4i1;
21860       unsigned Opc;
21861       if (IsStrict)
21862         Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
21863       else
21864         Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
21865 
21866       if (!IsSigned && !Subtarget.hasVLX()) {
21867         assert(Subtarget.useAVX512Regs() && "Unexpected features!");
21868         // Widen to 512-bits.
21869         ResVT = MVT::v8i32;
21870         TruncVT = MVT::v8i1;
21871         Opc = Op.getOpcode();
21872         // Need to concat with zero vector for strict fp to avoid spurious
21873         // exceptions.
21874         // TODO: Should we just do this for non-strict as well?
21875         SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
21876                                : DAG.getUNDEF(MVT::v8f64);
21877         Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
21878                           DAG.getIntPtrConstant(0, dl));
21879       }
21880       if (IsStrict) {
21881         Res = DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Chain, Src});
21882         Chain = Res.getValue(1);
21883       } else {
21884         Res = DAG.getNode(Opc, dl, ResVT, Src);
21885       }
21886 
21887       Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
21888       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
21889                         DAG.getIntPtrConstant(0, dl));
21890       if (IsStrict)
21891         return DAG.getMergeValues({Res, Chain}, dl);
21892       return Res;
21893     }
21894 
21895     if (Subtarget.hasFP16() && SrcVT.getVectorElementType() == MVT::f16) {
21896       if (VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16)
21897         return Op;
21898 
21899       MVT ResVT = VT;
21900       MVT EleVT = VT.getVectorElementType();
21901       if (EleVT != MVT::i64)
21902         ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
21903 
21904       if (SrcVT != MVT::v8f16) {
21905         SDValue Tmp =
21906             IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
21907         SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
21908         Ops[0] = Src;
21909         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
21910       }
21911 
21912       if (IsStrict) {
21913         Res = DAG.getNode(IsSigned ? X86ISD::STRICT_CVTTP2SI
21914                                    : X86ISD::STRICT_CVTTP2UI,
21915                           dl, {ResVT, MVT::Other}, {Chain, Src});
21916         Chain = Res.getValue(1);
21917       } else {
21918         Res = DAG.getNode(IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI, dl,
21919                           ResVT, Src);
21920       }
21921 
21922       // TODO: Need to add exception check code for strict FP.
21923       if (EleVT.getSizeInBits() < 16) {
21924         ResVT = MVT::getVectorVT(EleVT, 8);
21925         Res = DAG.getNode(ISD::TRUNCATE, dl, ResVT, Res);
21926       }
21927 
21928       if (ResVT != VT)
21929         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21930                           DAG.getIntPtrConstant(0, dl));
21931 
21932       if (IsStrict)
21933         return DAG.getMergeValues({Res, Chain}, dl);
21934       return Res;
21935     }
21936 
21937     if (VT == MVT::v8i16 && (SrcVT == MVT::v8f32 || SrcVT == MVT::v8f64)) {
21938       if (IsStrict) {
21939         Res = DAG.getNode(IsSigned ? ISD::STRICT_FP_TO_SINT
21940                                    : ISD::STRICT_FP_TO_UINT,
21941                           dl, {MVT::v8i32, MVT::Other}, {Chain, Src});
21942         Chain = Res.getValue(1);
21943       } else {
21944         Res = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl,
21945                           MVT::v8i32, Src);
21946       }
21947 
21948       // TODO: Need to add exception check code for strict FP.
21949       Res = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i16, Res);
21950 
21951       if (IsStrict)
21952         return DAG.getMergeValues({Res, Chain}, dl);
21953       return Res;
21954     }
21955 
21956     // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
21957     if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
21958       assert(!IsSigned && "Expected unsigned conversion!");
21959       assert(Subtarget.useAVX512Regs() && "Requires avx512f");
21960       return Op;
21961     }
21962 
21963     // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
21964     if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
21965         (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32) &&
21966         Subtarget.useAVX512Regs()) {
21967       assert(!IsSigned && "Expected unsigned conversion!");
21968       assert(!Subtarget.hasVLX() && "Unexpected features!");
21969       MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
21970       MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
21971       // Need to concat with zero vector for strict fp to avoid spurious
21972       // exceptions.
21973       // TODO: Should we just do this for non-strict as well?
21974       SDValue Tmp =
21975           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
21976       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
21977                         DAG.getIntPtrConstant(0, dl));
21978 
21979       if (IsStrict) {
21980         Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
21981                           {Chain, Src});
21982         Chain = Res.getValue(1);
21983       } else {
21984         Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
21985       }
21986 
21987       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21988                         DAG.getIntPtrConstant(0, dl));
21989 
21990       if (IsStrict)
21991         return DAG.getMergeValues({Res, Chain}, dl);
21992       return Res;
21993     }
21994 
21995     // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
21996     if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
21997         (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32) &&
21998         Subtarget.useAVX512Regs() && Subtarget.hasDQI()) {
21999       assert(!Subtarget.hasVLX() && "Unexpected features!");
22000       MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
22001       // Need to concat with zero vector for strict fp to avoid spurious
22002       // exceptions.
22003       // TODO: Should we just do this for non-strict as well?
22004       SDValue Tmp =
22005           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
22006       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
22007                         DAG.getIntPtrConstant(0, dl));
22008 
22009       if (IsStrict) {
22010         Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
22011                           {Chain, Src});
22012         Chain = Res.getValue(1);
22013       } else {
22014         Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
22015       }
22016 
22017       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
22018                         DAG.getIntPtrConstant(0, dl));
22019 
22020       if (IsStrict)
22021         return DAG.getMergeValues({Res, Chain}, dl);
22022       return Res;
22023     }
22024 
22025     if (VT == MVT::v2i64 && SrcVT == MVT::v2f32) {
22026       if (!Subtarget.hasVLX()) {
22027         // Non-strict nodes without VLX can we widened to v4f32->v4i64 by type
22028         // legalizer and then widened again by vector op legalization.
22029         if (!IsStrict)
22030           return SDValue();
22031 
22032         SDValue Zero = DAG.getConstantFP(0.0, dl, MVT::v2f32);
22033         SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f32,
22034                                   {Src, Zero, Zero, Zero});
22035         Tmp = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
22036                           {Chain, Tmp});
22037         SDValue Chain = Tmp.getValue(1);
22038         Tmp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Tmp,
22039                           DAG.getIntPtrConstant(0, dl));
22040         return DAG.getMergeValues({Tmp, Chain}, dl);
22041       }
22042 
22043       assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL");
22044       SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
22045                                 DAG.getUNDEF(MVT::v2f32));
22046       if (IsStrict) {
22047         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
22048                                 : X86ISD::STRICT_CVTTP2UI;
22049         return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
22050       }
22051       unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
22052       return DAG.getNode(Opc, dl, VT, Tmp);
22053     }
22054 
22055     // Generate optimized instructions for pre AVX512 unsigned conversions from
22056     // vXf32 to vXi32.
22057     if ((VT == MVT::v4i32 && SrcVT == MVT::v4f32) ||
22058         (VT == MVT::v4i32 && SrcVT == MVT::v4f64) ||
22059         (VT == MVT::v8i32 && SrcVT == MVT::v8f32)) {
22060       assert(!IsSigned && "Expected unsigned conversion!");
22061       return expandFP_TO_UINT_SSE(VT, Src, dl, DAG, Subtarget);
22062     }
22063 
22064     return SDValue();
22065   }
22066 
22067   assert(!VT.isVector());
22068 
22069   bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
22070 
22071   if (!IsSigned && UseSSEReg) {
22072     // Conversions from f32/f64 with AVX512 should be legal.
22073     if (Subtarget.hasAVX512())
22074       return Op;
22075 
22076     // We can leverage the specific way the "cvttss2si/cvttsd2si" instruction
22077     // behaves on out of range inputs to generate optimized conversions.
22078     if (!IsStrict && ((VT == MVT::i32 && !Subtarget.is64Bit()) ||
22079                       (VT == MVT::i64 && Subtarget.is64Bit()))) {
22080       unsigned DstBits = VT.getScalarSizeInBits();
22081       APInt UIntLimit = APInt::getSignMask(DstBits);
22082       SDValue FloatOffset = DAG.getNode(ISD::UINT_TO_FP, dl, SrcVT,
22083                                         DAG.getConstant(UIntLimit, dl, VT));
22084       MVT SrcVecVT = MVT::getVectorVT(SrcVT, 128 / SrcVT.getScalarSizeInBits());
22085 
22086       // Calculate the converted result for values in the range:
22087       // (i32) 0 to 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
22088       // (i64) 0 to 2^63-1 ("Small") and from 2^63 to 2^64-1 ("Big").
22089       SDValue Small =
22090           DAG.getNode(X86ISD::CVTTS2SI, dl, VT,
22091                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT, Src));
22092       SDValue Big = DAG.getNode(
22093           X86ISD::CVTTS2SI, dl, VT,
22094           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT,
22095                       DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FloatOffset)));
22096 
22097       // The "CVTTS2SI" instruction conveniently sets the sign bit if
22098       // and only if the value was out of range. So we can use that
22099       // as our indicator that we rather use "Big" instead of "Small".
22100       //
22101       // Use "Small" if "IsOverflown" has all bits cleared
22102       // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
22103       SDValue IsOverflown = DAG.getNode(
22104           ISD::SRA, dl, VT, Small, DAG.getConstant(DstBits - 1, dl, MVT::i8));
22105       return DAG.getNode(ISD::OR, dl, VT, Small,
22106                          DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
22107     }
22108 
22109     // Use default expansion for i64.
22110     if (VT == MVT::i64)
22111       return SDValue();
22112 
22113     assert(VT == MVT::i32 && "Unexpected VT!");
22114 
22115     // Promote i32 to i64 and use a signed operation on 64-bit targets.
22116     // FIXME: This does not generate an invalid exception if the input does not
22117     // fit in i32. PR44019
22118     if (Subtarget.is64Bit()) {
22119       if (IsStrict) {
22120         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i64, MVT::Other},
22121                           {Chain, Src});
22122         Chain = Res.getValue(1);
22123       } else
22124         Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
22125 
22126       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
22127       if (IsStrict)
22128         return DAG.getMergeValues({Res, Chain}, dl);
22129       return Res;
22130     }
22131 
22132     // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
22133     // use fisttp which will be handled later.
22134     if (!Subtarget.hasSSE3())
22135       return SDValue();
22136   }
22137 
22138   // Promote i16 to i32 if we can use a SSE operation or the type is f128.
22139   // FIXME: This does not generate an invalid exception if the input does not
22140   // fit in i16. PR44019
22141   if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
22142     assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!");
22143     if (IsStrict) {
22144       Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i32, MVT::Other},
22145                         {Chain, Src});
22146       Chain = Res.getValue(1);
22147     } else
22148       Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
22149 
22150     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
22151     if (IsStrict)
22152       return DAG.getMergeValues({Res, Chain}, dl);
22153     return Res;
22154   }
22155 
22156   // If this is a FP_TO_SINT using SSEReg we're done.
22157   if (UseSSEReg && IsSigned)
22158     return Op;
22159 
22160   // fp128 needs to use a libcall.
22161   if (SrcVT == MVT::f128) {
22162     RTLIB::Libcall LC;
22163     if (IsSigned)
22164       LC = RTLIB::getFPTOSINT(SrcVT, VT);
22165     else
22166       LC = RTLIB::getFPTOUINT(SrcVT, VT);
22167 
22168     MakeLibCallOptions CallOptions;
22169     std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, Src, CallOptions,
22170                                                   SDLoc(Op), Chain);
22171 
22172     if (IsStrict)
22173       return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
22174 
22175     return Tmp.first;
22176   }
22177 
22178   // Fall back to X87.
22179   if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
22180     if (IsStrict)
22181       return DAG.getMergeValues({V, Chain}, dl);
22182     return V;
22183   }
22184 
22185   llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.");
22186 }
22187 
22188 SDValue X86TargetLowering::LowerLRINT_LLRINT(SDValue Op,
22189                                              SelectionDAG &DAG) const {
22190   SDValue Src = Op.getOperand(0);
22191   MVT SrcVT = Src.getSimpleValueType();
22192 
22193   // If the source is in an SSE register, the node is Legal.
22194   if (isScalarFPTypeInSSEReg(SrcVT))
22195     return Op;
22196 
22197   return LRINT_LLRINTHelper(Op.getNode(), DAG);
22198 }
22199 
22200 SDValue X86TargetLowering::LRINT_LLRINTHelper(SDNode *N,
22201                                               SelectionDAG &DAG) const {
22202   EVT DstVT = N->getValueType(0);
22203   SDValue Src = N->getOperand(0);
22204   EVT SrcVT = Src.getValueType();
22205 
22206   if (SrcVT != MVT::f32 && SrcVT != MVT::f64 && SrcVT != MVT::f80) {
22207     // f16 must be promoted before using the lowering in this routine.
22208     // fp128 does not use this lowering.
22209     return SDValue();
22210   }
22211 
22212   SDLoc DL(N);
22213   SDValue Chain = DAG.getEntryNode();
22214 
22215   bool UseSSE = isScalarFPTypeInSSEReg(SrcVT);
22216 
22217   // If we're converting from SSE, the stack slot needs to hold both types.
22218   // Otherwise it only needs to hold the DstVT.
22219   EVT OtherVT = UseSSE ? SrcVT : DstVT;
22220   SDValue StackPtr = DAG.CreateStackTemporary(DstVT, OtherVT);
22221   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
22222   MachinePointerInfo MPI =
22223       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
22224 
22225   if (UseSSE) {
22226     assert(DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!");
22227     Chain = DAG.getStore(Chain, DL, Src, StackPtr, MPI);
22228     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
22229     SDValue Ops[] = { Chain, StackPtr };
22230 
22231     Src = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, SrcVT, MPI,
22232                                   /*Align*/ None, MachineMemOperand::MOLoad);
22233     Chain = Src.getValue(1);
22234   }
22235 
22236   SDValue StoreOps[] = { Chain, Src, StackPtr };
22237   Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, DL, DAG.getVTList(MVT::Other),
22238                                   StoreOps, DstVT, MPI, /*Align*/ None,
22239                                   MachineMemOperand::MOStore);
22240 
22241   return DAG.getLoad(DstVT, DL, Chain, StackPtr, MPI);
22242 }
22243 
22244 SDValue
22245 X86TargetLowering::LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) const {
22246   // This is based on the TargetLowering::expandFP_TO_INT_SAT implementation,
22247   // but making use of X86 specifics to produce better instruction sequences.
22248   SDNode *Node = Op.getNode();
22249   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
22250   unsigned FpToIntOpcode = IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
22251   SDLoc dl(SDValue(Node, 0));
22252   SDValue Src = Node->getOperand(0);
22253 
22254   // There are three types involved here: SrcVT is the source floating point
22255   // type, DstVT is the type of the result, and TmpVT is the result of the
22256   // intermediate FP_TO_*INT operation we'll use (which may be a promotion of
22257   // DstVT).
22258   EVT SrcVT = Src.getValueType();
22259   EVT DstVT = Node->getValueType(0);
22260   EVT TmpVT = DstVT;
22261 
22262   // This code is only for floats and doubles. Fall back to generic code for
22263   // anything else.
22264   if (!isScalarFPTypeInSSEReg(SrcVT))
22265     return SDValue();
22266 
22267   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
22268   unsigned SatWidth = SatVT.getScalarSizeInBits();
22269   unsigned DstWidth = DstVT.getScalarSizeInBits();
22270   unsigned TmpWidth = TmpVT.getScalarSizeInBits();
22271   assert(SatWidth <= DstWidth && SatWidth <= TmpWidth &&
22272          "Expected saturation width smaller than result width");
22273 
22274   // Promote result of FP_TO_*INT to at least 32 bits.
22275   if (TmpWidth < 32) {
22276     TmpVT = MVT::i32;
22277     TmpWidth = 32;
22278   }
22279 
22280   // Promote conversions to unsigned 32-bit to 64-bit, because it will allow
22281   // us to use a native signed conversion instead.
22282   if (SatWidth == 32 && !IsSigned && Subtarget.is64Bit()) {
22283     TmpVT = MVT::i64;
22284     TmpWidth = 64;
22285   }
22286 
22287   // If the saturation width is smaller than the size of the temporary result,
22288   // we can always use signed conversion, which is native.
22289   if (SatWidth < TmpWidth)
22290     FpToIntOpcode = ISD::FP_TO_SINT;
22291 
22292   // Determine minimum and maximum integer values and their corresponding
22293   // floating-point values.
22294   APInt MinInt, MaxInt;
22295   if (IsSigned) {
22296     MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth);
22297     MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth);
22298   } else {
22299     MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth);
22300     MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth);
22301   }
22302 
22303   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
22304   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
22305 
22306   APFloat::opStatus MinStatus = MinFloat.convertFromAPInt(
22307     MinInt, IsSigned, APFloat::rmTowardZero);
22308   APFloat::opStatus MaxStatus = MaxFloat.convertFromAPInt(
22309     MaxInt, IsSigned, APFloat::rmTowardZero);
22310   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact)
22311                           && !(MaxStatus & APFloat::opStatus::opInexact);
22312 
22313   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
22314   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
22315 
22316   // If the integer bounds are exactly representable as floats, emit a
22317   // min+max+fptoi sequence. Otherwise use comparisons and selects.
22318   if (AreExactFloatBounds) {
22319     if (DstVT != TmpVT) {
22320       // Clamp by MinFloat from below. If Src is NaN, propagate NaN.
22321       SDValue MinClamped = DAG.getNode(
22322         X86ISD::FMAX, dl, SrcVT, MinFloatNode, Src);
22323       // Clamp by MaxFloat from above. If Src is NaN, propagate NaN.
22324       SDValue BothClamped = DAG.getNode(
22325         X86ISD::FMIN, dl, SrcVT, MaxFloatNode, MinClamped);
22326       // Convert clamped value to integer.
22327       SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, BothClamped);
22328 
22329       // NaN will become INDVAL, with the top bit set and the rest zero.
22330       // Truncation will discard the top bit, resulting in zero.
22331       return DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
22332     }
22333 
22334     // Clamp by MinFloat from below. If Src is NaN, the result is MinFloat.
22335     SDValue MinClamped = DAG.getNode(
22336       X86ISD::FMAX, dl, SrcVT, Src, MinFloatNode);
22337     // Clamp by MaxFloat from above. NaN cannot occur.
22338     SDValue BothClamped = DAG.getNode(
22339       X86ISD::FMINC, dl, SrcVT, MinClamped, MaxFloatNode);
22340     // Convert clamped value to integer.
22341     SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, DstVT, BothClamped);
22342 
22343     if (!IsSigned) {
22344       // In the unsigned case we're done, because we mapped NaN to MinFloat,
22345       // which is zero.
22346       return FpToInt;
22347     }
22348 
22349     // Otherwise, select zero if Src is NaN.
22350     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
22351     return DAG.getSelectCC(
22352       dl, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
22353   }
22354 
22355   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
22356   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
22357 
22358   // Result of direct conversion, which may be selected away.
22359   SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, Src);
22360 
22361   if (DstVT != TmpVT) {
22362     // NaN will become INDVAL, with the top bit set and the rest zero.
22363     // Truncation will discard the top bit, resulting in zero.
22364     FpToInt = DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
22365   }
22366 
22367   SDValue Select = FpToInt;
22368   // For signed conversions where we saturate to the same size as the
22369   // result type of the fptoi instructions, INDVAL coincides with integer
22370   // minimum, so we don't need to explicitly check it.
22371   if (!IsSigned || SatWidth != TmpVT.getScalarSizeInBits()) {
22372     // If Src ULT MinFloat, select MinInt. In particular, this also selects
22373     // MinInt if Src is NaN.
22374     Select = DAG.getSelectCC(
22375       dl, Src, MinFloatNode, MinIntNode, Select, ISD::CondCode::SETULT);
22376   }
22377 
22378   // If Src OGT MaxFloat, select MaxInt.
22379   Select = DAG.getSelectCC(
22380     dl, Src, MaxFloatNode, MaxIntNode, Select, ISD::CondCode::SETOGT);
22381 
22382   // In the unsigned case we are done, because we mapped NaN to MinInt, which
22383   // is already zero. The promoted case was already handled above.
22384   if (!IsSigned || DstVT != TmpVT) {
22385     return Select;
22386   }
22387 
22388   // Otherwise, select 0 if Src is NaN.
22389   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
22390   return DAG.getSelectCC(
22391     dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
22392 }
22393 
22394 SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
22395   bool IsStrict = Op->isStrictFPOpcode();
22396 
22397   SDLoc DL(Op);
22398   MVT VT = Op.getSimpleValueType();
22399   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
22400   MVT SVT = In.getSimpleValueType();
22401 
22402   if (VT == MVT::f128)
22403     return SDValue();
22404 
22405   if (VT == MVT::f80) {
22406     if (SVT == MVT::f16) {
22407       assert(Subtarget.hasFP16() && "Unexpected features!");
22408       RTLIB::Libcall LC = RTLIB::getFPEXT(SVT, VT);
22409       MakeLibCallOptions CallOptions;
22410       std::pair<SDValue, SDValue> Tmp =
22411           makeLibCall(DAG, LC, VT, In, CallOptions, DL,
22412                       IsStrict ? Op.getOperand(0) : SDValue());
22413       if (IsStrict)
22414         return DAG.getMergeValues({Tmp.first, Tmp.second}, DL);
22415       else
22416         return Tmp.first;
22417     }
22418     return Op;
22419   }
22420 
22421   if (SVT.getVectorElementType() == MVT::f16) {
22422     assert(Subtarget.hasFP16() && Subtarget.hasVLX() && "Unexpected features!");
22423     if (SVT == MVT::v2f16)
22424       In = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f16, In,
22425                        DAG.getUNDEF(MVT::v2f16));
22426     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8f16, In,
22427                               DAG.getUNDEF(MVT::v4f16));
22428     if (IsStrict)
22429       return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
22430                          {Op->getOperand(0), Res});
22431     return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
22432   }
22433 
22434   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
22435 
22436   SDValue Res =
22437       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
22438   if (IsStrict)
22439     return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
22440                        {Op->getOperand(0), Res});
22441   return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
22442 }
22443 
22444 SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
22445   bool IsStrict = Op->isStrictFPOpcode();
22446   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
22447   MVT VT = Op.getSimpleValueType();
22448   MVT SVT = In.getSimpleValueType();
22449 
22450   // It's legal except when f128 is involved or we're converting f80->f16.
22451   if (SVT != MVT::f128 && !(VT == MVT::f16 && SVT == MVT::f80))
22452     return Op;
22453 
22454   return SDValue();
22455 }
22456 
22457 static SDValue LowerFP16_TO_FP(SDValue Op, SelectionDAG &DAG) {
22458   bool IsStrict = Op->isStrictFPOpcode();
22459   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
22460   assert(Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 &&
22461          "Unexpected VT!");
22462 
22463   SDLoc dl(Op);
22464   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16,
22465                             DAG.getConstant(0, dl, MVT::v8i16), Src,
22466                             DAG.getIntPtrConstant(0, dl));
22467 
22468   SDValue Chain;
22469   if (IsStrict) {
22470     Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {MVT::v4f32, MVT::Other},
22471                       {Op.getOperand(0), Res});
22472     Chain = Res.getValue(1);
22473   } else {
22474     Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
22475   }
22476 
22477   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
22478                     DAG.getIntPtrConstant(0, dl));
22479 
22480   if (IsStrict)
22481     return DAG.getMergeValues({Res, Chain}, dl);
22482 
22483   return Res;
22484 }
22485 
22486 static SDValue LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) {
22487   bool IsStrict = Op->isStrictFPOpcode();
22488   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
22489   assert(Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 &&
22490          "Unexpected VT!");
22491 
22492   SDLoc dl(Op);
22493   SDValue Res, Chain;
22494   if (IsStrict) {
22495     Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4f32,
22496                       DAG.getConstantFP(0, dl, MVT::v4f32), Src,
22497                       DAG.getIntPtrConstant(0, dl));
22498     Res = DAG.getNode(
22499         X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
22500         {Op.getOperand(0), Res, DAG.getTargetConstant(4, dl, MVT::i32)});
22501     Chain = Res.getValue(1);
22502   } else {
22503     // FIXME: Should we use zeros for upper elements for non-strict?
22504     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, Src);
22505     Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
22506                       DAG.getTargetConstant(4, dl, MVT::i32));
22507   }
22508 
22509   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Res,
22510                     DAG.getIntPtrConstant(0, dl));
22511 
22512   if (IsStrict)
22513     return DAG.getMergeValues({Res, Chain}, dl);
22514 
22515   return Res;
22516 }
22517 
22518 /// Depending on uarch and/or optimizing for size, we might prefer to use a
22519 /// vector operation in place of the typical scalar operation.
22520 static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
22521                                          const X86Subtarget &Subtarget) {
22522   // If both operands have other uses, this is probably not profitable.
22523   SDValue LHS = Op.getOperand(0);
22524   SDValue RHS = Op.getOperand(1);
22525   if (!LHS.hasOneUse() && !RHS.hasOneUse())
22526     return Op;
22527 
22528   // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
22529   bool IsFP = Op.getSimpleValueType().isFloatingPoint();
22530   if (IsFP && !Subtarget.hasSSE3())
22531     return Op;
22532   if (!IsFP && !Subtarget.hasSSSE3())
22533     return Op;
22534 
22535   // Extract from a common vector.
22536   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
22537       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
22538       LHS.getOperand(0) != RHS.getOperand(0) ||
22539       !isa<ConstantSDNode>(LHS.getOperand(1)) ||
22540       !isa<ConstantSDNode>(RHS.getOperand(1)) ||
22541       !shouldUseHorizontalOp(true, DAG, Subtarget))
22542     return Op;
22543 
22544   // Allow commuted 'hadd' ops.
22545   // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
22546   unsigned HOpcode;
22547   switch (Op.getOpcode()) {
22548     case ISD::ADD: HOpcode = X86ISD::HADD; break;
22549     case ISD::SUB: HOpcode = X86ISD::HSUB; break;
22550     case ISD::FADD: HOpcode = X86ISD::FHADD; break;
22551     case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
22552     default:
22553       llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
22554   }
22555   unsigned LExtIndex = LHS.getConstantOperandVal(1);
22556   unsigned RExtIndex = RHS.getConstantOperandVal(1);
22557   if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
22558       (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
22559     std::swap(LExtIndex, RExtIndex);
22560 
22561   if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
22562     return Op;
22563 
22564   SDValue X = LHS.getOperand(0);
22565   EVT VecVT = X.getValueType();
22566   unsigned BitWidth = VecVT.getSizeInBits();
22567   unsigned NumLanes = BitWidth / 128;
22568   unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
22569   assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
22570          "Not expecting illegal vector widths here");
22571 
22572   // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
22573   // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
22574   SDLoc DL(Op);
22575   if (BitWidth == 256 || BitWidth == 512) {
22576     unsigned LaneIdx = LExtIndex / NumEltsPerLane;
22577     X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
22578     LExtIndex %= NumEltsPerLane;
22579   }
22580 
22581   // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
22582   // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
22583   // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
22584   // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
22585   SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
22586   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
22587                      DAG.getIntPtrConstant(LExtIndex / 2, DL));
22588 }
22589 
22590 /// Depending on uarch and/or optimizing for size, we might prefer to use a
22591 /// vector operation in place of the typical scalar operation.
22592 SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
22593   assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
22594          "Only expecting float/double");
22595   return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
22596 }
22597 
22598 /// ISD::FROUND is defined to round to nearest with ties rounding away from 0.
22599 /// This mode isn't supported in hardware on X86. But as long as we aren't
22600 /// compiling with trapping math, we can emulate this with
22601 /// floor(X + copysign(nextafter(0.5, 0.0), X)).
22602 static SDValue LowerFROUND(SDValue Op, SelectionDAG &DAG) {
22603   SDValue N0 = Op.getOperand(0);
22604   SDLoc dl(Op);
22605   MVT VT = Op.getSimpleValueType();
22606 
22607   // N0 += copysign(nextafter(0.5, 0.0), N0)
22608   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
22609   bool Ignored;
22610   APFloat Point5Pred = APFloat(0.5f);
22611   Point5Pred.convert(Sem, APFloat::rmNearestTiesToEven, &Ignored);
22612   Point5Pred.next(/*nextDown*/true);
22613 
22614   SDValue Adder = DAG.getNode(ISD::FCOPYSIGN, dl, VT,
22615                               DAG.getConstantFP(Point5Pred, dl, VT), N0);
22616   N0 = DAG.getNode(ISD::FADD, dl, VT, N0, Adder);
22617 
22618   // Truncate the result to remove fraction.
22619   return DAG.getNode(ISD::FTRUNC, dl, VT, N0);
22620 }
22621 
22622 /// The only differences between FABS and FNEG are the mask and the logic op.
22623 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
22624 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
22625   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
22626          "Wrong opcode for lowering FABS or FNEG.");
22627 
22628   bool IsFABS = (Op.getOpcode() == ISD::FABS);
22629 
22630   // If this is a FABS and it has an FNEG user, bail out to fold the combination
22631   // into an FNABS. We'll lower the FABS after that if it is still in use.
22632   if (IsFABS)
22633     for (SDNode *User : Op->uses())
22634       if (User->getOpcode() == ISD::FNEG)
22635         return Op;
22636 
22637   SDLoc dl(Op);
22638   MVT VT = Op.getSimpleValueType();
22639 
22640   bool IsF128 = (VT == MVT::f128);
22641   assert(VT.isFloatingPoint() && VT != MVT::f80 &&
22642          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
22643          "Unexpected type in LowerFABSorFNEG");
22644 
22645   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
22646   // decide if we should generate a 16-byte constant mask when we only need 4 or
22647   // 8 bytes for the scalar case.
22648 
22649   // There are no scalar bitwise logical SSE/AVX instructions, so we
22650   // generate a 16-byte vector constant and logic op even for the scalar case.
22651   // Using a 16-byte mask allows folding the load of the mask with
22652   // the logic op, so it can save (~4 bytes) on code size.
22653   bool IsFakeVector = !VT.isVector() && !IsF128;
22654   MVT LogicVT = VT;
22655   if (IsFakeVector)
22656     LogicVT = (VT == MVT::f64)   ? MVT::v2f64
22657               : (VT == MVT::f32) ? MVT::v4f32
22658                                  : MVT::v8f16;
22659 
22660   unsigned EltBits = VT.getScalarSizeInBits();
22661   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
22662   APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
22663                            APInt::getSignMask(EltBits);
22664   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
22665   SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
22666 
22667   SDValue Op0 = Op.getOperand(0);
22668   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
22669   unsigned LogicOp = IsFABS  ? X86ISD::FAND :
22670                      IsFNABS ? X86ISD::FOR  :
22671                                X86ISD::FXOR;
22672   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
22673 
22674   if (VT.isVector() || IsF128)
22675     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
22676 
22677   // For the scalar case extend to a 128-bit vector, perform the logic op,
22678   // and extract the scalar result back out.
22679   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
22680   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
22681   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
22682                      DAG.getIntPtrConstant(0, dl));
22683 }
22684 
22685 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
22686   SDValue Mag = Op.getOperand(0);
22687   SDValue Sign = Op.getOperand(1);
22688   SDLoc dl(Op);
22689 
22690   // If the sign operand is smaller, extend it first.
22691   MVT VT = Op.getSimpleValueType();
22692   if (Sign.getSimpleValueType().bitsLT(VT))
22693     Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
22694 
22695   // And if it is bigger, shrink it first.
22696   if (Sign.getSimpleValueType().bitsGT(VT))
22697     Sign =
22698         DAG.getNode(ISD::FP_ROUND, dl, VT, Sign, DAG.getIntPtrConstant(0, dl));
22699 
22700   // At this point the operands and the result should have the same
22701   // type, and that won't be f80 since that is not custom lowered.
22702   bool IsF128 = (VT == MVT::f128);
22703   assert(VT.isFloatingPoint() && VT != MVT::f80 &&
22704          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
22705          "Unexpected type in LowerFCOPYSIGN");
22706 
22707   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
22708 
22709   // Perform all scalar logic operations as 16-byte vectors because there are no
22710   // scalar FP logic instructions in SSE.
22711   // TODO: This isn't necessary. If we used scalar types, we might avoid some
22712   // unnecessary splats, but we might miss load folding opportunities. Should
22713   // this decision be based on OptimizeForSize?
22714   bool IsFakeVector = !VT.isVector() && !IsF128;
22715   MVT LogicVT = VT;
22716   if (IsFakeVector)
22717     LogicVT = (VT == MVT::f64)   ? MVT::v2f64
22718               : (VT == MVT::f32) ? MVT::v4f32
22719                                  : MVT::v8f16;
22720 
22721   // The mask constants are automatically splatted for vector types.
22722   unsigned EltSizeInBits = VT.getScalarSizeInBits();
22723   SDValue SignMask = DAG.getConstantFP(
22724       APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
22725   SDValue MagMask = DAG.getConstantFP(
22726       APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
22727 
22728   // First, clear all bits but the sign bit from the second operand (sign).
22729   if (IsFakeVector)
22730     Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
22731   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
22732 
22733   // Next, clear the sign bit from the first operand (magnitude).
22734   // TODO: If we had general constant folding for FP logic ops, this check
22735   // wouldn't be necessary.
22736   SDValue MagBits;
22737   if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
22738     APFloat APF = Op0CN->getValueAPF();
22739     APF.clearSign();
22740     MagBits = DAG.getConstantFP(APF, dl, LogicVT);
22741   } else {
22742     // If the magnitude operand wasn't a constant, we need to AND out the sign.
22743     if (IsFakeVector)
22744       Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
22745     MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
22746   }
22747 
22748   // OR the magnitude value with the sign bit.
22749   SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
22750   return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
22751                                           DAG.getIntPtrConstant(0, dl));
22752 }
22753 
22754 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
22755   SDValue N0 = Op.getOperand(0);
22756   SDLoc dl(Op);
22757   MVT VT = Op.getSimpleValueType();
22758 
22759   MVT OpVT = N0.getSimpleValueType();
22760   assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
22761          "Unexpected type for FGETSIGN");
22762 
22763   // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
22764   MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
22765   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
22766   Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
22767   Res = DAG.getZExtOrTrunc(Res, dl, VT);
22768   Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
22769   return Res;
22770 }
22771 
22772 /// Helper for creating a X86ISD::SETCC node.
22773 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
22774                         SelectionDAG &DAG) {
22775   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
22776                      DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
22777 }
22778 
22779 /// Helper for matching OR(EXTRACTELT(X,0),OR(EXTRACTELT(X,1),...))
22780 /// style scalarized (associative) reduction patterns. Partial reductions
22781 /// are supported when the pointer SrcMask is non-null.
22782 /// TODO - move this to SelectionDAG?
22783 static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
22784                                  SmallVectorImpl<SDValue> &SrcOps,
22785                                  SmallVectorImpl<APInt> *SrcMask = nullptr) {
22786   SmallVector<SDValue, 8> Opnds;
22787   DenseMap<SDValue, APInt> SrcOpMap;
22788   EVT VT = MVT::Other;
22789 
22790   // Recognize a special case where a vector is casted into wide integer to
22791   // test all 0s.
22792   assert(Op.getOpcode() == unsigned(BinOp) &&
22793          "Unexpected bit reduction opcode");
22794   Opnds.push_back(Op.getOperand(0));
22795   Opnds.push_back(Op.getOperand(1));
22796 
22797   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
22798     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
22799     // BFS traverse all BinOp operands.
22800     if (I->getOpcode() == unsigned(BinOp)) {
22801       Opnds.push_back(I->getOperand(0));
22802       Opnds.push_back(I->getOperand(1));
22803       // Re-evaluate the number of nodes to be traversed.
22804       e += 2; // 2 more nodes (LHS and RHS) are pushed.
22805       continue;
22806     }
22807 
22808     // Quit if a non-EXTRACT_VECTOR_ELT
22809     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22810       return false;
22811 
22812     // Quit if without a constant index.
22813     auto *Idx = dyn_cast<ConstantSDNode>(I->getOperand(1));
22814     if (!Idx)
22815       return false;
22816 
22817     SDValue Src = I->getOperand(0);
22818     DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
22819     if (M == SrcOpMap.end()) {
22820       VT = Src.getValueType();
22821       // Quit if not the same type.
22822       if (!SrcOpMap.empty() && VT != SrcOpMap.begin()->first.getValueType())
22823         return false;
22824       unsigned NumElts = VT.getVectorNumElements();
22825       APInt EltCount = APInt::getZero(NumElts);
22826       M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
22827       SrcOps.push_back(Src);
22828     }
22829 
22830     // Quit if element already used.
22831     unsigned CIdx = Idx->getZExtValue();
22832     if (M->second[CIdx])
22833       return false;
22834     M->second.setBit(CIdx);
22835   }
22836 
22837   if (SrcMask) {
22838     // Collect the source partial masks.
22839     for (SDValue &SrcOp : SrcOps)
22840       SrcMask->push_back(SrcOpMap[SrcOp]);
22841   } else {
22842     // Quit if not all elements are used.
22843     for (const auto &I : SrcOpMap)
22844       if (!I.second.isAllOnes())
22845         return false;
22846   }
22847 
22848   return true;
22849 }
22850 
22851 // Helper function for comparing all bits of a vector against zero.
22852 static SDValue LowerVectorAllZero(const SDLoc &DL, SDValue V, ISD::CondCode CC,
22853                                   const APInt &Mask,
22854                                   const X86Subtarget &Subtarget,
22855                                   SelectionDAG &DAG, X86::CondCode &X86CC) {
22856   EVT VT = V.getValueType();
22857   unsigned ScalarSize = VT.getScalarSizeInBits();
22858   if (Mask.getBitWidth() != ScalarSize) {
22859     assert(ScalarSize == 1 && "Element Mask vs Vector bitwidth mismatch");
22860     return SDValue();
22861   }
22862 
22863   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
22864   X86CC = (CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE);
22865 
22866   auto MaskBits = [&](SDValue Src) {
22867     if (Mask.isAllOnes())
22868       return Src;
22869     EVT SrcVT = Src.getValueType();
22870     SDValue MaskValue = DAG.getConstant(Mask, DL, SrcVT);
22871     return DAG.getNode(ISD::AND, DL, SrcVT, Src, MaskValue);
22872   };
22873 
22874   // For sub-128-bit vector, cast to (legal) integer and compare with zero.
22875   if (VT.getSizeInBits() < 128) {
22876     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
22877     if (!DAG.getTargetLoweringInfo().isTypeLegal(IntVT))
22878       return SDValue();
22879     return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
22880                        DAG.getBitcast(IntVT, MaskBits(V)),
22881                        DAG.getConstant(0, DL, IntVT));
22882   }
22883 
22884   // Quit if not splittable to 128/256-bit vector.
22885   if (!isPowerOf2_32(VT.getSizeInBits()))
22886     return SDValue();
22887 
22888   // Split down to 128/256-bit vector.
22889   unsigned TestSize = Subtarget.hasAVX() ? 256 : 128;
22890   while (VT.getSizeInBits() > TestSize) {
22891     auto Split = DAG.SplitVector(V, DL);
22892     VT = Split.first.getValueType();
22893     V = DAG.getNode(ISD::OR, DL, VT, Split.first, Split.second);
22894   }
22895 
22896   bool UsePTEST = Subtarget.hasSSE41();
22897   if (UsePTEST) {
22898     MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
22899     V = DAG.getBitcast(TestVT, MaskBits(V));
22900     return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, V, V);
22901   }
22902 
22903   // Without PTEST, a masked v2i64 or-reduction is not faster than
22904   // scalarization.
22905   if (!Mask.isAllOnes() && VT.getScalarSizeInBits() > 32)
22906     return SDValue();
22907 
22908   V = DAG.getBitcast(MVT::v16i8, MaskBits(V));
22909   V = DAG.getNode(X86ISD::PCMPEQ, DL, MVT::v16i8, V,
22910                   getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
22911   V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
22912   return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
22913                      DAG.getConstant(0xFFFF, DL, MVT::i32));
22914 }
22915 
22916 // Check whether an OR'd reduction tree is PTEST-able, or if we can fallback to
22917 // CMP(MOVMSK(PCMPEQB(X,0))).
22918 static SDValue MatchVectorAllZeroTest(SDValue Op, ISD::CondCode CC,
22919                                       const SDLoc &DL,
22920                                       const X86Subtarget &Subtarget,
22921                                       SelectionDAG &DAG, SDValue &X86CC) {
22922   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
22923 
22924   if (!Subtarget.hasSSE2() || !Op->hasOneUse())
22925     return SDValue();
22926 
22927   // Check whether we're masking/truncating an OR-reduction result, in which
22928   // case track the masked bits.
22929   APInt Mask = APInt::getAllOnes(Op.getScalarValueSizeInBits());
22930   switch (Op.getOpcode()) {
22931   case ISD::TRUNCATE: {
22932     SDValue Src = Op.getOperand(0);
22933     Mask = APInt::getLowBitsSet(Src.getScalarValueSizeInBits(),
22934                                 Op.getScalarValueSizeInBits());
22935     Op = Src;
22936     break;
22937   }
22938   case ISD::AND: {
22939     if (auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22940       Mask = Cst->getAPIntValue();
22941       Op = Op.getOperand(0);
22942     }
22943     break;
22944   }
22945   }
22946 
22947   SmallVector<SDValue, 8> VecIns;
22948   if (Op.getOpcode() == ISD::OR && matchScalarReduction(Op, ISD::OR, VecIns)) {
22949     EVT VT = VecIns[0].getValueType();
22950     assert(llvm::all_of(VecIns,
22951                         [VT](SDValue V) { return VT == V.getValueType(); }) &&
22952            "Reduction source vector mismatch");
22953 
22954     // Quit if less than 128-bits or not splittable to 128/256-bit vector.
22955     if (VT.getSizeInBits() < 128 || !isPowerOf2_32(VT.getSizeInBits()))
22956       return SDValue();
22957 
22958     // If more than one full vector is evaluated, OR them first before PTEST.
22959     for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1;
22960          Slot += 2, e += 1) {
22961       // Each iteration will OR 2 nodes and append the result until there is
22962       // only 1 node left, i.e. the final OR'd value of all vectors.
22963       SDValue LHS = VecIns[Slot];
22964       SDValue RHS = VecIns[Slot + 1];
22965       VecIns.push_back(DAG.getNode(ISD::OR, DL, VT, LHS, RHS));
22966     }
22967 
22968     X86::CondCode CCode;
22969     if (SDValue V = LowerVectorAllZero(DL, VecIns.back(), CC, Mask, Subtarget,
22970                                        DAG, CCode)) {
22971       X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
22972       return V;
22973     }
22974   }
22975 
22976   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
22977     ISD::NodeType BinOp;
22978     if (SDValue Match =
22979             DAG.matchBinOpReduction(Op.getNode(), BinOp, {ISD::OR})) {
22980       X86::CondCode CCode;
22981       if (SDValue V =
22982               LowerVectorAllZero(DL, Match, CC, Mask, Subtarget, DAG, CCode)) {
22983         X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
22984         return V;
22985       }
22986     }
22987   }
22988 
22989   return SDValue();
22990 }
22991 
22992 /// return true if \c Op has a use that doesn't just read flags.
22993 static bool hasNonFlagsUse(SDValue Op) {
22994   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
22995        ++UI) {
22996     SDNode *User = *UI;
22997     unsigned UOpNo = UI.getOperandNo();
22998     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
22999       // Look pass truncate.
23000       UOpNo = User->use_begin().getOperandNo();
23001       User = *User->use_begin();
23002     }
23003 
23004     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
23005         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
23006       return true;
23007   }
23008   return false;
23009 }
23010 
23011 // Transform to an x86-specific ALU node with flags if there is a chance of
23012 // using an RMW op or only the flags are used. Otherwise, leave
23013 // the node alone and emit a 'cmp' or 'test' instruction.
23014 static bool isProfitableToUseFlagOp(SDValue Op) {
23015   for (SDNode *U : Op->uses())
23016     if (U->getOpcode() != ISD::CopyToReg &&
23017         U->getOpcode() != ISD::SETCC &&
23018         U->getOpcode() != ISD::STORE)
23019       return false;
23020 
23021   return true;
23022 }
23023 
23024 /// Emit nodes that will be selected as "test Op0,Op0", or something
23025 /// equivalent.
23026 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
23027                         SelectionDAG &DAG, const X86Subtarget &Subtarget) {
23028   // CF and OF aren't always set the way we want. Determine which
23029   // of these we need.
23030   bool NeedCF = false;
23031   bool NeedOF = false;
23032   switch (X86CC) {
23033   default: break;
23034   case X86::COND_A: case X86::COND_AE:
23035   case X86::COND_B: case X86::COND_BE:
23036     NeedCF = true;
23037     break;
23038   case X86::COND_G: case X86::COND_GE:
23039   case X86::COND_L: case X86::COND_LE:
23040   case X86::COND_O: case X86::COND_NO: {
23041     // Check if we really need to set the
23042     // Overflow flag. If NoSignedWrap is present
23043     // that is not actually needed.
23044     switch (Op->getOpcode()) {
23045     case ISD::ADD:
23046     case ISD::SUB:
23047     case ISD::MUL:
23048     case ISD::SHL:
23049       if (Op.getNode()->getFlags().hasNoSignedWrap())
23050         break;
23051       LLVM_FALLTHROUGH;
23052     default:
23053       NeedOF = true;
23054       break;
23055     }
23056     break;
23057   }
23058   }
23059   // See if we can use the EFLAGS value from the operand instead of
23060   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
23061   // we prove that the arithmetic won't overflow, we can't use OF or CF.
23062   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
23063     // Emit a CMP with 0, which is the TEST pattern.
23064     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
23065                        DAG.getConstant(0, dl, Op.getValueType()));
23066   }
23067   unsigned Opcode = 0;
23068   unsigned NumOperands = 0;
23069 
23070   SDValue ArithOp = Op;
23071 
23072   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
23073   // which may be the result of a CAST.  We use the variable 'Op', which is the
23074   // non-casted variable when we check for possible users.
23075   switch (ArithOp.getOpcode()) {
23076   case ISD::AND:
23077     // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
23078     // because a TEST instruction will be better.
23079     if (!hasNonFlagsUse(Op))
23080       break;
23081 
23082     LLVM_FALLTHROUGH;
23083   case ISD::ADD:
23084   case ISD::SUB:
23085   case ISD::OR:
23086   case ISD::XOR:
23087     if (!isProfitableToUseFlagOp(Op))
23088       break;
23089 
23090     // Otherwise use a regular EFLAGS-setting instruction.
23091     switch (ArithOp.getOpcode()) {
23092     default: llvm_unreachable("unexpected operator!");
23093     case ISD::ADD: Opcode = X86ISD::ADD; break;
23094     case ISD::SUB: Opcode = X86ISD::SUB; break;
23095     case ISD::XOR: Opcode = X86ISD::XOR; break;
23096     case ISD::AND: Opcode = X86ISD::AND; break;
23097     case ISD::OR:  Opcode = X86ISD::OR;  break;
23098     }
23099 
23100     NumOperands = 2;
23101     break;
23102   case X86ISD::ADD:
23103   case X86ISD::SUB:
23104   case X86ISD::OR:
23105   case X86ISD::XOR:
23106   case X86ISD::AND:
23107     return SDValue(Op.getNode(), 1);
23108   case ISD::SSUBO:
23109   case ISD::USUBO: {
23110     // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
23111     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23112     return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
23113                        Op->getOperand(1)).getValue(1);
23114   }
23115   default:
23116     break;
23117   }
23118 
23119   if (Opcode == 0) {
23120     // Emit a CMP with 0, which is the TEST pattern.
23121     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
23122                        DAG.getConstant(0, dl, Op.getValueType()));
23123   }
23124   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23125   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
23126 
23127   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
23128   DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
23129   return SDValue(New.getNode(), 1);
23130 }
23131 
23132 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
23133 /// equivalent.
23134 static SDValue EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
23135                        const SDLoc &dl, SelectionDAG &DAG,
23136                        const X86Subtarget &Subtarget) {
23137   if (isNullConstant(Op1))
23138     return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
23139 
23140   EVT CmpVT = Op0.getValueType();
23141 
23142   assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||
23143           CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!");
23144 
23145   // Only promote the compare up to I32 if it is a 16 bit operation
23146   // with an immediate.  16 bit immediates are to be avoided.
23147   if (CmpVT == MVT::i16 && !Subtarget.isAtom() &&
23148       !DAG.getMachineFunction().getFunction().hasMinSize()) {
23149     ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
23150     ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
23151     // Don't do this if the immediate can fit in 8-bits.
23152     if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
23153         (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
23154       unsigned ExtendOp =
23155           isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
23156       if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
23157         // For equality comparisons try to use SIGN_EXTEND if the input was
23158         // truncate from something with enough sign bits.
23159         if (Op0.getOpcode() == ISD::TRUNCATE) {
23160           if (DAG.ComputeMinSignedBits(Op0.getOperand(0)) <= 16)
23161             ExtendOp = ISD::SIGN_EXTEND;
23162         } else if (Op1.getOpcode() == ISD::TRUNCATE) {
23163           if (DAG.ComputeMinSignedBits(Op1.getOperand(0)) <= 16)
23164             ExtendOp = ISD::SIGN_EXTEND;
23165         }
23166       }
23167 
23168       CmpVT = MVT::i32;
23169       Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
23170       Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
23171     }
23172   }
23173 
23174   // Try to shrink i64 compares if the input has enough zero bits.
23175   // FIXME: Do this for non-constant compares for constant on LHS?
23176   if (CmpVT == MVT::i64 && isa<ConstantSDNode>(Op1) && !isX86CCSigned(X86CC) &&
23177       Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
23178       cast<ConstantSDNode>(Op1)->getAPIntValue().getActiveBits() <= 32 &&
23179       DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
23180     CmpVT = MVT::i32;
23181     Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
23182     Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
23183   }
23184 
23185   // 0-x == y --> x+y == 0
23186   // 0-x != y --> x+y != 0
23187   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op0.getOperand(0)) &&
23188       Op0.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
23189     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23190     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(1), Op1);
23191     return Add.getValue(1);
23192   }
23193 
23194   // x == 0-y --> x+y == 0
23195   // x != 0-y --> x+y != 0
23196   if (Op1.getOpcode() == ISD::SUB && isNullConstant(Op1.getOperand(0)) &&
23197       Op1.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
23198     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23199     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0, Op1.getOperand(1));
23200     return Add.getValue(1);
23201   }
23202 
23203   // Use SUB instead of CMP to enable CSE between SUB and CMP.
23204   SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23205   SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
23206   return Sub.getValue(1);
23207 }
23208 
23209 /// Check if replacement of SQRT with RSQRT should be disabled.
23210 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
23211   EVT VT = Op.getValueType();
23212 
23213   // We don't need to replace SQRT with RSQRT for half type.
23214   if (VT.getScalarType() == MVT::f16)
23215     return true;
23216 
23217   // We never want to use both SQRT and RSQRT instructions for the same input.
23218   if (DAG.getNodeIfExists(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
23219     return false;
23220 
23221   if (VT.isVector())
23222     return Subtarget.hasFastVectorFSQRT();
23223   return Subtarget.hasFastScalarFSQRT();
23224 }
23225 
23226 /// The minimum architected relative accuracy is 2^-12. We need one
23227 /// Newton-Raphson step to have a good float result (24 bits of precision).
23228 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
23229                                            SelectionDAG &DAG, int Enabled,
23230                                            int &RefinementSteps,
23231                                            bool &UseOneConstNR,
23232                                            bool Reciprocal) const {
23233   SDLoc DL(Op);
23234   EVT VT = Op.getValueType();
23235 
23236   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
23237   // It is likely not profitable to do this for f64 because a double-precision
23238   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
23239   // instructions: convert to single, rsqrtss, convert back to double, refine
23240   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
23241   // along with FMA, this could be a throughput win.
23242   // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
23243   // after legalize types.
23244   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
23245       (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
23246       (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
23247       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
23248       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
23249     if (RefinementSteps == ReciprocalEstimate::Unspecified)
23250       RefinementSteps = 1;
23251 
23252     UseOneConstNR = false;
23253     // There is no FSQRT for 512-bits, but there is RSQRT14.
23254     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
23255     SDValue Estimate = DAG.getNode(Opcode, DL, VT, Op);
23256     if (RefinementSteps == 0 && !Reciprocal)
23257       Estimate = DAG.getNode(ISD::FMUL, DL, VT, Op, Estimate);
23258     return Estimate;
23259   }
23260 
23261   if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
23262       Subtarget.hasFP16()) {
23263     assert(Reciprocal && "Don't replace SQRT with RSQRT for half type");
23264     if (RefinementSteps == ReciprocalEstimate::Unspecified)
23265       RefinementSteps = 0;
23266 
23267     if (VT == MVT::f16) {
23268       SDValue Zero = DAG.getIntPtrConstant(0, DL);
23269       SDValue Undef = DAG.getUNDEF(MVT::v8f16);
23270       Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
23271       Op = DAG.getNode(X86ISD::RSQRT14S, DL, MVT::v8f16, Undef, Op);
23272       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
23273     }
23274 
23275     return DAG.getNode(X86ISD::RSQRT14, DL, VT, Op);
23276   }
23277   return SDValue();
23278 }
23279 
23280 /// The minimum architected relative accuracy is 2^-12. We need one
23281 /// Newton-Raphson step to have a good float result (24 bits of precision).
23282 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
23283                                             int Enabled,
23284                                             int &RefinementSteps) const {
23285   SDLoc DL(Op);
23286   EVT VT = Op.getValueType();
23287 
23288   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
23289   // It is likely not profitable to do this for f64 because a double-precision
23290   // reciprocal estimate with refinement on x86 prior to FMA requires
23291   // 15 instructions: convert to single, rcpss, convert back to double, refine
23292   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
23293   // along with FMA, this could be a throughput win.
23294 
23295   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
23296       (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
23297       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
23298       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
23299     // Enable estimate codegen with 1 refinement step for vector division.
23300     // Scalar division estimates are disabled because they break too much
23301     // real-world code. These defaults are intended to match GCC behavior.
23302     if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
23303       return SDValue();
23304 
23305     if (RefinementSteps == ReciprocalEstimate::Unspecified)
23306       RefinementSteps = 1;
23307 
23308     // There is no FSQRT for 512-bits, but there is RCP14.
23309     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
23310     return DAG.getNode(Opcode, DL, VT, Op);
23311   }
23312 
23313   if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
23314       Subtarget.hasFP16()) {
23315     if (RefinementSteps == ReciprocalEstimate::Unspecified)
23316       RefinementSteps = 0;
23317 
23318     if (VT == MVT::f16) {
23319       SDValue Zero = DAG.getIntPtrConstant(0, DL);
23320       SDValue Undef = DAG.getUNDEF(MVT::v8f16);
23321       Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
23322       Op = DAG.getNode(X86ISD::RCP14S, DL, MVT::v8f16, Undef, Op);
23323       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
23324     }
23325 
23326     return DAG.getNode(X86ISD::RCP14, DL, VT, Op);
23327   }
23328   return SDValue();
23329 }
23330 
23331 /// If we have at least two divisions that use the same divisor, convert to
23332 /// multiplication by a reciprocal. This may need to be adjusted for a given
23333 /// CPU if a division's cost is not at least twice the cost of a multiplication.
23334 /// This is because we still need one division to calculate the reciprocal and
23335 /// then we need two multiplies by that reciprocal as replacements for the
23336 /// original divisions.
23337 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
23338   return 2;
23339 }
23340 
23341 SDValue
23342 X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
23343                                  SelectionDAG &DAG,
23344                                  SmallVectorImpl<SDNode *> &Created) const {
23345   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
23346   if (isIntDivCheap(N->getValueType(0), Attr))
23347     return SDValue(N,0); // Lower SDIV as SDIV
23348 
23349   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
23350          "Unexpected divisor!");
23351 
23352   // Only perform this transform if CMOV is supported otherwise the select
23353   // below will become a branch.
23354   if (!Subtarget.hasCMov())
23355     return SDValue();
23356 
23357   // fold (sdiv X, pow2)
23358   EVT VT = N->getValueType(0);
23359   // FIXME: Support i8.
23360   if (VT != MVT::i16 && VT != MVT::i32 &&
23361       !(Subtarget.is64Bit() && VT == MVT::i64))
23362     return SDValue();
23363 
23364   unsigned Lg2 = Divisor.countTrailingZeros();
23365 
23366   // If the divisor is 2 or -2, the default expansion is better.
23367   if (Lg2 == 1)
23368     return SDValue();
23369 
23370   SDLoc DL(N);
23371   SDValue N0 = N->getOperand(0);
23372   SDValue Zero = DAG.getConstant(0, DL, VT);
23373   APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
23374   SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
23375 
23376   // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
23377   SDValue Cmp = DAG.getSetCC(DL, MVT::i8, N0, Zero, ISD::SETLT);
23378   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
23379   SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
23380 
23381   Created.push_back(Cmp.getNode());
23382   Created.push_back(Add.getNode());
23383   Created.push_back(CMov.getNode());
23384 
23385   // Divide by pow2.
23386   SDValue SRA =
23387       DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, MVT::i8));
23388 
23389   // If we're dividing by a positive value, we're done.  Otherwise, we must
23390   // negate the result.
23391   if (Divisor.isNonNegative())
23392     return SRA;
23393 
23394   Created.push_back(SRA.getNode());
23395   return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
23396 }
23397 
23398 /// Result of 'and' is compared against zero. Change to a BT node if possible.
23399 /// Returns the BT node and the condition code needed to use it.
23400 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC,
23401                             const SDLoc &dl, SelectionDAG &DAG,
23402                             SDValue &X86CC) {
23403   assert(And.getOpcode() == ISD::AND && "Expected AND node!");
23404   SDValue Op0 = And.getOperand(0);
23405   SDValue Op1 = And.getOperand(1);
23406   if (Op0.getOpcode() == ISD::TRUNCATE)
23407     Op0 = Op0.getOperand(0);
23408   if (Op1.getOpcode() == ISD::TRUNCATE)
23409     Op1 = Op1.getOperand(0);
23410 
23411   SDValue Src, BitNo;
23412   if (Op1.getOpcode() == ISD::SHL)
23413     std::swap(Op0, Op1);
23414   if (Op0.getOpcode() == ISD::SHL) {
23415     if (isOneConstant(Op0.getOperand(0))) {
23416       // If we looked past a truncate, check that it's only truncating away
23417       // known zeros.
23418       unsigned BitWidth = Op0.getValueSizeInBits();
23419       unsigned AndBitWidth = And.getValueSizeInBits();
23420       if (BitWidth > AndBitWidth) {
23421         KnownBits Known = DAG.computeKnownBits(Op0);
23422         if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
23423           return SDValue();
23424       }
23425       Src = Op1;
23426       BitNo = Op0.getOperand(1);
23427     }
23428   } else if (Op1.getOpcode() == ISD::Constant) {
23429     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
23430     uint64_t AndRHSVal = AndRHS->getZExtValue();
23431     SDValue AndLHS = Op0;
23432 
23433     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
23434       Src = AndLHS.getOperand(0);
23435       BitNo = AndLHS.getOperand(1);
23436     } else {
23437       // Use BT if the immediate can't be encoded in a TEST instruction or we
23438       // are optimizing for size and the immedaite won't fit in a byte.
23439       bool OptForSize = DAG.shouldOptForSize();
23440       if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
23441           isPowerOf2_64(AndRHSVal)) {
23442         Src = AndLHS;
23443         BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
23444                                 Src.getValueType());
23445       }
23446     }
23447   }
23448 
23449   // No patterns found, give up.
23450   if (!Src.getNode())
23451     return SDValue();
23452 
23453   // If Src is i8, promote it to i32 with any_extend.  There is no i8 BT
23454   // instruction.  Since the shift amount is in-range-or-undefined, we know
23455   // that doing a bittest on the i32 value is ok.  We extend to i32 because
23456   // the encoding for the i16 version is larger than the i32 version.
23457   // Also promote i16 to i32 for performance / code size reason.
23458   if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
23459     Src = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Src);
23460 
23461   // See if we can use the 32-bit instruction instead of the 64-bit one for a
23462   // shorter encoding. Since the former takes the modulo 32 of BitNo and the
23463   // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
23464   // known to be zero.
23465   if (Src.getValueType() == MVT::i64 &&
23466       DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
23467     Src = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
23468 
23469   // If the operand types disagree, extend the shift amount to match.  Since
23470   // BT ignores high bits (like shifts) we can use anyextend.
23471   if (Src.getValueType() != BitNo.getValueType())
23472     BitNo = DAG.getNode(ISD::ANY_EXTEND, dl, Src.getValueType(), BitNo);
23473 
23474   X86CC = DAG.getTargetConstant(CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B,
23475                                 dl, MVT::i8);
23476   return DAG.getNode(X86ISD::BT, dl, MVT::i32, Src, BitNo);
23477 }
23478 
23479 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
23480 /// CMPs.
23481 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
23482                                    SDValue &Op1, bool &IsAlwaysSignaling) {
23483   unsigned SSECC;
23484   bool Swap = false;
23485 
23486   // SSE Condition code mapping:
23487   //  0 - EQ
23488   //  1 - LT
23489   //  2 - LE
23490   //  3 - UNORD
23491   //  4 - NEQ
23492   //  5 - NLT
23493   //  6 - NLE
23494   //  7 - ORD
23495   switch (SetCCOpcode) {
23496   default: llvm_unreachable("Unexpected SETCC condition");
23497   case ISD::SETOEQ:
23498   case ISD::SETEQ:  SSECC = 0; break;
23499   case ISD::SETOGT:
23500   case ISD::SETGT:  Swap = true; LLVM_FALLTHROUGH;
23501   case ISD::SETLT:
23502   case ISD::SETOLT: SSECC = 1; break;
23503   case ISD::SETOGE:
23504   case ISD::SETGE:  Swap = true; LLVM_FALLTHROUGH;
23505   case ISD::SETLE:
23506   case ISD::SETOLE: SSECC = 2; break;
23507   case ISD::SETUO:  SSECC = 3; break;
23508   case ISD::SETUNE:
23509   case ISD::SETNE:  SSECC = 4; break;
23510   case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
23511   case ISD::SETUGE: SSECC = 5; break;
23512   case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
23513   case ISD::SETUGT: SSECC = 6; break;
23514   case ISD::SETO:   SSECC = 7; break;
23515   case ISD::SETUEQ: SSECC = 8; break;
23516   case ISD::SETONE: SSECC = 12; break;
23517   }
23518   if (Swap)
23519     std::swap(Op0, Op1);
23520 
23521   switch (SetCCOpcode) {
23522   default:
23523     IsAlwaysSignaling = true;
23524     break;
23525   case ISD::SETEQ:
23526   case ISD::SETOEQ:
23527   case ISD::SETUEQ:
23528   case ISD::SETNE:
23529   case ISD::SETONE:
23530   case ISD::SETUNE:
23531   case ISD::SETO:
23532   case ISD::SETUO:
23533     IsAlwaysSignaling = false;
23534     break;
23535   }
23536 
23537   return SSECC;
23538 }
23539 
23540 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
23541 /// concatenate the result back.
23542 static SDValue splitIntVSETCC(EVT VT, SDValue LHS, SDValue RHS,
23543                               ISD::CondCode Cond, SelectionDAG &DAG,
23544                               const SDLoc &dl) {
23545   assert(VT.isInteger() && VT == LHS.getValueType() &&
23546          VT == RHS.getValueType() && "Unsupported VTs!");
23547 
23548   SDValue CC = DAG.getCondCode(Cond);
23549 
23550   // Extract the LHS Lo/Hi vectors
23551   SDValue LHS1, LHS2;
23552   std::tie(LHS1, LHS2) = splitVector(LHS, DAG, dl);
23553 
23554   // Extract the RHS Lo/Hi vectors
23555   SDValue RHS1, RHS2;
23556   std::tie(RHS1, RHS2) = splitVector(RHS, DAG, dl);
23557 
23558   // Issue the operation on the smaller types and concatenate the result back
23559   EVT LoVT, HiVT;
23560   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
23561   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
23562                      DAG.getNode(ISD::SETCC, dl, LoVT, LHS1, RHS1, CC),
23563                      DAG.getNode(ISD::SETCC, dl, HiVT, LHS2, RHS2, CC));
23564 }
23565 
23566 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
23567 
23568   SDValue Op0 = Op.getOperand(0);
23569   SDValue Op1 = Op.getOperand(1);
23570   SDValue CC = Op.getOperand(2);
23571   MVT VT = Op.getSimpleValueType();
23572   SDLoc dl(Op);
23573 
23574   assert(VT.getVectorElementType() == MVT::i1 &&
23575          "Cannot set masked compare for this operation");
23576 
23577   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
23578 
23579   // Prefer SETGT over SETLT.
23580   if (SetCCOpcode == ISD::SETLT) {
23581     SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
23582     std::swap(Op0, Op1);
23583   }
23584 
23585   return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
23586 }
23587 
23588 /// Given a buildvector constant, return a new vector constant with each element
23589 /// incremented or decremented. If incrementing or decrementing would result in
23590 /// unsigned overflow or underflow or this is not a simple vector constant,
23591 /// return an empty value.
23592 static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc) {
23593   auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
23594   if (!BV)
23595     return SDValue();
23596 
23597   MVT VT = V.getSimpleValueType();
23598   MVT EltVT = VT.getVectorElementType();
23599   unsigned NumElts = VT.getVectorNumElements();
23600   SmallVector<SDValue, 8> NewVecC;
23601   SDLoc DL(V);
23602   for (unsigned i = 0; i < NumElts; ++i) {
23603     auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
23604     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
23605       return SDValue();
23606 
23607     // Avoid overflow/underflow.
23608     const APInt &EltC = Elt->getAPIntValue();
23609     if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isZero()))
23610       return SDValue();
23611 
23612     NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
23613   }
23614 
23615   return DAG.getBuildVector(VT, DL, NewVecC);
23616 }
23617 
23618 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
23619 /// Op0 u<= Op1:
23620 ///   t = psubus Op0, Op1
23621 ///   pcmpeq t, <0..0>
23622 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
23623                                     ISD::CondCode Cond, const SDLoc &dl,
23624                                     const X86Subtarget &Subtarget,
23625                                     SelectionDAG &DAG) {
23626   if (!Subtarget.hasSSE2())
23627     return SDValue();
23628 
23629   MVT VET = VT.getVectorElementType();
23630   if (VET != MVT::i8 && VET != MVT::i16)
23631     return SDValue();
23632 
23633   switch (Cond) {
23634   default:
23635     return SDValue();
23636   case ISD::SETULT: {
23637     // If the comparison is against a constant we can turn this into a
23638     // setule.  With psubus, setule does not require a swap.  This is
23639     // beneficial because the constant in the register is no longer
23640     // destructed as the destination so it can be hoisted out of a loop.
23641     // Only do this pre-AVX since vpcmp* is no longer destructive.
23642     if (Subtarget.hasAVX())
23643       return SDValue();
23644     SDValue ULEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false);
23645     if (!ULEOp1)
23646       return SDValue();
23647     Op1 = ULEOp1;
23648     break;
23649   }
23650   case ISD::SETUGT: {
23651     // If the comparison is against a constant, we can turn this into a setuge.
23652     // This is beneficial because materializing a constant 0 for the PCMPEQ is
23653     // probably cheaper than XOR+PCMPGT using 2 different vector constants:
23654     // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
23655     SDValue UGEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true);
23656     if (!UGEOp1)
23657       return SDValue();
23658     Op1 = Op0;
23659     Op0 = UGEOp1;
23660     break;
23661   }
23662   // Psubus is better than flip-sign because it requires no inversion.
23663   case ISD::SETUGE:
23664     std::swap(Op0, Op1);
23665     break;
23666   case ISD::SETULE:
23667     break;
23668   }
23669 
23670   SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
23671   return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
23672                      DAG.getConstant(0, dl, VT));
23673 }
23674 
23675 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
23676                            SelectionDAG &DAG) {
23677   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
23678                   Op.getOpcode() == ISD::STRICT_FSETCCS;
23679   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
23680   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
23681   SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
23682   MVT VT = Op->getSimpleValueType(0);
23683   ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
23684   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
23685   SDLoc dl(Op);
23686 
23687   if (isFP) {
23688 #ifndef NDEBUG
23689     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
23690     assert(EltVT == MVT::f16 || EltVT == MVT::f32 || EltVT == MVT::f64);
23691 #endif
23692 
23693     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
23694     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
23695 
23696     // If we have a strict compare with a vXi1 result and the input is 128/256
23697     // bits we can't use a masked compare unless we have VLX. If we use a wider
23698     // compare like we do for non-strict, we might trigger spurious exceptions
23699     // from the upper elements. Instead emit a AVX compare and convert to mask.
23700     unsigned Opc;
23701     if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1 &&
23702         (!IsStrict || Subtarget.hasVLX() ||
23703          Op0.getSimpleValueType().is512BitVector())) {
23704 #ifndef NDEBUG
23705       unsigned Num = VT.getVectorNumElements();
23706       assert(Num <= 16 || (Num == 32 && EltVT == MVT::f16));
23707 #endif
23708       Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
23709     } else {
23710       Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
23711       // The SSE/AVX packed FP comparison nodes are defined with a
23712       // floating-point vector result that matches the operand type. This allows
23713       // them to work with an SSE1 target (integer vector types are not legal).
23714       VT = Op0.getSimpleValueType();
23715     }
23716 
23717     SDValue Cmp;
23718     bool IsAlwaysSignaling;
23719     unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
23720     if (!Subtarget.hasAVX()) {
23721       // TODO: We could use following steps to handle a quiet compare with
23722       // signaling encodings.
23723       // 1. Get ordered masks from a quiet ISD::SETO
23724       // 2. Use the masks to mask potential unordered elements in operand A, B
23725       // 3. Get the compare results of masked A, B
23726       // 4. Calculating final result using the mask and result from 3
23727       // But currently, we just fall back to scalar operations.
23728       if (IsStrict && IsAlwaysSignaling && !IsSignaling)
23729         return SDValue();
23730 
23731       // Insert an extra signaling instruction to raise exception.
23732       if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
23733         SDValue SignalCmp = DAG.getNode(
23734             Opc, dl, {VT, MVT::Other},
23735             {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
23736         // FIXME: It seems we need to update the flags of all new strict nodes.
23737         // Otherwise, mayRaiseFPException in MI will return false due to
23738         // NoFPExcept = false by default. However, I didn't find it in other
23739         // patches.
23740         SignalCmp->setFlags(Op->getFlags());
23741         Chain = SignalCmp.getValue(1);
23742       }
23743 
23744       // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
23745       // emit two comparisons and a logic op to tie them together.
23746       if (SSECC >= 8) {
23747         // LLVM predicate is SETUEQ or SETONE.
23748         unsigned CC0, CC1;
23749         unsigned CombineOpc;
23750         if (Cond == ISD::SETUEQ) {
23751           CC0 = 3; // UNORD
23752           CC1 = 0; // EQ
23753           CombineOpc = X86ISD::FOR;
23754         } else {
23755           assert(Cond == ISD::SETONE);
23756           CC0 = 7; // ORD
23757           CC1 = 4; // NEQ
23758           CombineOpc = X86ISD::FAND;
23759         }
23760 
23761         SDValue Cmp0, Cmp1;
23762         if (IsStrict) {
23763           Cmp0 = DAG.getNode(
23764               Opc, dl, {VT, MVT::Other},
23765               {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
23766           Cmp1 = DAG.getNode(
23767               Opc, dl, {VT, MVT::Other},
23768               {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
23769           Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
23770                               Cmp1.getValue(1));
23771         } else {
23772           Cmp0 = DAG.getNode(
23773               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
23774           Cmp1 = DAG.getNode(
23775               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
23776         }
23777         Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
23778       } else {
23779         if (IsStrict) {
23780           Cmp = DAG.getNode(
23781               Opc, dl, {VT, MVT::Other},
23782               {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
23783           Chain = Cmp.getValue(1);
23784         } else
23785           Cmp = DAG.getNode(
23786               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
23787       }
23788     } else {
23789       // Handle all other FP comparisons here.
23790       if (IsStrict) {
23791         // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
23792         SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
23793         Cmp = DAG.getNode(
23794             Opc, dl, {VT, MVT::Other},
23795             {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
23796         Chain = Cmp.getValue(1);
23797       } else
23798         Cmp = DAG.getNode(
23799             Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
23800     }
23801 
23802     if (VT.getFixedSizeInBits() >
23803         Op.getSimpleValueType().getFixedSizeInBits()) {
23804       // We emitted a compare with an XMM/YMM result. Finish converting to a
23805       // mask register using a vptestm.
23806       EVT CastVT = EVT(VT).changeVectorElementTypeToInteger();
23807       Cmp = DAG.getBitcast(CastVT, Cmp);
23808       Cmp = DAG.getSetCC(dl, Op.getSimpleValueType(), Cmp,
23809                          DAG.getConstant(0, dl, CastVT), ISD::SETNE);
23810     } else {
23811       // If this is SSE/AVX CMPP, bitcast the result back to integer to match
23812       // the result type of SETCC. The bitcast is expected to be optimized
23813       // away during combining/isel.
23814       Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
23815     }
23816 
23817     if (IsStrict)
23818       return DAG.getMergeValues({Cmp, Chain}, dl);
23819 
23820     return Cmp;
23821   }
23822 
23823   assert(!IsStrict && "Strict SETCC only handles FP operands.");
23824 
23825   MVT VTOp0 = Op0.getSimpleValueType();
23826   (void)VTOp0;
23827   assert(VTOp0 == Op1.getSimpleValueType() &&
23828          "Expected operands with same type!");
23829   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
23830          "Invalid number of packed elements for source and destination!");
23831 
23832   // The non-AVX512 code below works under the assumption that source and
23833   // destination types are the same.
23834   assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
23835          "Value types for source and destination must be the same!");
23836 
23837   // The result is boolean, but operands are int/float
23838   if (VT.getVectorElementType() == MVT::i1) {
23839     // In AVX-512 architecture setcc returns mask with i1 elements,
23840     // But there is no compare instruction for i8 and i16 elements in KNL.
23841     assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
23842            "Unexpected operand type");
23843     return LowerIntVSETCC_AVX512(Op, DAG);
23844   }
23845 
23846   // Lower using XOP integer comparisons.
23847   if (VT.is128BitVector() && Subtarget.hasXOP()) {
23848     // Translate compare code to XOP PCOM compare mode.
23849     unsigned CmpMode = 0;
23850     switch (Cond) {
23851     default: llvm_unreachable("Unexpected SETCC condition");
23852     case ISD::SETULT:
23853     case ISD::SETLT: CmpMode = 0x00; break;
23854     case ISD::SETULE:
23855     case ISD::SETLE: CmpMode = 0x01; break;
23856     case ISD::SETUGT:
23857     case ISD::SETGT: CmpMode = 0x02; break;
23858     case ISD::SETUGE:
23859     case ISD::SETGE: CmpMode = 0x03; break;
23860     case ISD::SETEQ: CmpMode = 0x04; break;
23861     case ISD::SETNE: CmpMode = 0x05; break;
23862     }
23863 
23864     // Are we comparing unsigned or signed integers?
23865     unsigned Opc =
23866         ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
23867 
23868     return DAG.getNode(Opc, dl, VT, Op0, Op1,
23869                        DAG.getTargetConstant(CmpMode, dl, MVT::i8));
23870   }
23871 
23872   // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
23873   // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
23874   if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
23875     SDValue BC0 = peekThroughBitcasts(Op0);
23876     if (BC0.getOpcode() == ISD::AND) {
23877       APInt UndefElts;
23878       SmallVector<APInt, 64> EltBits;
23879       if (getTargetConstantBitsFromNode(BC0.getOperand(1),
23880                                         VT.getScalarSizeInBits(), UndefElts,
23881                                         EltBits, false, false)) {
23882         if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
23883           Cond = ISD::SETEQ;
23884           Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
23885         }
23886       }
23887     }
23888   }
23889 
23890   // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
23891   if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
23892       Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
23893     ConstantSDNode *C1 = isConstOrConstSplat(Op1);
23894     if (C1 && C1->getAPIntValue().isPowerOf2()) {
23895       unsigned BitWidth = VT.getScalarSizeInBits();
23896       unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
23897 
23898       SDValue Result = Op0.getOperand(0);
23899       Result = DAG.getNode(ISD::SHL, dl, VT, Result,
23900                            DAG.getConstant(ShiftAmt, dl, VT));
23901       Result = DAG.getNode(ISD::SRA, dl, VT, Result,
23902                            DAG.getConstant(BitWidth - 1, dl, VT));
23903       return Result;
23904     }
23905   }
23906 
23907   // Break 256-bit integer vector compare into smaller ones.
23908   if (VT.is256BitVector() && !Subtarget.hasInt256())
23909     return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
23910 
23911   if (VT == MVT::v32i16 || VT == MVT::v64i8) {
23912     assert(!Subtarget.hasBWI() && "Unexpected VT with AVX512BW!");
23913     return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
23914   }
23915 
23916   // If we have a limit constant, try to form PCMPGT (signed cmp) to avoid
23917   // not-of-PCMPEQ:
23918   // X != INT_MIN --> X >s INT_MIN
23919   // X != INT_MAX --> X <s INT_MAX --> INT_MAX >s X
23920   // +X != 0 --> +X >s 0
23921   APInt ConstValue;
23922   if (Cond == ISD::SETNE &&
23923       ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
23924     if (ConstValue.isMinSignedValue())
23925       Cond = ISD::SETGT;
23926     else if (ConstValue.isMaxSignedValue())
23927       Cond = ISD::SETLT;
23928     else if (ConstValue.isZero() && DAG.SignBitIsZero(Op0))
23929       Cond = ISD::SETGT;
23930   }
23931 
23932   // If both operands are known non-negative, then an unsigned compare is the
23933   // same as a signed compare and there's no need to flip signbits.
23934   // TODO: We could check for more general simplifications here since we're
23935   // computing known bits.
23936   bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
23937                    !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
23938 
23939   // Special case: Use min/max operations for unsigned compares.
23940   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23941   if (ISD::isUnsignedIntSetCC(Cond) &&
23942       (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
23943       TLI.isOperationLegal(ISD::UMIN, VT)) {
23944     // If we have a constant operand, increment/decrement it and change the
23945     // condition to avoid an invert.
23946     if (Cond == ISD::SETUGT) {
23947       // X > C --> X >= (C+1) --> X == umax(X, C+1)
23948       if (SDValue UGTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true)) {
23949         Op1 = UGTOp1;
23950         Cond = ISD::SETUGE;
23951       }
23952     }
23953     if (Cond == ISD::SETULT) {
23954       // X < C --> X <= (C-1) --> X == umin(X, C-1)
23955       if (SDValue ULTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false)) {
23956         Op1 = ULTOp1;
23957         Cond = ISD::SETULE;
23958       }
23959     }
23960     bool Invert = false;
23961     unsigned Opc;
23962     switch (Cond) {
23963     default: llvm_unreachable("Unexpected condition code");
23964     case ISD::SETUGT: Invert = true; LLVM_FALLTHROUGH;
23965     case ISD::SETULE: Opc = ISD::UMIN; break;
23966     case ISD::SETULT: Invert = true; LLVM_FALLTHROUGH;
23967     case ISD::SETUGE: Opc = ISD::UMAX; break;
23968     }
23969 
23970     SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23971     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
23972 
23973     // If the logical-not of the result is required, perform that now.
23974     if (Invert)
23975       Result = DAG.getNOT(dl, Result, VT);
23976 
23977     return Result;
23978   }
23979 
23980   // Try to use SUBUS and PCMPEQ.
23981   if (FlipSigns)
23982     if (SDValue V =
23983             LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
23984       return V;
23985 
23986   // We are handling one of the integer comparisons here. Since SSE only has
23987   // GT and EQ comparisons for integer, swapping operands and multiple
23988   // operations may be required for some comparisons.
23989   unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
23990                                                             : X86ISD::PCMPGT;
23991   bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
23992               Cond == ISD::SETGE || Cond == ISD::SETUGE;
23993   bool Invert = Cond == ISD::SETNE ||
23994                 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
23995 
23996   if (Swap)
23997     std::swap(Op0, Op1);
23998 
23999   // Check that the operation in question is available (most are plain SSE2,
24000   // but PCMPGTQ and PCMPEQQ have different requirements).
24001   if (VT == MVT::v2i64) {
24002     if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
24003       assert(Subtarget.hasSSE2() && "Don't know how to lower!");
24004 
24005       // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
24006       // the odd elements over the even elements.
24007       if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
24008         Op0 = DAG.getConstant(0, dl, MVT::v4i32);
24009         Op1 = DAG.getBitcast(MVT::v4i32, Op1);
24010 
24011         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
24012         static const int MaskHi[] = { 1, 1, 3, 3 };
24013         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
24014 
24015         return DAG.getBitcast(VT, Result);
24016       }
24017 
24018       if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
24019         Op0 = DAG.getBitcast(MVT::v4i32, Op0);
24020         Op1 = DAG.getConstant(-1, dl, MVT::v4i32);
24021 
24022         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
24023         static const int MaskHi[] = { 1, 1, 3, 3 };
24024         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
24025 
24026         return DAG.getBitcast(VT, Result);
24027       }
24028 
24029       // Since SSE has no unsigned integer comparisons, we need to flip the sign
24030       // bits of the inputs before performing those operations. The lower
24031       // compare is always unsigned.
24032       SDValue SB;
24033       if (FlipSigns) {
24034         SB = DAG.getConstant(0x8000000080000000ULL, dl, MVT::v2i64);
24035       } else {
24036         SB = DAG.getConstant(0x0000000080000000ULL, dl, MVT::v2i64);
24037       }
24038       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
24039       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
24040 
24041       // Cast everything to the right type.
24042       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
24043       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
24044 
24045       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
24046       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
24047       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
24048 
24049       // Create masks for only the low parts/high parts of the 64 bit integers.
24050       static const int MaskHi[] = { 1, 1, 3, 3 };
24051       static const int MaskLo[] = { 0, 0, 2, 2 };
24052       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
24053       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
24054       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
24055 
24056       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
24057       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
24058 
24059       if (Invert)
24060         Result = DAG.getNOT(dl, Result, MVT::v4i32);
24061 
24062       return DAG.getBitcast(VT, Result);
24063     }
24064 
24065     if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
24066       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
24067       // pcmpeqd + pshufd + pand.
24068       assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
24069 
24070       // First cast everything to the right type.
24071       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
24072       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
24073 
24074       // Do the compare.
24075       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
24076 
24077       // Make sure the lower and upper halves are both all-ones.
24078       static const int Mask[] = { 1, 0, 3, 2 };
24079       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
24080       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
24081 
24082       if (Invert)
24083         Result = DAG.getNOT(dl, Result, MVT::v4i32);
24084 
24085       return DAG.getBitcast(VT, Result);
24086     }
24087   }
24088 
24089   // Since SSE has no unsigned integer comparisons, we need to flip the sign
24090   // bits of the inputs before performing those operations.
24091   if (FlipSigns) {
24092     MVT EltVT = VT.getVectorElementType();
24093     SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
24094                                  VT);
24095     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
24096     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
24097   }
24098 
24099   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
24100 
24101   // If the logical-not of the result is required, perform that now.
24102   if (Invert)
24103     Result = DAG.getNOT(dl, Result, VT);
24104 
24105   return Result;
24106 }
24107 
24108 // Try to select this as a KORTEST+SETCC or KTEST+SETCC if possible.
24109 static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
24110                               const SDLoc &dl, SelectionDAG &DAG,
24111                               const X86Subtarget &Subtarget,
24112                               SDValue &X86CC) {
24113   // Only support equality comparisons.
24114   if (CC != ISD::SETEQ && CC != ISD::SETNE)
24115     return SDValue();
24116 
24117   // Must be a bitcast from vXi1.
24118   if (Op0.getOpcode() != ISD::BITCAST)
24119     return SDValue();
24120 
24121   Op0 = Op0.getOperand(0);
24122   MVT VT = Op0.getSimpleValueType();
24123   if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
24124       !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
24125       !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
24126     return SDValue();
24127 
24128   X86::CondCode X86Cond;
24129   if (isNullConstant(Op1)) {
24130     X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
24131   } else if (isAllOnesConstant(Op1)) {
24132     // C flag is set for all ones.
24133     X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
24134   } else
24135     return SDValue();
24136 
24137   // If the input is an AND, we can combine it's operands into the KTEST.
24138   bool KTestable = false;
24139   if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
24140     KTestable = true;
24141   if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
24142     KTestable = true;
24143   if (!isNullConstant(Op1))
24144     KTestable = false;
24145   if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
24146     SDValue LHS = Op0.getOperand(0);
24147     SDValue RHS = Op0.getOperand(1);
24148     X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24149     return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
24150   }
24151 
24152   // If the input is an OR, we can combine it's operands into the KORTEST.
24153   SDValue LHS = Op0;
24154   SDValue RHS = Op0;
24155   if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
24156     LHS = Op0.getOperand(0);
24157     RHS = Op0.getOperand(1);
24158   }
24159 
24160   X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24161   return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
24162 }
24163 
24164 /// Emit flags for the given setcc condition and operands. Also returns the
24165 /// corresponding X86 condition code constant in X86CC.
24166 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
24167                                              ISD::CondCode CC, const SDLoc &dl,
24168                                              SelectionDAG &DAG,
24169                                              SDValue &X86CC) const {
24170   // Optimize to BT if possible.
24171   // Lower (X & (1 << N)) == 0 to BT(X, N).
24172   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
24173   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
24174   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1) &&
24175       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
24176     if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CC))
24177       return BT;
24178   }
24179 
24180   // Try to use PTEST/PMOVMSKB for a tree ORs equality compared with 0.
24181   // TODO: We could do AND tree with all 1s as well by using the C flag.
24182   if (isNullConstant(Op1) && (CC == ISD::SETEQ || CC == ISD::SETNE))
24183     if (SDValue CmpZ =
24184             MatchVectorAllZeroTest(Op0, CC, dl, Subtarget, DAG, X86CC))
24185       return CmpZ;
24186 
24187   // Try to lower using KORTEST or KTEST.
24188   if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
24189     return Test;
24190 
24191   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
24192   // these.
24193   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
24194       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
24195     // If the input is a setcc, then reuse the input setcc or use a new one with
24196     // the inverted condition.
24197     if (Op0.getOpcode() == X86ISD::SETCC) {
24198       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
24199 
24200       X86CC = Op0.getOperand(0);
24201       if (Invert) {
24202         X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
24203         CCode = X86::GetOppositeBranchCondition(CCode);
24204         X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
24205       }
24206 
24207       return Op0.getOperand(1);
24208     }
24209   }
24210 
24211   // Try to use the carry flag from the add in place of an separate CMP for:
24212   // (seteq (add X, -1), -1). Similar for setne.
24213   if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
24214       Op0.getOperand(1) == Op1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
24215     if (isProfitableToUseFlagOp(Op0)) {
24216       SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
24217 
24218       SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
24219                                 Op0.getOperand(1));
24220       DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
24221       X86::CondCode CCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
24222       X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
24223       return SDValue(New.getNode(), 1);
24224     }
24225   }
24226 
24227   X86::CondCode CondCode =
24228       TranslateX86CC(CC, dl, /*IsFP*/ false, Op0, Op1, DAG);
24229   assert(CondCode != X86::COND_INVALID && "Unexpected condition code!");
24230 
24231   SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget);
24232   X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
24233   return EFLAGS;
24234 }
24235 
24236 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
24237 
24238   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
24239                   Op.getOpcode() == ISD::STRICT_FSETCCS;
24240   MVT VT = Op->getSimpleValueType(0);
24241 
24242   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
24243 
24244   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
24245   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
24246   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
24247   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
24248   SDLoc dl(Op);
24249   ISD::CondCode CC =
24250       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
24251 
24252   // Handle f128 first, since one possible outcome is a normal integer
24253   // comparison which gets handled by emitFlagsForSetcc.
24254   if (Op0.getValueType() == MVT::f128) {
24255     softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
24256                         Op.getOpcode() == ISD::STRICT_FSETCCS);
24257 
24258     // If softenSetCCOperands returned a scalar, use it.
24259     if (!Op1.getNode()) {
24260       assert(Op0.getValueType() == Op.getValueType() &&
24261              "Unexpected setcc expansion!");
24262       if (IsStrict)
24263         return DAG.getMergeValues({Op0, Chain}, dl);
24264       return Op0;
24265     }
24266   }
24267 
24268   if (Op0.getSimpleValueType().isInteger()) {
24269     // Attempt to canonicalize SGT/UGT -> SGE/UGE compares with constant which
24270     // reduces the number of EFLAGs bit reads (the GE conditions don't read ZF),
24271     // this may translate to less uops depending on uarch implementation. The
24272     // equivalent for SLE/ULE -> SLT/ULT isn't likely to happen as we already
24273     // canonicalize to that CondCode.
24274     // NOTE: Only do this if incrementing the constant doesn't increase the bit
24275     // encoding size - so it must either already be a i8 or i32 immediate, or it
24276     // shrinks down to that. We don't do this for any i64's to avoid additional
24277     // constant materializations.
24278     // TODO: Can we move this to TranslateX86CC to handle jumps/branches too?
24279     if (auto *Op1C = dyn_cast<ConstantSDNode>(Op1)) {
24280       const APInt &Op1Val = Op1C->getAPIntValue();
24281       if (!Op1Val.isZero()) {
24282         // Ensure the constant+1 doesn't overflow.
24283         if ((CC == ISD::CondCode::SETGT && !Op1Val.isMaxSignedValue()) ||
24284             (CC == ISD::CondCode::SETUGT && !Op1Val.isMaxValue())) {
24285           APInt Op1ValPlusOne = Op1Val + 1;
24286           if (Op1ValPlusOne.isSignedIntN(32) &&
24287               (!Op1Val.isSignedIntN(8) || Op1ValPlusOne.isSignedIntN(8))) {
24288             Op1 = DAG.getConstant(Op1ValPlusOne, dl, Op0.getValueType());
24289             CC = CC == ISD::CondCode::SETGT ? ISD::CondCode::SETGE
24290                                             : ISD::CondCode::SETUGE;
24291           }
24292         }
24293       }
24294     }
24295 
24296     SDValue X86CC;
24297     SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
24298     SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
24299     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
24300   }
24301 
24302   // Handle floating point.
24303   X86::CondCode CondCode = TranslateX86CC(CC, dl, /*IsFP*/ true, Op0, Op1, DAG);
24304   if (CondCode == X86::COND_INVALID)
24305     return SDValue();
24306 
24307   SDValue EFLAGS;
24308   if (IsStrict) {
24309     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
24310     EFLAGS =
24311         DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
24312                     dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
24313     Chain = EFLAGS.getValue(1);
24314   } else {
24315     EFLAGS = DAG.getNode(X86ISD::FCMP, dl, MVT::i32, Op0, Op1);
24316   }
24317 
24318   SDValue X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
24319   SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
24320   return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
24321 }
24322 
24323 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
24324   SDValue LHS = Op.getOperand(0);
24325   SDValue RHS = Op.getOperand(1);
24326   SDValue Carry = Op.getOperand(2);
24327   SDValue Cond = Op.getOperand(3);
24328   SDLoc DL(Op);
24329 
24330   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
24331   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
24332 
24333   // Recreate the carry if needed.
24334   EVT CarryVT = Carry.getValueType();
24335   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
24336                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
24337 
24338   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
24339   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
24340   return getSETCC(CC, Cmp.getValue(1), DL, DAG);
24341 }
24342 
24343 // This function returns three things: the arithmetic computation itself
24344 // (Value), an EFLAGS result (Overflow), and a condition code (Cond).  The
24345 // flag and the condition code define the case in which the arithmetic
24346 // computation overflows.
24347 static std::pair<SDValue, SDValue>
24348 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
24349   assert(Op.getResNo() == 0 && "Unexpected result number!");
24350   SDValue Value, Overflow;
24351   SDValue LHS = Op.getOperand(0);
24352   SDValue RHS = Op.getOperand(1);
24353   unsigned BaseOp = 0;
24354   SDLoc DL(Op);
24355   switch (Op.getOpcode()) {
24356   default: llvm_unreachable("Unknown ovf instruction!");
24357   case ISD::SADDO:
24358     BaseOp = X86ISD::ADD;
24359     Cond = X86::COND_O;
24360     break;
24361   case ISD::UADDO:
24362     BaseOp = X86ISD::ADD;
24363     Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
24364     break;
24365   case ISD::SSUBO:
24366     BaseOp = X86ISD::SUB;
24367     Cond = X86::COND_O;
24368     break;
24369   case ISD::USUBO:
24370     BaseOp = X86ISD::SUB;
24371     Cond = X86::COND_B;
24372     break;
24373   case ISD::SMULO:
24374     BaseOp = X86ISD::SMUL;
24375     Cond = X86::COND_O;
24376     break;
24377   case ISD::UMULO:
24378     BaseOp = X86ISD::UMUL;
24379     Cond = X86::COND_O;
24380     break;
24381   }
24382 
24383   if (BaseOp) {
24384     // Also sets EFLAGS.
24385     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
24386     Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
24387     Overflow = Value.getValue(1);
24388   }
24389 
24390   return std::make_pair(Value, Overflow);
24391 }
24392 
24393 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
24394   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
24395   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
24396   // looks for this combo and may remove the "setcc" instruction if the "setcc"
24397   // has only one use.
24398   SDLoc DL(Op);
24399   X86::CondCode Cond;
24400   SDValue Value, Overflow;
24401   std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
24402 
24403   SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
24404   assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!");
24405   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
24406 }
24407 
24408 /// Return true if opcode is a X86 logical comparison.
24409 static bool isX86LogicalCmp(SDValue Op) {
24410   unsigned Opc = Op.getOpcode();
24411   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
24412       Opc == X86ISD::FCMP)
24413     return true;
24414   if (Op.getResNo() == 1 &&
24415       (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
24416        Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
24417        Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
24418     return true;
24419 
24420   return false;
24421 }
24422 
24423 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
24424   if (V.getOpcode() != ISD::TRUNCATE)
24425     return false;
24426 
24427   SDValue VOp0 = V.getOperand(0);
24428   unsigned InBits = VOp0.getValueSizeInBits();
24429   unsigned Bits = V.getValueSizeInBits();
24430   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
24431 }
24432 
24433 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
24434   bool AddTest = true;
24435   SDValue Cond  = Op.getOperand(0);
24436   SDValue Op1 = Op.getOperand(1);
24437   SDValue Op2 = Op.getOperand(2);
24438   SDLoc DL(Op);
24439   MVT VT = Op1.getSimpleValueType();
24440   SDValue CC;
24441 
24442   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
24443   // are available or VBLENDV if AVX is available.
24444   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
24445   if (Cond.getOpcode() == ISD::SETCC && isScalarFPTypeInSSEReg(VT) &&
24446       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
24447     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
24448     bool IsAlwaysSignaling;
24449     unsigned SSECC =
24450         translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
24451                            CondOp0, CondOp1, IsAlwaysSignaling);
24452 
24453     if (Subtarget.hasAVX512()) {
24454       SDValue Cmp =
24455           DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
24456                       DAG.getTargetConstant(SSECC, DL, MVT::i8));
24457       assert(!VT.isVector() && "Not a scalar type?");
24458       return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
24459     }
24460 
24461     if (SSECC < 8 || Subtarget.hasAVX()) {
24462       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
24463                                 DAG.getTargetConstant(SSECC, DL, MVT::i8));
24464 
24465       // If we have AVX, we can use a variable vector select (VBLENDV) instead
24466       // of 3 logic instructions for size savings and potentially speed.
24467       // Unfortunately, there is no scalar form of VBLENDV.
24468 
24469       // If either operand is a +0.0 constant, don't try this. We can expect to
24470       // optimize away at least one of the logic instructions later in that
24471       // case, so that sequence would be faster than a variable blend.
24472 
24473       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
24474       // uses XMM0 as the selection register. That may need just as many
24475       // instructions as the AND/ANDN/OR sequence due to register moves, so
24476       // don't bother.
24477       if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
24478           !isNullFPConstant(Op2)) {
24479         // Convert to vectors, do a VSELECT, and convert back to scalar.
24480         // All of the conversions should be optimized away.
24481         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
24482         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
24483         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
24484         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
24485 
24486         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
24487         VCmp = DAG.getBitcast(VCmpVT, VCmp);
24488 
24489         SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
24490 
24491         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
24492                            VSel, DAG.getIntPtrConstant(0, DL));
24493       }
24494       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
24495       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
24496       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
24497     }
24498   }
24499 
24500   // AVX512 fallback is to lower selects of scalar floats to masked moves.
24501   if (isScalarFPTypeInSSEReg(VT) && Subtarget.hasAVX512()) {
24502     SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
24503     return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
24504   }
24505 
24506   if (Cond.getOpcode() == ISD::SETCC) {
24507     if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
24508       Cond = NewCond;
24509       // If the condition was updated, it's possible that the operands of the
24510       // select were also updated (for example, EmitTest has a RAUW). Refresh
24511       // the local references to the select operands in case they got stale.
24512       Op1 = Op.getOperand(1);
24513       Op2 = Op.getOperand(2);
24514     }
24515   }
24516 
24517   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
24518   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
24519   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
24520   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
24521   // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
24522   // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
24523   if (Cond.getOpcode() == X86ISD::SETCC &&
24524       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
24525       isNullConstant(Cond.getOperand(1).getOperand(1))) {
24526     SDValue Cmp = Cond.getOperand(1);
24527     SDValue CmpOp0 = Cmp.getOperand(0);
24528     unsigned CondCode = Cond.getConstantOperandVal(0);
24529 
24530     // Special handling for __builtin_ffs(X) - 1 pattern which looks like
24531     // (select (seteq X, 0), -1, (cttz_zero_undef X)). Disable the special
24532     // handle to keep the CMP with 0. This should be removed by
24533     // optimizeCompareInst by using the flags from the BSR/TZCNT used for the
24534     // cttz_zero_undef.
24535     auto MatchFFSMinus1 = [&](SDValue Op1, SDValue Op2) {
24536       return (Op1.getOpcode() == ISD::CTTZ_ZERO_UNDEF && Op1.hasOneUse() &&
24537               Op1.getOperand(0) == CmpOp0 && isAllOnesConstant(Op2));
24538     };
24539     if (Subtarget.hasCMov() && (VT == MVT::i32 || VT == MVT::i64) &&
24540         ((CondCode == X86::COND_NE && MatchFFSMinus1(Op1, Op2)) ||
24541          (CondCode == X86::COND_E && MatchFFSMinus1(Op2, Op1)))) {
24542       // Keep Cmp.
24543     } else if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
24544         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
24545       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
24546 
24547       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
24548       SDVTList CmpVTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
24549 
24550       // Apply further optimizations for special cases
24551       // (select (x != 0), -1, 0) -> neg & sbb
24552       // (select (x == 0), 0, -1) -> neg & sbb
24553       if (isNullConstant(Y) &&
24554           (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
24555         SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
24556         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, CmpVTs, Zero, CmpOp0);
24557         Zero = DAG.getConstant(0, DL, Op.getValueType());
24558         return DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Neg.getValue(1));
24559       }
24560 
24561       Cmp = DAG.getNode(X86ISD::SUB, DL, CmpVTs,
24562                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
24563 
24564       SDValue Zero = DAG.getConstant(0, DL, Op.getValueType());
24565       SDValue Res =   // Res = 0 or -1.
24566         DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Cmp.getValue(1));
24567 
24568       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
24569         Res = DAG.getNOT(DL, Res, Res.getValueType());
24570 
24571       return DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
24572     } else if (!Subtarget.hasCMov() && CondCode == X86::COND_E &&
24573                Cmp.getOperand(0).getOpcode() == ISD::AND &&
24574                isOneConstant(Cmp.getOperand(0).getOperand(1))) {
24575       SDValue Src1, Src2;
24576       // true if Op2 is XOR or OR operator and one of its operands
24577       // is equal to Op1
24578       // ( a , a op b) || ( b , a op b)
24579       auto isOrXorPattern = [&]() {
24580         if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
24581             (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
24582           Src1 =
24583               Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
24584           Src2 = Op1;
24585           return true;
24586         }
24587         return false;
24588       };
24589 
24590       if (isOrXorPattern()) {
24591         SDValue Neg;
24592         unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
24593         // we need mask of all zeros or ones with same size of the other
24594         // operands.
24595         if (CmpSz > VT.getSizeInBits())
24596           Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
24597         else if (CmpSz < VT.getSizeInBits())
24598           Neg = DAG.getNode(ISD::AND, DL, VT,
24599               DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
24600               DAG.getConstant(1, DL, VT));
24601         else
24602           Neg = CmpOp0;
24603         SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
24604                                    Neg); // -(and (x, 0x1))
24605         SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
24606         return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2);  // And Op y
24607       }
24608     }
24609   }
24610 
24611   // Look past (and (setcc_carry (cmp ...)), 1).
24612   if (Cond.getOpcode() == ISD::AND &&
24613       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
24614       isOneConstant(Cond.getOperand(1)))
24615     Cond = Cond.getOperand(0);
24616 
24617   // If condition flag is set by a X86ISD::CMP, then use it as the condition
24618   // setting operand in place of the X86ISD::SETCC.
24619   unsigned CondOpcode = Cond.getOpcode();
24620   if (CondOpcode == X86ISD::SETCC ||
24621       CondOpcode == X86ISD::SETCC_CARRY) {
24622     CC = Cond.getOperand(0);
24623 
24624     SDValue Cmp = Cond.getOperand(1);
24625     bool IllegalFPCMov = false;
24626     if (VT.isFloatingPoint() && !VT.isVector() &&
24627         !isScalarFPTypeInSSEReg(VT) && Subtarget.hasCMov())  // FPStack?
24628       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
24629 
24630     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
24631         Cmp.getOpcode() == X86ISD::BT) { // FIXME
24632       Cond = Cmp;
24633       AddTest = false;
24634     }
24635   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
24636              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
24637              CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
24638     SDValue Value;
24639     X86::CondCode X86Cond;
24640     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
24641 
24642     CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
24643     AddTest = false;
24644   }
24645 
24646   if (AddTest) {
24647     // Look past the truncate if the high bits are known zero.
24648     if (isTruncWithZeroHighBitsInput(Cond, DAG))
24649       Cond = Cond.getOperand(0);
24650 
24651     // We know the result of AND is compared against zero. Try to match
24652     // it to BT.
24653     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
24654       SDValue BTCC;
24655       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, BTCC)) {
24656         CC = BTCC;
24657         Cond = BT;
24658         AddTest = false;
24659       }
24660     }
24661   }
24662 
24663   if (AddTest) {
24664     CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
24665     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
24666   }
24667 
24668   // a <  b ? -1 :  0 -> RES = ~setcc_carry
24669   // a <  b ?  0 : -1 -> RES = setcc_carry
24670   // a >= b ? -1 :  0 -> RES = setcc_carry
24671   // a >= b ?  0 : -1 -> RES = ~setcc_carry
24672   if (Cond.getOpcode() == X86ISD::SUB) {
24673     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
24674 
24675     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
24676         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
24677         (isNullConstant(Op1) || isNullConstant(Op2))) {
24678       SDValue Res =
24679           DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
24680                       DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
24681       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
24682         return DAG.getNOT(DL, Res, Res.getValueType());
24683       return Res;
24684     }
24685   }
24686 
24687   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
24688   // widen the cmov and push the truncate through. This avoids introducing a new
24689   // branch during isel and doesn't add any extensions.
24690   if (Op.getValueType() == MVT::i8 &&
24691       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
24692     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
24693     if (T1.getValueType() == T2.getValueType() &&
24694         // Exclude CopyFromReg to avoid partial register stalls.
24695         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
24696       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
24697                                  CC, Cond);
24698       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
24699     }
24700   }
24701 
24702   // Or finally, promote i8 cmovs if we have CMOV,
24703   //                 or i16 cmovs if it won't prevent folding a load.
24704   // FIXME: we should not limit promotion of i8 case to only when the CMOV is
24705   //        legal, but EmitLoweredSelect() can not deal with these extensions
24706   //        being inserted between two CMOV's. (in i16 case too TBN)
24707   //        https://bugs.llvm.org/show_bug.cgi?id=40974
24708   if ((Op.getValueType() == MVT::i8 && Subtarget.hasCMov()) ||
24709       (Op.getValueType() == MVT::i16 && !X86::mayFoldLoad(Op1, Subtarget) &&
24710        !X86::mayFoldLoad(Op2, Subtarget))) {
24711     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
24712     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
24713     SDValue Ops[] = { Op2, Op1, CC, Cond };
24714     SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
24715     return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
24716   }
24717 
24718   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
24719   // condition is true.
24720   SDValue Ops[] = { Op2, Op1, CC, Cond };
24721   return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops);
24722 }
24723 
24724 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
24725                                      const X86Subtarget &Subtarget,
24726                                      SelectionDAG &DAG) {
24727   MVT VT = Op->getSimpleValueType(0);
24728   SDValue In = Op->getOperand(0);
24729   MVT InVT = In.getSimpleValueType();
24730   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
24731   MVT VTElt = VT.getVectorElementType();
24732   SDLoc dl(Op);
24733 
24734   unsigned NumElts = VT.getVectorNumElements();
24735 
24736   // Extend VT if the scalar type is i8/i16 and BWI is not supported.
24737   MVT ExtVT = VT;
24738   if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
24739     // If v16i32 is to be avoided, we'll need to split and concatenate.
24740     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
24741       return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
24742 
24743     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
24744   }
24745 
24746   // Widen to 512-bits if VLX is not supported.
24747   MVT WideVT = ExtVT;
24748   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
24749     NumElts *= 512 / ExtVT.getSizeInBits();
24750     InVT = MVT::getVectorVT(MVT::i1, NumElts);
24751     In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
24752                      In, DAG.getIntPtrConstant(0, dl));
24753     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
24754   }
24755 
24756   SDValue V;
24757   MVT WideEltVT = WideVT.getVectorElementType();
24758   if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
24759       (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
24760     V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
24761   } else {
24762     SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
24763     SDValue Zero = DAG.getConstant(0, dl, WideVT);
24764     V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
24765   }
24766 
24767   // Truncate if we had to extend i16/i8 above.
24768   if (VT != ExtVT) {
24769     WideVT = MVT::getVectorVT(VTElt, NumElts);
24770     V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
24771   }
24772 
24773   // Extract back to 128/256-bit if we widened.
24774   if (WideVT != VT)
24775     V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
24776                     DAG.getIntPtrConstant(0, dl));
24777 
24778   return V;
24779 }
24780 
24781 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
24782                                SelectionDAG &DAG) {
24783   SDValue In = Op->getOperand(0);
24784   MVT InVT = In.getSimpleValueType();
24785 
24786   if (InVT.getVectorElementType() == MVT::i1)
24787     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
24788 
24789   assert(Subtarget.hasAVX() && "Expected AVX support");
24790   return LowerAVXExtend(Op, DAG, Subtarget);
24791 }
24792 
24793 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
24794 // For sign extend this needs to handle all vector sizes and SSE4.1 and
24795 // non-SSE4.1 targets. For zero extend this should only handle inputs of
24796 // MVT::v64i8 when BWI is not supported, but AVX512 is.
24797 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
24798                                         const X86Subtarget &Subtarget,
24799                                         SelectionDAG &DAG) {
24800   SDValue In = Op->getOperand(0);
24801   MVT VT = Op->getSimpleValueType(0);
24802   MVT InVT = In.getSimpleValueType();
24803 
24804   MVT SVT = VT.getVectorElementType();
24805   MVT InSVT = InVT.getVectorElementType();
24806   assert(SVT.getFixedSizeInBits() > InSVT.getFixedSizeInBits());
24807 
24808   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
24809     return SDValue();
24810   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
24811     return SDValue();
24812   if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
24813       !(VT.is256BitVector() && Subtarget.hasAVX()) &&
24814       !(VT.is512BitVector() && Subtarget.hasAVX512()))
24815     return SDValue();
24816 
24817   SDLoc dl(Op);
24818   unsigned Opc = Op.getOpcode();
24819   unsigned NumElts = VT.getVectorNumElements();
24820 
24821   // For 256-bit vectors, we only need the lower (128-bit) half of the input.
24822   // For 512-bit vectors, we need 128-bits or 256-bits.
24823   if (InVT.getSizeInBits() > 128) {
24824     // Input needs to be at least the same number of elements as output, and
24825     // at least 128-bits.
24826     int InSize = InSVT.getSizeInBits() * NumElts;
24827     In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
24828     InVT = In.getSimpleValueType();
24829   }
24830 
24831   // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
24832   // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
24833   // need to be handled here for 256/512-bit results.
24834   if (Subtarget.hasInt256()) {
24835     assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
24836 
24837     if (InVT.getVectorNumElements() != NumElts)
24838       return DAG.getNode(Op.getOpcode(), dl, VT, In);
24839 
24840     // FIXME: Apparently we create inreg operations that could be regular
24841     // extends.
24842     unsigned ExtOpc =
24843         Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
24844                                              : ISD::ZERO_EXTEND;
24845     return DAG.getNode(ExtOpc, dl, VT, In);
24846   }
24847 
24848   // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
24849   if (Subtarget.hasAVX()) {
24850     assert(VT.is256BitVector() && "256-bit vector expected");
24851     MVT HalfVT = VT.getHalfNumVectorElementsVT();
24852     int HalfNumElts = HalfVT.getVectorNumElements();
24853 
24854     unsigned NumSrcElts = InVT.getVectorNumElements();
24855     SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
24856     for (int i = 0; i != HalfNumElts; ++i)
24857       HiMask[i] = HalfNumElts + i;
24858 
24859     SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
24860     SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
24861     Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
24862     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
24863   }
24864 
24865   // We should only get here for sign extend.
24866   assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
24867   assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
24868 
24869   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
24870   SDValue Curr = In;
24871   SDValue SignExt = Curr;
24872 
24873   // As SRAI is only available on i16/i32 types, we expand only up to i32
24874   // and handle i64 separately.
24875   if (InVT != MVT::v4i32) {
24876     MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
24877 
24878     unsigned DestWidth = DestVT.getScalarSizeInBits();
24879     unsigned Scale = DestWidth / InSVT.getSizeInBits();
24880 
24881     unsigned InNumElts = InVT.getVectorNumElements();
24882     unsigned DestElts = DestVT.getVectorNumElements();
24883 
24884     // Build a shuffle mask that takes each input element and places it in the
24885     // MSBs of the new element size.
24886     SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
24887     for (unsigned i = 0; i != DestElts; ++i)
24888       Mask[i * Scale + (Scale - 1)] = i;
24889 
24890     Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
24891     Curr = DAG.getBitcast(DestVT, Curr);
24892 
24893     unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
24894     SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
24895                           DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
24896   }
24897 
24898   if (VT == MVT::v2i64) {
24899     assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT");
24900     SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
24901     SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
24902     SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
24903     SignExt = DAG.getBitcast(VT, SignExt);
24904   }
24905 
24906   return SignExt;
24907 }
24908 
24909 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
24910                                 SelectionDAG &DAG) {
24911   MVT VT = Op->getSimpleValueType(0);
24912   SDValue In = Op->getOperand(0);
24913   MVT InVT = In.getSimpleValueType();
24914   SDLoc dl(Op);
24915 
24916   if (InVT.getVectorElementType() == MVT::i1)
24917     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
24918 
24919   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
24920   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
24921          "Expected same number of elements");
24922   assert((VT.getVectorElementType() == MVT::i16 ||
24923           VT.getVectorElementType() == MVT::i32 ||
24924           VT.getVectorElementType() == MVT::i64) &&
24925          "Unexpected element type");
24926   assert((InVT.getVectorElementType() == MVT::i8 ||
24927           InVT.getVectorElementType() == MVT::i16 ||
24928           InVT.getVectorElementType() == MVT::i32) &&
24929          "Unexpected element type");
24930 
24931   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
24932     assert(InVT == MVT::v32i8 && "Unexpected VT!");
24933     return splitVectorIntUnary(Op, DAG);
24934   }
24935 
24936   if (Subtarget.hasInt256())
24937     return Op;
24938 
24939   // Optimize vectors in AVX mode
24940   // Sign extend  v8i16 to v8i32 and
24941   //              v4i32 to v4i64
24942   //
24943   // Divide input vector into two parts
24944   // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
24945   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
24946   // concat the vectors to original VT
24947   MVT HalfVT = VT.getHalfNumVectorElementsVT();
24948   SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
24949 
24950   unsigned NumElems = InVT.getVectorNumElements();
24951   SmallVector<int,8> ShufMask(NumElems, -1);
24952   for (unsigned i = 0; i != NumElems/2; ++i)
24953     ShufMask[i] = i + NumElems/2;
24954 
24955   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
24956   OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
24957 
24958   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
24959 }
24960 
24961 /// Change a vector store into a pair of half-size vector stores.
24962 static SDValue splitVectorStore(StoreSDNode *Store, SelectionDAG &DAG) {
24963   SDValue StoredVal = Store->getValue();
24964   assert((StoredVal.getValueType().is256BitVector() ||
24965           StoredVal.getValueType().is512BitVector()) &&
24966          "Expecting 256/512-bit op");
24967 
24968   // Splitting volatile memory ops is not allowed unless the operation was not
24969   // legal to begin with. Assume the input store is legal (this transform is
24970   // only used for targets with AVX). Note: It is possible that we have an
24971   // illegal type like v2i128, and so we could allow splitting a volatile store
24972   // in that case if that is important.
24973   if (!Store->isSimple())
24974     return SDValue();
24975 
24976   SDLoc DL(Store);
24977   SDValue Value0, Value1;
24978   std::tie(Value0, Value1) = splitVector(StoredVal, DAG, DL);
24979   unsigned HalfOffset = Value0.getValueType().getStoreSize();
24980   SDValue Ptr0 = Store->getBasePtr();
24981   SDValue Ptr1 =
24982       DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(HalfOffset), DL);
24983   SDValue Ch0 =
24984       DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
24985                    Store->getOriginalAlign(),
24986                    Store->getMemOperand()->getFlags());
24987   SDValue Ch1 = DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
24988                              Store->getPointerInfo().getWithOffset(HalfOffset),
24989                              Store->getOriginalAlign(),
24990                              Store->getMemOperand()->getFlags());
24991   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
24992 }
24993 
24994 /// Scalarize a vector store, bitcasting to TargetVT to determine the scalar
24995 /// type.
24996 static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT,
24997                                     SelectionDAG &DAG) {
24998   SDValue StoredVal = Store->getValue();
24999   assert(StoreVT.is128BitVector() &&
25000          StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op");
25001   StoredVal = DAG.getBitcast(StoreVT, StoredVal);
25002 
25003   // Splitting volatile memory ops is not allowed unless the operation was not
25004   // legal to begin with. We are assuming the input op is legal (this transform
25005   // is only used for targets with AVX).
25006   if (!Store->isSimple())
25007     return SDValue();
25008 
25009   MVT StoreSVT = StoreVT.getScalarType();
25010   unsigned NumElems = StoreVT.getVectorNumElements();
25011   unsigned ScalarSize = StoreSVT.getStoreSize();
25012 
25013   SDLoc DL(Store);
25014   SmallVector<SDValue, 4> Stores;
25015   for (unsigned i = 0; i != NumElems; ++i) {
25016     unsigned Offset = i * ScalarSize;
25017     SDValue Ptr = DAG.getMemBasePlusOffset(Store->getBasePtr(),
25018                                            TypeSize::Fixed(Offset), DL);
25019     SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreSVT, StoredVal,
25020                               DAG.getIntPtrConstant(i, DL));
25021     SDValue Ch = DAG.getStore(Store->getChain(), DL, Scl, Ptr,
25022                               Store->getPointerInfo().getWithOffset(Offset),
25023                               Store->getOriginalAlign(),
25024                               Store->getMemOperand()->getFlags());
25025     Stores.push_back(Ch);
25026   }
25027   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
25028 }
25029 
25030 static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
25031                           SelectionDAG &DAG) {
25032   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
25033   SDLoc dl(St);
25034   SDValue StoredVal = St->getValue();
25035 
25036   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
25037   if (StoredVal.getValueType().isVector() &&
25038       StoredVal.getValueType().getVectorElementType() == MVT::i1) {
25039     unsigned NumElts = StoredVal.getValueType().getVectorNumElements();
25040     assert(NumElts <= 8 && "Unexpected VT");
25041     assert(!St->isTruncatingStore() && "Expected non-truncating store");
25042     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
25043            "Expected AVX512F without AVX512DQI");
25044 
25045     // We must pad with zeros to ensure we store zeroes to any unused bits.
25046     StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
25047                             DAG.getUNDEF(MVT::v16i1), StoredVal,
25048                             DAG.getIntPtrConstant(0, dl));
25049     StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
25050     StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
25051     // Make sure we store zeros in the extra bits.
25052     if (NumElts < 8)
25053       StoredVal = DAG.getZeroExtendInReg(
25054           StoredVal, dl, EVT::getIntegerVT(*DAG.getContext(), NumElts));
25055 
25056     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
25057                         St->getPointerInfo(), St->getOriginalAlign(),
25058                         St->getMemOperand()->getFlags());
25059   }
25060 
25061   if (St->isTruncatingStore())
25062     return SDValue();
25063 
25064   // If this is a 256-bit store of concatenated ops, we are better off splitting
25065   // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
25066   // and each half can execute independently. Some cores would split the op into
25067   // halves anyway, so the concat (vinsertf128) is purely an extra op.
25068   MVT StoreVT = StoredVal.getSimpleValueType();
25069   if (StoreVT.is256BitVector() ||
25070       ((StoreVT == MVT::v32i16 || StoreVT == MVT::v64i8) &&
25071        !Subtarget.hasBWI())) {
25072     SmallVector<SDValue, 4> CatOps;
25073     if (StoredVal.hasOneUse() && collectConcatOps(StoredVal.getNode(), CatOps))
25074       return splitVectorStore(St, DAG);
25075     return SDValue();
25076   }
25077 
25078   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25079   assert(StoreVT.isVector() && StoreVT.getSizeInBits() == 64 &&
25080          "Unexpected VT");
25081   assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==
25082              TargetLowering::TypeWidenVector && "Unexpected type action!");
25083 
25084   EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
25085   StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
25086                           DAG.getUNDEF(StoreVT));
25087 
25088   if (Subtarget.hasSSE2()) {
25089     // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
25090     // and store it.
25091     MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
25092     MVT CastVT = MVT::getVectorVT(StVT, 2);
25093     StoredVal = DAG.getBitcast(CastVT, StoredVal);
25094     StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
25095                             DAG.getIntPtrConstant(0, dl));
25096 
25097     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
25098                         St->getPointerInfo(), St->getOriginalAlign(),
25099                         St->getMemOperand()->getFlags());
25100   }
25101   assert(Subtarget.hasSSE1() && "Expected SSE");
25102   SDVTList Tys = DAG.getVTList(MVT::Other);
25103   SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
25104   return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
25105                                  St->getMemOperand());
25106 }
25107 
25108 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
25109 // may emit an illegal shuffle but the expansion is still better than scalar
25110 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
25111 // we'll emit a shuffle and a arithmetic shift.
25112 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
25113 // TODO: It is possible to support ZExt by zeroing the undef values during
25114 // the shuffle phase or after the shuffle.
25115 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
25116                                  SelectionDAG &DAG) {
25117   MVT RegVT = Op.getSimpleValueType();
25118   assert(RegVT.isVector() && "We only custom lower vector loads.");
25119   assert(RegVT.isInteger() &&
25120          "We only custom lower integer vector loads.");
25121 
25122   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
25123   SDLoc dl(Ld);
25124 
25125   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
25126   if (RegVT.getVectorElementType() == MVT::i1) {
25127     assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load");
25128     assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
25129     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
25130            "Expected AVX512F without AVX512DQI");
25131 
25132     SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
25133                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
25134                                 Ld->getMemOperand()->getFlags());
25135 
25136     // Replace chain users with the new chain.
25137     assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
25138 
25139     SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
25140     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
25141                       DAG.getBitcast(MVT::v16i1, Val),
25142                       DAG.getIntPtrConstant(0, dl));
25143     return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
25144   }
25145 
25146   return SDValue();
25147 }
25148 
25149 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
25150 /// each of which has no other use apart from the AND / OR.
25151 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
25152   Opc = Op.getOpcode();
25153   if (Opc != ISD::OR && Opc != ISD::AND)
25154     return false;
25155   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
25156           Op.getOperand(0).hasOneUse() &&
25157           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
25158           Op.getOperand(1).hasOneUse());
25159 }
25160 
25161 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
25162   SDValue Chain = Op.getOperand(0);
25163   SDValue Cond  = Op.getOperand(1);
25164   SDValue Dest  = Op.getOperand(2);
25165   SDLoc dl(Op);
25166 
25167   if (Cond.getOpcode() == ISD::SETCC &&
25168       Cond.getOperand(0).getValueType() != MVT::f128) {
25169     SDValue LHS = Cond.getOperand(0);
25170     SDValue RHS = Cond.getOperand(1);
25171     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
25172 
25173     // Special case for
25174     // setcc([su]{add,sub,mul}o == 0)
25175     // setcc([su]{add,sub,mul}o != 1)
25176     if (ISD::isOverflowIntrOpRes(LHS) &&
25177         (CC == ISD::SETEQ || CC == ISD::SETNE) &&
25178         (isNullConstant(RHS) || isOneConstant(RHS))) {
25179       SDValue Value, Overflow;
25180       X86::CondCode X86Cond;
25181       std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, LHS.getValue(0), DAG);
25182 
25183       if ((CC == ISD::SETEQ) == isNullConstant(RHS))
25184         X86Cond = X86::GetOppositeBranchCondition(X86Cond);
25185 
25186       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25187       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25188                          Overflow);
25189     }
25190 
25191     if (LHS.getSimpleValueType().isInteger()) {
25192       SDValue CCVal;
25193       SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, CC, SDLoc(Cond), DAG, CCVal);
25194       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25195                          EFLAGS);
25196     }
25197 
25198     if (CC == ISD::SETOEQ) {
25199       // For FCMP_OEQ, we can emit
25200       // two branches instead of an explicit AND instruction with a
25201       // separate test. However, we only do this if this block doesn't
25202       // have a fall-through edge, because this requires an explicit
25203       // jmp when the condition is false.
25204       if (Op.getNode()->hasOneUse()) {
25205         SDNode *User = *Op.getNode()->use_begin();
25206         // Look for an unconditional branch following this conditional branch.
25207         // We need this because we need to reverse the successors in order
25208         // to implement FCMP_OEQ.
25209         if (User->getOpcode() == ISD::BR) {
25210           SDValue FalseBB = User->getOperand(1);
25211           SDNode *NewBR =
25212             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
25213           assert(NewBR == User);
25214           (void)NewBR;
25215           Dest = FalseBB;
25216 
25217           SDValue Cmp =
25218               DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25219           SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
25220           Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest,
25221                               CCVal, Cmp);
25222           CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
25223           return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25224                              Cmp);
25225         }
25226       }
25227     } else if (CC == ISD::SETUNE) {
25228       // For FCMP_UNE, we can emit
25229       // two branches instead of an explicit OR instruction with a
25230       // separate test.
25231       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25232       SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
25233       Chain =
25234           DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Cmp);
25235       CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
25236       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25237                          Cmp);
25238     } else {
25239       X86::CondCode X86Cond =
25240           TranslateX86CC(CC, dl, /*IsFP*/ true, LHS, RHS, DAG);
25241       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25242       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25243       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25244                          Cmp);
25245     }
25246   }
25247 
25248   if (ISD::isOverflowIntrOpRes(Cond)) {
25249     SDValue Value, Overflow;
25250     X86::CondCode X86Cond;
25251     std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
25252 
25253     SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25254     return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25255                        Overflow);
25256   }
25257 
25258   // Look past the truncate if the high bits are known zero.
25259   if (isTruncWithZeroHighBitsInput(Cond, DAG))
25260     Cond = Cond.getOperand(0);
25261 
25262   EVT CondVT = Cond.getValueType();
25263 
25264   // Add an AND with 1 if we don't already have one.
25265   if (!(Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1))))
25266     Cond =
25267         DAG.getNode(ISD::AND, dl, CondVT, Cond, DAG.getConstant(1, dl, CondVT));
25268 
25269   SDValue LHS = Cond;
25270   SDValue RHS = DAG.getConstant(0, dl, CondVT);
25271 
25272   SDValue CCVal;
25273   SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, ISD::SETNE, dl, DAG, CCVal);
25274   return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25275                      EFLAGS);
25276 }
25277 
25278 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
25279 // Calls to _alloca are needed to probe the stack when allocating more than 4k
25280 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
25281 // that the guard pages used by the OS virtual memory manager are allocated in
25282 // correct sequence.
25283 SDValue
25284 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
25285                                            SelectionDAG &DAG) const {
25286   MachineFunction &MF = DAG.getMachineFunction();
25287   bool SplitStack = MF.shouldSplitStack();
25288   bool EmitStackProbeCall = hasStackProbeSymbol(MF);
25289   bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
25290                SplitStack || EmitStackProbeCall;
25291   SDLoc dl(Op);
25292 
25293   // Get the inputs.
25294   SDNode *Node = Op.getNode();
25295   SDValue Chain = Op.getOperand(0);
25296   SDValue Size  = Op.getOperand(1);
25297   MaybeAlign Alignment(Op.getConstantOperandVal(2));
25298   EVT VT = Node->getValueType(0);
25299 
25300   // Chain the dynamic stack allocation so that it doesn't modify the stack
25301   // pointer when other instructions are using the stack.
25302   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
25303 
25304   bool Is64Bit = Subtarget.is64Bit();
25305   MVT SPTy = getPointerTy(DAG.getDataLayout());
25306 
25307   SDValue Result;
25308   if (!Lower) {
25309     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25310     Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
25311     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
25312                     " not tell us which reg is the stack pointer!");
25313 
25314     const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
25315     const Align StackAlign = TFI.getStackAlign();
25316     if (hasInlineStackProbe(MF)) {
25317       MachineRegisterInfo &MRI = MF.getRegInfo();
25318 
25319       const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
25320       Register Vreg = MRI.createVirtualRegister(AddrRegClass);
25321       Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
25322       Result = DAG.getNode(X86ISD::PROBED_ALLOCA, dl, SPTy, Chain,
25323                            DAG.getRegister(Vreg, SPTy));
25324     } else {
25325       SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
25326       Chain = SP.getValue(1);
25327       Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
25328     }
25329     if (Alignment && *Alignment > StackAlign)
25330       Result =
25331           DAG.getNode(ISD::AND, dl, VT, Result,
25332                       DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
25333     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
25334   } else if (SplitStack) {
25335     MachineRegisterInfo &MRI = MF.getRegInfo();
25336 
25337     if (Is64Bit) {
25338       // The 64 bit implementation of segmented stacks needs to clobber both r10
25339       // r11. This makes it impossible to use it along with nested parameters.
25340       const Function &F = MF.getFunction();
25341       for (const auto &A : F.args()) {
25342         if (A.hasNestAttr())
25343           report_fatal_error("Cannot use segmented stacks with functions that "
25344                              "have nested arguments.");
25345       }
25346     }
25347 
25348     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
25349     Register Vreg = MRI.createVirtualRegister(AddrRegClass);
25350     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
25351     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
25352                                 DAG.getRegister(Vreg, SPTy));
25353   } else {
25354     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
25355     Chain = DAG.getNode(X86ISD::DYN_ALLOCA, dl, NodeTys, Chain, Size);
25356     MF.getInfo<X86MachineFunctionInfo>()->setHasDynAlloca(true);
25357 
25358     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25359     Register SPReg = RegInfo->getStackRegister();
25360     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
25361     Chain = SP.getValue(1);
25362 
25363     if (Alignment) {
25364       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
25365                        DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
25366       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
25367     }
25368 
25369     Result = SP;
25370   }
25371 
25372   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
25373                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
25374 
25375   SDValue Ops[2] = {Result, Chain};
25376   return DAG.getMergeValues(Ops, dl);
25377 }
25378 
25379 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
25380   MachineFunction &MF = DAG.getMachineFunction();
25381   auto PtrVT = getPointerTy(MF.getDataLayout());
25382   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
25383 
25384   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
25385   SDLoc DL(Op);
25386 
25387   if (!Subtarget.is64Bit() ||
25388       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
25389     // vastart just stores the address of the VarArgsFrameIndex slot into the
25390     // memory location argument.
25391     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
25392     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
25393                         MachinePointerInfo(SV));
25394   }
25395 
25396   // __va_list_tag:
25397   //   gp_offset         (0 - 6 * 8)
25398   //   fp_offset         (48 - 48 + 8 * 16)
25399   //   overflow_arg_area (point to parameters coming in memory).
25400   //   reg_save_area
25401   SmallVector<SDValue, 8> MemOps;
25402   SDValue FIN = Op.getOperand(1);
25403   // Store gp_offset
25404   SDValue Store = DAG.getStore(
25405       Op.getOperand(0), DL,
25406       DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
25407       MachinePointerInfo(SV));
25408   MemOps.push_back(Store);
25409 
25410   // Store fp_offset
25411   FIN = DAG.getMemBasePlusOffset(FIN, TypeSize::Fixed(4), DL);
25412   Store = DAG.getStore(
25413       Op.getOperand(0), DL,
25414       DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
25415       MachinePointerInfo(SV, 4));
25416   MemOps.push_back(Store);
25417 
25418   // Store ptr to overflow_arg_area
25419   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
25420   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
25421   Store =
25422       DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
25423   MemOps.push_back(Store);
25424 
25425   // Store ptr to reg_save_area.
25426   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
25427       Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
25428   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
25429   Store = DAG.getStore(
25430       Op.getOperand(0), DL, RSFIN, FIN,
25431       MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
25432   MemOps.push_back(Store);
25433   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
25434 }
25435 
25436 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
25437   assert(Subtarget.is64Bit() &&
25438          "LowerVAARG only handles 64-bit va_arg!");
25439   assert(Op.getNumOperands() == 4);
25440 
25441   MachineFunction &MF = DAG.getMachineFunction();
25442   if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
25443     // The Win64 ABI uses char* instead of a structure.
25444     return DAG.expandVAArg(Op.getNode());
25445 
25446   SDValue Chain = Op.getOperand(0);
25447   SDValue SrcPtr = Op.getOperand(1);
25448   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
25449   unsigned Align = Op.getConstantOperandVal(3);
25450   SDLoc dl(Op);
25451 
25452   EVT ArgVT = Op.getNode()->getValueType(0);
25453   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
25454   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
25455   uint8_t ArgMode;
25456 
25457   // Decide which area this value should be read from.
25458   // TODO: Implement the AMD64 ABI in its entirety. This simple
25459   // selection mechanism works only for the basic types.
25460   assert(ArgVT != MVT::f80 && "va_arg for f80 not yet implemented");
25461   if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
25462     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
25463   } else {
25464     assert(ArgVT.isInteger() && ArgSize <= 32 /*bytes*/ &&
25465            "Unhandled argument type in LowerVAARG");
25466     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
25467   }
25468 
25469   if (ArgMode == 2) {
25470     // Make sure using fp_offset makes sense.
25471     assert(!Subtarget.useSoftFloat() &&
25472            !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
25473            Subtarget.hasSSE1());
25474   }
25475 
25476   // Insert VAARG node into the DAG
25477   // VAARG returns two values: Variable Argument Address, Chain
25478   SDValue InstOps[] = {Chain, SrcPtr,
25479                        DAG.getTargetConstant(ArgSize, dl, MVT::i32),
25480                        DAG.getTargetConstant(ArgMode, dl, MVT::i8),
25481                        DAG.getTargetConstant(Align, dl, MVT::i32)};
25482   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
25483   SDValue VAARG = DAG.getMemIntrinsicNode(
25484       Subtarget.isTarget64BitLP64() ? X86ISD::VAARG_64 : X86ISD::VAARG_X32, dl,
25485       VTs, InstOps, MVT::i64, MachinePointerInfo(SV),
25486       /*Alignment=*/None,
25487       MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
25488   Chain = VAARG.getValue(1);
25489 
25490   // Load the next argument and return it
25491   return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
25492 }
25493 
25494 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
25495                            SelectionDAG &DAG) {
25496   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
25497   // where a va_list is still an i8*.
25498   assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
25499   if (Subtarget.isCallingConvWin64(
25500         DAG.getMachineFunction().getFunction().getCallingConv()))
25501     // Probably a Win64 va_copy.
25502     return DAG.expandVACopy(Op.getNode());
25503 
25504   SDValue Chain = Op.getOperand(0);
25505   SDValue DstPtr = Op.getOperand(1);
25506   SDValue SrcPtr = Op.getOperand(2);
25507   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
25508   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
25509   SDLoc DL(Op);
25510 
25511   return DAG.getMemcpy(
25512       Chain, DL, DstPtr, SrcPtr,
25513       DAG.getIntPtrConstant(Subtarget.isTarget64BitLP64() ? 24 : 16, DL),
25514       Align(Subtarget.isTarget64BitLP64() ? 8 : 4), /*isVolatile*/ false, false,
25515       false, MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
25516 }
25517 
25518 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
25519 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
25520   switch (Opc) {
25521   case ISD::SHL:
25522   case X86ISD::VSHL:
25523   case X86ISD::VSHLI:
25524     return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
25525   case ISD::SRL:
25526   case X86ISD::VSRL:
25527   case X86ISD::VSRLI:
25528     return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
25529   case ISD::SRA:
25530   case X86ISD::VSRA:
25531   case X86ISD::VSRAI:
25532     return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
25533   }
25534   llvm_unreachable("Unknown target vector shift node");
25535 }
25536 
25537 /// Handle vector element shifts where the shift amount is a constant.
25538 /// Takes immediate version of shift as input.
25539 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
25540                                           SDValue SrcOp, uint64_t ShiftAmt,
25541                                           SelectionDAG &DAG) {
25542   MVT ElementType = VT.getVectorElementType();
25543 
25544   // Bitcast the source vector to the output type, this is mainly necessary for
25545   // vXi8/vXi64 shifts.
25546   if (VT != SrcOp.getSimpleValueType())
25547     SrcOp = DAG.getBitcast(VT, SrcOp);
25548 
25549   // Fold this packed shift into its first operand if ShiftAmt is 0.
25550   if (ShiftAmt == 0)
25551     return SrcOp;
25552 
25553   // Check for ShiftAmt >= element width
25554   if (ShiftAmt >= ElementType.getSizeInBits()) {
25555     if (Opc == X86ISD::VSRAI)
25556       ShiftAmt = ElementType.getSizeInBits() - 1;
25557     else
25558       return DAG.getConstant(0, dl, VT);
25559   }
25560 
25561   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
25562          && "Unknown target vector shift-by-constant node");
25563 
25564   // Fold this packed vector shift into a build vector if SrcOp is a
25565   // vector of Constants or UNDEFs.
25566   if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
25567     SmallVector<SDValue, 8> Elts;
25568     unsigned NumElts = SrcOp->getNumOperands();
25569 
25570     switch (Opc) {
25571     default: llvm_unreachable("Unknown opcode!");
25572     case X86ISD::VSHLI:
25573       for (unsigned i = 0; i != NumElts; ++i) {
25574         SDValue CurrentOp = SrcOp->getOperand(i);
25575         if (CurrentOp->isUndef()) {
25576           // Must produce 0s in the correct bits.
25577           Elts.push_back(DAG.getConstant(0, dl, ElementType));
25578           continue;
25579         }
25580         auto *ND = cast<ConstantSDNode>(CurrentOp);
25581         const APInt &C = ND->getAPIntValue();
25582         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
25583       }
25584       break;
25585     case X86ISD::VSRLI:
25586       for (unsigned i = 0; i != NumElts; ++i) {
25587         SDValue CurrentOp = SrcOp->getOperand(i);
25588         if (CurrentOp->isUndef()) {
25589           // Must produce 0s in the correct bits.
25590           Elts.push_back(DAG.getConstant(0, dl, ElementType));
25591           continue;
25592         }
25593         auto *ND = cast<ConstantSDNode>(CurrentOp);
25594         const APInt &C = ND->getAPIntValue();
25595         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
25596       }
25597       break;
25598     case X86ISD::VSRAI:
25599       for (unsigned i = 0; i != NumElts; ++i) {
25600         SDValue CurrentOp = SrcOp->getOperand(i);
25601         if (CurrentOp->isUndef()) {
25602           // All shifted in bits must be the same so use 0.
25603           Elts.push_back(DAG.getConstant(0, dl, ElementType));
25604           continue;
25605         }
25606         auto *ND = cast<ConstantSDNode>(CurrentOp);
25607         const APInt &C = ND->getAPIntValue();
25608         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
25609       }
25610       break;
25611     }
25612 
25613     return DAG.getBuildVector(VT, dl, Elts);
25614   }
25615 
25616   return DAG.getNode(Opc, dl, VT, SrcOp,
25617                      DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
25618 }
25619 
25620 /// Handle vector element shifts where the shift amount may or may not be a
25621 /// constant. Takes immediate version of shift as input.
25622 /// TODO: Replace with vector + (splat) idx to avoid extract_element nodes.
25623 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
25624                                    SDValue SrcOp, SDValue ShAmt,
25625                                    const X86Subtarget &Subtarget,
25626                                    SelectionDAG &DAG) {
25627   MVT SVT = ShAmt.getSimpleValueType();
25628   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
25629 
25630   // Change opcode to non-immediate version.
25631   Opc = getTargetVShiftUniformOpcode(Opc, true);
25632 
25633   // Need to build a vector containing shift amount.
25634   // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
25635   // +====================+============+=======================================+
25636   // | ShAmt is           | HasSSE4.1? | Construct ShAmt vector as             |
25637   // +====================+============+=======================================+
25638   // | i64                | Yes, No    | Use ShAmt as lowest elt               |
25639   // | i32                | Yes        | zero-extend in-reg                    |
25640   // | (i32 zext(i16/i8)) | Yes        | zero-extend in-reg                    |
25641   // | (i32 zext(i16/i8)) | No         | byte-shift-in-reg                     |
25642   // | i16/i32            | No         | v4i32 build_vector(ShAmt, 0, ud, ud)) |
25643   // +====================+============+=======================================+
25644 
25645   if (SVT == MVT::i64)
25646     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v2i64, ShAmt);
25647   else if (ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
25648            ShAmt.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25649            (ShAmt.getOperand(0).getSimpleValueType() == MVT::i16 ||
25650             ShAmt.getOperand(0).getSimpleValueType() == MVT::i8)) {
25651     ShAmt = ShAmt.getOperand(0);
25652     MVT AmtTy = ShAmt.getSimpleValueType() == MVT::i8 ? MVT::v16i8 : MVT::v8i16;
25653     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), AmtTy, ShAmt);
25654     if (Subtarget.hasSSE41())
25655       ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
25656                           MVT::v2i64, ShAmt);
25657     else {
25658       SDValue ByteShift = DAG.getTargetConstant(
25659           (128 - AmtTy.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
25660       ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
25661       ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
25662                           ByteShift);
25663       ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
25664                           ByteShift);
25665     }
25666   } else if (Subtarget.hasSSE41() &&
25667              ShAmt.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25668     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v4i32, ShAmt);
25669     ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
25670                         MVT::v2i64, ShAmt);
25671   } else {
25672     SDValue ShOps[4] = {ShAmt, DAG.getConstant(0, dl, SVT), DAG.getUNDEF(SVT),
25673                         DAG.getUNDEF(SVT)};
25674     ShAmt = DAG.getBuildVector(MVT::v4i32, dl, ShOps);
25675   }
25676 
25677   // The return type has to be a 128-bit type with the same element
25678   // type as the input type.
25679   MVT EltVT = VT.getVectorElementType();
25680   MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
25681 
25682   ShAmt = DAG.getBitcast(ShVT, ShAmt);
25683   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
25684 }
25685 
25686 /// Return Mask with the necessary casting or extending
25687 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
25688 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
25689                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
25690                            const SDLoc &dl) {
25691 
25692   if (isAllOnesConstant(Mask))
25693     return DAG.getConstant(1, dl, MaskVT);
25694   if (X86::isZeroNode(Mask))
25695     return DAG.getConstant(0, dl, MaskVT);
25696 
25697   assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
25698 
25699   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
25700     assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
25701     assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
25702     // In case 32bit mode, bitcast i64 is illegal, extend/split it.
25703     SDValue Lo, Hi;
25704     Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
25705                         DAG.getConstant(0, dl, MVT::i32));
25706     Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
25707                         DAG.getConstant(1, dl, MVT::i32));
25708 
25709     Lo = DAG.getBitcast(MVT::v32i1, Lo);
25710     Hi = DAG.getBitcast(MVT::v32i1, Hi);
25711 
25712     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
25713   } else {
25714     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
25715                                      Mask.getSimpleValueType().getSizeInBits());
25716     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
25717     // are extracted by EXTRACT_SUBVECTOR.
25718     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
25719                        DAG.getBitcast(BitcastVT, Mask),
25720                        DAG.getIntPtrConstant(0, dl));
25721   }
25722 }
25723 
25724 /// Return (and \p Op, \p Mask) for compare instructions or
25725 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
25726 /// necessary casting or extending for \p Mask when lowering masking intrinsics
25727 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
25728                   SDValue PreservedSrc,
25729                   const X86Subtarget &Subtarget,
25730                   SelectionDAG &DAG) {
25731   MVT VT = Op.getSimpleValueType();
25732   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
25733   unsigned OpcodeSelect = ISD::VSELECT;
25734   SDLoc dl(Op);
25735 
25736   if (isAllOnesConstant(Mask))
25737     return Op;
25738 
25739   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25740 
25741   if (PreservedSrc.isUndef())
25742     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
25743   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
25744 }
25745 
25746 /// Creates an SDNode for a predicated scalar operation.
25747 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
25748 /// The mask is coming as MVT::i8 and it should be transformed
25749 /// to MVT::v1i1 while lowering masking intrinsics.
25750 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
25751 /// "X86select" instead of "vselect". We just can't create the "vselect" node
25752 /// for a scalar instruction.
25753 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
25754                                     SDValue PreservedSrc,
25755                                     const X86Subtarget &Subtarget,
25756                                     SelectionDAG &DAG) {
25757 
25758   if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
25759     if (MaskConst->getZExtValue() & 0x1)
25760       return Op;
25761 
25762   MVT VT = Op.getSimpleValueType();
25763   SDLoc dl(Op);
25764 
25765   assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
25766   SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
25767                               DAG.getBitcast(MVT::v8i1, Mask),
25768                               DAG.getIntPtrConstant(0, dl));
25769   if (Op.getOpcode() == X86ISD::FSETCCM ||
25770       Op.getOpcode() == X86ISD::FSETCCM_SAE ||
25771       Op.getOpcode() == X86ISD::VFPCLASSS)
25772     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
25773 
25774   if (PreservedSrc.isUndef())
25775     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
25776   return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
25777 }
25778 
25779 static int getSEHRegistrationNodeSize(const Function *Fn) {
25780   if (!Fn->hasPersonalityFn())
25781     report_fatal_error(
25782         "querying registration node size for function without personality");
25783   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
25784   // WinEHStatePass for the full struct definition.
25785   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
25786   case EHPersonality::MSVC_X86SEH: return 24;
25787   case EHPersonality::MSVC_CXX: return 16;
25788   default: break;
25789   }
25790   report_fatal_error(
25791       "can only recover FP for 32-bit MSVC EH personality functions");
25792 }
25793 
25794 /// When the MSVC runtime transfers control to us, either to an outlined
25795 /// function or when returning to a parent frame after catching an exception, we
25796 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
25797 /// Here's the math:
25798 ///   RegNodeBase = EntryEBP - RegNodeSize
25799 ///   ParentFP = RegNodeBase - ParentFrameOffset
25800 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
25801 /// subtracting the offset (negative on x86) takes us back to the parent FP.
25802 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
25803                                    SDValue EntryEBP) {
25804   MachineFunction &MF = DAG.getMachineFunction();
25805   SDLoc dl;
25806 
25807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25808   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
25809 
25810   // It's possible that the parent function no longer has a personality function
25811   // if the exceptional code was optimized away, in which case we just return
25812   // the incoming EBP.
25813   if (!Fn->hasPersonalityFn())
25814     return EntryEBP;
25815 
25816   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
25817   // registration, or the .set_setframe offset.
25818   MCSymbol *OffsetSym =
25819       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
25820           GlobalValue::dropLLVMManglingEscape(Fn->getName()));
25821   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
25822   SDValue ParentFrameOffset =
25823       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
25824 
25825   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
25826   // prologue to RBP in the parent function.
25827   const X86Subtarget &Subtarget =
25828       static_cast<const X86Subtarget &>(DAG.getSubtarget());
25829   if (Subtarget.is64Bit())
25830     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
25831 
25832   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
25833   // RegNodeBase = EntryEBP - RegNodeSize
25834   // ParentFP = RegNodeBase - ParentFrameOffset
25835   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
25836                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
25837   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
25838 }
25839 
25840 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
25841                                                    SelectionDAG &DAG) const {
25842   // Helper to detect if the operand is CUR_DIRECTION rounding mode.
25843   auto isRoundModeCurDirection = [](SDValue Rnd) {
25844     if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
25845       return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
25846 
25847     return false;
25848   };
25849   auto isRoundModeSAE = [](SDValue Rnd) {
25850     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
25851       unsigned RC = C->getZExtValue();
25852       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
25853         // Clear the NO_EXC bit and check remaining bits.
25854         RC ^= X86::STATIC_ROUNDING::NO_EXC;
25855         // As a convenience we allow no other bits or explicitly
25856         // current direction.
25857         return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
25858       }
25859     }
25860 
25861     return false;
25862   };
25863   auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
25864     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
25865       RC = C->getZExtValue();
25866       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
25867         // Clear the NO_EXC bit and check remaining bits.
25868         RC ^= X86::STATIC_ROUNDING::NO_EXC;
25869         return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
25870                RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
25871                RC == X86::STATIC_ROUNDING::TO_POS_INF ||
25872                RC == X86::STATIC_ROUNDING::TO_ZERO;
25873       }
25874     }
25875 
25876     return false;
25877   };
25878 
25879   SDLoc dl(Op);
25880   unsigned IntNo = Op.getConstantOperandVal(0);
25881   MVT VT = Op.getSimpleValueType();
25882   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
25883 
25884   // Propagate flags from original node to transformed node(s).
25885   SelectionDAG::FlagInserter FlagsInserter(DAG, Op->getFlags());
25886 
25887   if (IntrData) {
25888     switch(IntrData->Type) {
25889     case INTR_TYPE_1OP: {
25890       // We specify 2 possible opcodes for intrinsics with rounding modes.
25891       // First, we check if the intrinsic may have non-default rounding mode,
25892       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25893       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25894       if (IntrWithRoundingModeOpcode != 0) {
25895         SDValue Rnd = Op.getOperand(2);
25896         unsigned RC = 0;
25897         if (isRoundModeSAEToX(Rnd, RC))
25898           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25899                              Op.getOperand(1),
25900                              DAG.getTargetConstant(RC, dl, MVT::i32));
25901         if (!isRoundModeCurDirection(Rnd))
25902           return SDValue();
25903       }
25904       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25905                          Op.getOperand(1));
25906     }
25907     case INTR_TYPE_1OP_SAE: {
25908       SDValue Sae = Op.getOperand(2);
25909 
25910       unsigned Opc;
25911       if (isRoundModeCurDirection(Sae))
25912         Opc = IntrData->Opc0;
25913       else if (isRoundModeSAE(Sae))
25914         Opc = IntrData->Opc1;
25915       else
25916         return SDValue();
25917 
25918       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
25919     }
25920     case INTR_TYPE_2OP: {
25921       SDValue Src2 = Op.getOperand(2);
25922 
25923       // We specify 2 possible opcodes for intrinsics with rounding modes.
25924       // First, we check if the intrinsic may have non-default rounding mode,
25925       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25926       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25927       if (IntrWithRoundingModeOpcode != 0) {
25928         SDValue Rnd = Op.getOperand(3);
25929         unsigned RC = 0;
25930         if (isRoundModeSAEToX(Rnd, RC))
25931           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25932                              Op.getOperand(1), Src2,
25933                              DAG.getTargetConstant(RC, dl, MVT::i32));
25934         if (!isRoundModeCurDirection(Rnd))
25935           return SDValue();
25936       }
25937 
25938       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25939                          Op.getOperand(1), Src2);
25940     }
25941     case INTR_TYPE_2OP_SAE: {
25942       SDValue Sae = Op.getOperand(3);
25943 
25944       unsigned Opc;
25945       if (isRoundModeCurDirection(Sae))
25946         Opc = IntrData->Opc0;
25947       else if (isRoundModeSAE(Sae))
25948         Opc = IntrData->Opc1;
25949       else
25950         return SDValue();
25951 
25952       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
25953                          Op.getOperand(2));
25954     }
25955     case INTR_TYPE_3OP:
25956     case INTR_TYPE_3OP_IMM8: {
25957       SDValue Src1 = Op.getOperand(1);
25958       SDValue Src2 = Op.getOperand(2);
25959       SDValue Src3 = Op.getOperand(3);
25960 
25961       if (IntrData->Type == INTR_TYPE_3OP_IMM8 &&
25962           Src3.getValueType() != MVT::i8) {
25963         Src3 = DAG.getTargetConstant(
25964             cast<ConstantSDNode>(Src3)->getZExtValue() & 0xff, dl, MVT::i8);
25965       }
25966 
25967       // We specify 2 possible opcodes for intrinsics with rounding modes.
25968       // First, we check if the intrinsic may have non-default rounding mode,
25969       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25970       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25971       if (IntrWithRoundingModeOpcode != 0) {
25972         SDValue Rnd = Op.getOperand(4);
25973         unsigned RC = 0;
25974         if (isRoundModeSAEToX(Rnd, RC))
25975           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25976                              Src1, Src2, Src3,
25977                              DAG.getTargetConstant(RC, dl, MVT::i32));
25978         if (!isRoundModeCurDirection(Rnd))
25979           return SDValue();
25980       }
25981 
25982       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25983                          {Src1, Src2, Src3});
25984     }
25985     case INTR_TYPE_4OP_IMM8: {
25986       assert(Op.getOperand(4)->getOpcode() == ISD::TargetConstant);
25987       SDValue Src4 = Op.getOperand(4);
25988       if (Src4.getValueType() != MVT::i8) {
25989         Src4 = DAG.getTargetConstant(
25990             cast<ConstantSDNode>(Src4)->getZExtValue() & 0xff, dl, MVT::i8);
25991       }
25992 
25993       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25994                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
25995                          Src4);
25996     }
25997     case INTR_TYPE_1OP_MASK: {
25998       SDValue Src = Op.getOperand(1);
25999       SDValue PassThru = Op.getOperand(2);
26000       SDValue Mask = Op.getOperand(3);
26001       // We add rounding mode to the Node when
26002       //   - RC Opcode is specified and
26003       //   - RC is not "current direction".
26004       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
26005       if (IntrWithRoundingModeOpcode != 0) {
26006         SDValue Rnd = Op.getOperand(4);
26007         unsigned RC = 0;
26008         if (isRoundModeSAEToX(Rnd, RC))
26009           return getVectorMaskingNode(
26010               DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
26011                           Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
26012               Mask, PassThru, Subtarget, DAG);
26013         if (!isRoundModeCurDirection(Rnd))
26014           return SDValue();
26015       }
26016       return getVectorMaskingNode(
26017           DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
26018           Subtarget, DAG);
26019     }
26020     case INTR_TYPE_1OP_MASK_SAE: {
26021       SDValue Src = Op.getOperand(1);
26022       SDValue PassThru = Op.getOperand(2);
26023       SDValue Mask = Op.getOperand(3);
26024       SDValue Rnd = Op.getOperand(4);
26025 
26026       unsigned Opc;
26027       if (isRoundModeCurDirection(Rnd))
26028         Opc = IntrData->Opc0;
26029       else if (isRoundModeSAE(Rnd))
26030         Opc = IntrData->Opc1;
26031       else
26032         return SDValue();
26033 
26034       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
26035                                   Subtarget, DAG);
26036     }
26037     case INTR_TYPE_SCALAR_MASK: {
26038       SDValue Src1 = Op.getOperand(1);
26039       SDValue Src2 = Op.getOperand(2);
26040       SDValue passThru = Op.getOperand(3);
26041       SDValue Mask = Op.getOperand(4);
26042       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
26043       // There are 2 kinds of intrinsics in this group:
26044       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
26045       // (2) With rounding mode and sae - 7 operands.
26046       bool HasRounding = IntrWithRoundingModeOpcode != 0;
26047       if (Op.getNumOperands() == (5U + HasRounding)) {
26048         if (HasRounding) {
26049           SDValue Rnd = Op.getOperand(5);
26050           unsigned RC = 0;
26051           if (isRoundModeSAEToX(Rnd, RC))
26052             return getScalarMaskingNode(
26053                 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
26054                             DAG.getTargetConstant(RC, dl, MVT::i32)),
26055                 Mask, passThru, Subtarget, DAG);
26056           if (!isRoundModeCurDirection(Rnd))
26057             return SDValue();
26058         }
26059         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
26060                                                 Src2),
26061                                     Mask, passThru, Subtarget, DAG);
26062       }
26063 
26064       assert(Op.getNumOperands() == (6U + HasRounding) &&
26065              "Unexpected intrinsic form");
26066       SDValue RoundingMode = Op.getOperand(5);
26067       unsigned Opc = IntrData->Opc0;
26068       if (HasRounding) {
26069         SDValue Sae = Op.getOperand(6);
26070         if (isRoundModeSAE(Sae))
26071           Opc = IntrWithRoundingModeOpcode;
26072         else if (!isRoundModeCurDirection(Sae))
26073           return SDValue();
26074       }
26075       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
26076                                               Src2, RoundingMode),
26077                                   Mask, passThru, Subtarget, DAG);
26078     }
26079     case INTR_TYPE_SCALAR_MASK_RND: {
26080       SDValue Src1 = Op.getOperand(1);
26081       SDValue Src2 = Op.getOperand(2);
26082       SDValue passThru = Op.getOperand(3);
26083       SDValue Mask = Op.getOperand(4);
26084       SDValue Rnd = Op.getOperand(5);
26085 
26086       SDValue NewOp;
26087       unsigned RC = 0;
26088       if (isRoundModeCurDirection(Rnd))
26089         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
26090       else if (isRoundModeSAEToX(Rnd, RC))
26091         NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
26092                             DAG.getTargetConstant(RC, dl, MVT::i32));
26093       else
26094         return SDValue();
26095 
26096       return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
26097     }
26098     case INTR_TYPE_SCALAR_MASK_SAE: {
26099       SDValue Src1 = Op.getOperand(1);
26100       SDValue Src2 = Op.getOperand(2);
26101       SDValue passThru = Op.getOperand(3);
26102       SDValue Mask = Op.getOperand(4);
26103       SDValue Sae = Op.getOperand(5);
26104       unsigned Opc;
26105       if (isRoundModeCurDirection(Sae))
26106         Opc = IntrData->Opc0;
26107       else if (isRoundModeSAE(Sae))
26108         Opc = IntrData->Opc1;
26109       else
26110         return SDValue();
26111 
26112       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
26113                                   Mask, passThru, Subtarget, DAG);
26114     }
26115     case INTR_TYPE_2OP_MASK: {
26116       SDValue Src1 = Op.getOperand(1);
26117       SDValue Src2 = Op.getOperand(2);
26118       SDValue PassThru = Op.getOperand(3);
26119       SDValue Mask = Op.getOperand(4);
26120       SDValue NewOp;
26121       if (IntrData->Opc1 != 0) {
26122         SDValue Rnd = Op.getOperand(5);
26123         unsigned RC = 0;
26124         if (isRoundModeSAEToX(Rnd, RC))
26125           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
26126                               DAG.getTargetConstant(RC, dl, MVT::i32));
26127         else if (!isRoundModeCurDirection(Rnd))
26128           return SDValue();
26129       }
26130       if (!NewOp)
26131         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
26132       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
26133     }
26134     case INTR_TYPE_2OP_MASK_SAE: {
26135       SDValue Src1 = Op.getOperand(1);
26136       SDValue Src2 = Op.getOperand(2);
26137       SDValue PassThru = Op.getOperand(3);
26138       SDValue Mask = Op.getOperand(4);
26139 
26140       unsigned Opc = IntrData->Opc0;
26141       if (IntrData->Opc1 != 0) {
26142         SDValue Sae = Op.getOperand(5);
26143         if (isRoundModeSAE(Sae))
26144           Opc = IntrData->Opc1;
26145         else if (!isRoundModeCurDirection(Sae))
26146           return SDValue();
26147       }
26148 
26149       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
26150                                   Mask, PassThru, Subtarget, DAG);
26151     }
26152     case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
26153       SDValue Src1 = Op.getOperand(1);
26154       SDValue Src2 = Op.getOperand(2);
26155       SDValue Src3 = Op.getOperand(3);
26156       SDValue PassThru = Op.getOperand(4);
26157       SDValue Mask = Op.getOperand(5);
26158       SDValue Sae = Op.getOperand(6);
26159       unsigned Opc;
26160       if (isRoundModeCurDirection(Sae))
26161         Opc = IntrData->Opc0;
26162       else if (isRoundModeSAE(Sae))
26163         Opc = IntrData->Opc1;
26164       else
26165         return SDValue();
26166 
26167       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
26168                                   Mask, PassThru, Subtarget, DAG);
26169     }
26170     case INTR_TYPE_3OP_MASK_SAE: {
26171       SDValue Src1 = Op.getOperand(1);
26172       SDValue Src2 = Op.getOperand(2);
26173       SDValue Src3 = Op.getOperand(3);
26174       SDValue PassThru = Op.getOperand(4);
26175       SDValue Mask = Op.getOperand(5);
26176 
26177       unsigned Opc = IntrData->Opc0;
26178       if (IntrData->Opc1 != 0) {
26179         SDValue Sae = Op.getOperand(6);
26180         if (isRoundModeSAE(Sae))
26181           Opc = IntrData->Opc1;
26182         else if (!isRoundModeCurDirection(Sae))
26183           return SDValue();
26184       }
26185       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
26186                                   Mask, PassThru, Subtarget, DAG);
26187     }
26188     case BLENDV: {
26189       SDValue Src1 = Op.getOperand(1);
26190       SDValue Src2 = Op.getOperand(2);
26191       SDValue Src3 = Op.getOperand(3);
26192 
26193       EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
26194       Src3 = DAG.getBitcast(MaskVT, Src3);
26195 
26196       // Reverse the operands to match VSELECT order.
26197       return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
26198     }
26199     case VPERM_2OP : {
26200       SDValue Src1 = Op.getOperand(1);
26201       SDValue Src2 = Op.getOperand(2);
26202 
26203       // Swap Src1 and Src2 in the node creation
26204       return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
26205     }
26206     case CFMA_OP_MASKZ:
26207     case CFMA_OP_MASK: {
26208       SDValue Src1 = Op.getOperand(1);
26209       SDValue Src2 = Op.getOperand(2);
26210       SDValue Src3 = Op.getOperand(3);
26211       SDValue Mask = Op.getOperand(4);
26212       MVT VT = Op.getSimpleValueType();
26213 
26214       SDValue PassThru = Src3;
26215       if (IntrData->Type == CFMA_OP_MASKZ)
26216         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
26217 
26218       // We add rounding mode to the Node when
26219       //   - RC Opcode is specified and
26220       //   - RC is not "current direction".
26221       SDValue NewOp;
26222       if (IntrData->Opc1 != 0) {
26223         SDValue Rnd = Op.getOperand(5);
26224         unsigned RC = 0;
26225         if (isRoundModeSAEToX(Rnd, RC))
26226           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2, Src3,
26227                               DAG.getTargetConstant(RC, dl, MVT::i32));
26228         else if (!isRoundModeCurDirection(Rnd))
26229           return SDValue();
26230       }
26231       if (!NewOp)
26232         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2, Src3);
26233       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
26234     }
26235     case IFMA_OP:
26236       // NOTE: We need to swizzle the operands to pass the multiply operands
26237       // first.
26238       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26239                          Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
26240     case FPCLASSS: {
26241       SDValue Src1 = Op.getOperand(1);
26242       SDValue Imm = Op.getOperand(2);
26243       SDValue Mask = Op.getOperand(3);
26244       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
26245       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
26246                                                  Subtarget, DAG);
26247       // Need to fill with zeros to ensure the bitcast will produce zeroes
26248       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26249       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
26250                                 DAG.getConstant(0, dl, MVT::v8i1),
26251                                 FPclassMask, DAG.getIntPtrConstant(0, dl));
26252       return DAG.getBitcast(MVT::i8, Ins);
26253     }
26254 
26255     case CMP_MASK_CC: {
26256       MVT MaskVT = Op.getSimpleValueType();
26257       SDValue CC = Op.getOperand(3);
26258       SDValue Mask = Op.getOperand(4);
26259       // We specify 2 possible opcodes for intrinsics with rounding modes.
26260       // First, we check if the intrinsic may have non-default rounding mode,
26261       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
26262       if (IntrData->Opc1 != 0) {
26263         SDValue Sae = Op.getOperand(5);
26264         if (isRoundModeSAE(Sae))
26265           return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
26266                              Op.getOperand(2), CC, Mask, Sae);
26267         if (!isRoundModeCurDirection(Sae))
26268           return SDValue();
26269       }
26270       //default rounding mode
26271       return DAG.getNode(IntrData->Opc0, dl, MaskVT,
26272                          {Op.getOperand(1), Op.getOperand(2), CC, Mask});
26273     }
26274     case CMP_MASK_SCALAR_CC: {
26275       SDValue Src1 = Op.getOperand(1);
26276       SDValue Src2 = Op.getOperand(2);
26277       SDValue CC = Op.getOperand(3);
26278       SDValue Mask = Op.getOperand(4);
26279 
26280       SDValue Cmp;
26281       if (IntrData->Opc1 != 0) {
26282         SDValue Sae = Op.getOperand(5);
26283         if (isRoundModeSAE(Sae))
26284           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
26285         else if (!isRoundModeCurDirection(Sae))
26286           return SDValue();
26287       }
26288       //default rounding mode
26289       if (!Cmp.getNode())
26290         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
26291 
26292       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
26293                                              Subtarget, DAG);
26294       // Need to fill with zeros to ensure the bitcast will produce zeroes
26295       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26296       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
26297                                 DAG.getConstant(0, dl, MVT::v8i1),
26298                                 CmpMask, DAG.getIntPtrConstant(0, dl));
26299       return DAG.getBitcast(MVT::i8, Ins);
26300     }
26301     case COMI: { // Comparison intrinsics
26302       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
26303       SDValue LHS = Op.getOperand(1);
26304       SDValue RHS = Op.getOperand(2);
26305       // Some conditions require the operands to be swapped.
26306       if (CC == ISD::SETLT || CC == ISD::SETLE)
26307         std::swap(LHS, RHS);
26308 
26309       SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
26310       SDValue SetCC;
26311       switch (CC) {
26312       case ISD::SETEQ: { // (ZF = 0 and PF = 0)
26313         SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
26314         SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
26315         SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
26316         break;
26317       }
26318       case ISD::SETNE: { // (ZF = 1 or PF = 1)
26319         SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
26320         SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
26321         SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
26322         break;
26323       }
26324       case ISD::SETGT: // (CF = 0 and ZF = 0)
26325       case ISD::SETLT: { // Condition opposite to GT. Operands swapped above.
26326         SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
26327         break;
26328       }
26329       case ISD::SETGE: // CF = 0
26330       case ISD::SETLE: // Condition opposite to GE. Operands swapped above.
26331         SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
26332         break;
26333       default:
26334         llvm_unreachable("Unexpected illegal condition!");
26335       }
26336       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26337     }
26338     case COMI_RM: { // Comparison intrinsics with Sae
26339       SDValue LHS = Op.getOperand(1);
26340       SDValue RHS = Op.getOperand(2);
26341       unsigned CondVal = Op.getConstantOperandVal(3);
26342       SDValue Sae = Op.getOperand(4);
26343 
26344       SDValue FCmp;
26345       if (isRoundModeCurDirection(Sae))
26346         FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
26347                            DAG.getTargetConstant(CondVal, dl, MVT::i8));
26348       else if (isRoundModeSAE(Sae))
26349         FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
26350                            DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
26351       else
26352         return SDValue();
26353       // Need to fill with zeros to ensure the bitcast will produce zeroes
26354       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26355       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
26356                                 DAG.getConstant(0, dl, MVT::v16i1),
26357                                 FCmp, DAG.getIntPtrConstant(0, dl));
26358       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
26359                          DAG.getBitcast(MVT::i16, Ins));
26360     }
26361     case VSHIFT: {
26362       SDValue SrcOp = Op.getOperand(1);
26363       SDValue ShAmt = Op.getOperand(2);
26364 
26365       // Catch shift-by-constant.
26366       if (auto *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
26367         return getTargetVShiftByConstNode(IntrData->Opc0, dl,
26368                                           Op.getSimpleValueType(), SrcOp,
26369                                           CShAmt->getZExtValue(), DAG);
26370 
26371       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
26372                                  SrcOp, ShAmt, Subtarget, DAG);
26373     }
26374     case COMPRESS_EXPAND_IN_REG: {
26375       SDValue Mask = Op.getOperand(3);
26376       SDValue DataToCompress = Op.getOperand(1);
26377       SDValue PassThru = Op.getOperand(2);
26378       if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
26379         return Op.getOperand(1);
26380 
26381       // Avoid false dependency.
26382       if (PassThru.isUndef())
26383         PassThru = DAG.getConstant(0, dl, VT);
26384 
26385       return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
26386                          Mask);
26387     }
26388     case FIXUPIMM:
26389     case FIXUPIMM_MASKZ: {
26390       SDValue Src1 = Op.getOperand(1);
26391       SDValue Src2 = Op.getOperand(2);
26392       SDValue Src3 = Op.getOperand(3);
26393       SDValue Imm = Op.getOperand(4);
26394       SDValue Mask = Op.getOperand(5);
26395       SDValue Passthru = (IntrData->Type == FIXUPIMM)
26396                              ? Src1
26397                              : getZeroVector(VT, Subtarget, DAG, dl);
26398 
26399       unsigned Opc = IntrData->Opc0;
26400       if (IntrData->Opc1 != 0) {
26401         SDValue Sae = Op.getOperand(6);
26402         if (isRoundModeSAE(Sae))
26403           Opc = IntrData->Opc1;
26404         else if (!isRoundModeCurDirection(Sae))
26405           return SDValue();
26406       }
26407 
26408       SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
26409 
26410       if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
26411         return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
26412 
26413       return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
26414     }
26415     case ROUNDP: {
26416       assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
26417       // Clear the upper bits of the rounding immediate so that the legacy
26418       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
26419       auto Round = cast<ConstantSDNode>(Op.getOperand(2));
26420       SDValue RoundingMode =
26421           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
26422       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26423                          Op.getOperand(1), RoundingMode);
26424     }
26425     case ROUNDS: {
26426       assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
26427       // Clear the upper bits of the rounding immediate so that the legacy
26428       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
26429       auto Round = cast<ConstantSDNode>(Op.getOperand(3));
26430       SDValue RoundingMode =
26431           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
26432       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26433                          Op.getOperand(1), Op.getOperand(2), RoundingMode);
26434     }
26435     case BEXTRI: {
26436       assert(IntrData->Opc0 == X86ISD::BEXTRI && "Unexpected opcode");
26437 
26438       uint64_t Imm = Op.getConstantOperandVal(2);
26439       SDValue Control = DAG.getTargetConstant(Imm & 0xffff, dl,
26440                                               Op.getValueType());
26441       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26442                          Op.getOperand(1), Control);
26443     }
26444     // ADC/ADCX/SBB
26445     case ADX: {
26446       SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
26447       SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
26448 
26449       SDValue Res;
26450       // If the carry in is zero, then we should just use ADD/SUB instead of
26451       // ADC/SBB.
26452       if (isNullConstant(Op.getOperand(1))) {
26453         Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
26454                           Op.getOperand(3));
26455       } else {
26456         SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
26457                                     DAG.getConstant(-1, dl, MVT::i8));
26458         Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
26459                           Op.getOperand(3), GenCF.getValue(1));
26460       }
26461       SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
26462       SDValue Results[] = { SetCC, Res };
26463       return DAG.getMergeValues(Results, dl);
26464     }
26465     case CVTPD2PS_MASK:
26466     case CVTPD2DQ_MASK:
26467     case CVTQQ2PS_MASK:
26468     case TRUNCATE_TO_REG: {
26469       SDValue Src = Op.getOperand(1);
26470       SDValue PassThru = Op.getOperand(2);
26471       SDValue Mask = Op.getOperand(3);
26472 
26473       if (isAllOnesConstant(Mask))
26474         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
26475 
26476       MVT SrcVT = Src.getSimpleValueType();
26477       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
26478       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26479       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
26480                          {Src, PassThru, Mask});
26481     }
26482     case CVTPS2PH_MASK: {
26483       SDValue Src = Op.getOperand(1);
26484       SDValue Rnd = Op.getOperand(2);
26485       SDValue PassThru = Op.getOperand(3);
26486       SDValue Mask = Op.getOperand(4);
26487 
26488       if (isAllOnesConstant(Mask))
26489         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src, Rnd);
26490 
26491       MVT SrcVT = Src.getSimpleValueType();
26492       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
26493       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26494       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, Rnd,
26495                          PassThru, Mask);
26496 
26497     }
26498     case CVTNEPS2BF16_MASK: {
26499       SDValue Src = Op.getOperand(1);
26500       SDValue PassThru = Op.getOperand(2);
26501       SDValue Mask = Op.getOperand(3);
26502 
26503       if (ISD::isBuildVectorAllOnes(Mask.getNode()))
26504         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
26505 
26506       // Break false dependency.
26507       if (PassThru.isUndef())
26508         PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
26509 
26510       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
26511                          Mask);
26512     }
26513     default:
26514       break;
26515     }
26516   }
26517 
26518   switch (IntNo) {
26519   default: return SDValue();    // Don't custom lower most intrinsics.
26520 
26521   // ptest and testp intrinsics. The intrinsic these come from are designed to
26522   // return an integer value, not just an instruction so lower it to the ptest
26523   // or testp pattern and a setcc for the result.
26524   case Intrinsic::x86_avx512_ktestc_b:
26525   case Intrinsic::x86_avx512_ktestc_w:
26526   case Intrinsic::x86_avx512_ktestc_d:
26527   case Intrinsic::x86_avx512_ktestc_q:
26528   case Intrinsic::x86_avx512_ktestz_b:
26529   case Intrinsic::x86_avx512_ktestz_w:
26530   case Intrinsic::x86_avx512_ktestz_d:
26531   case Intrinsic::x86_avx512_ktestz_q:
26532   case Intrinsic::x86_sse41_ptestz:
26533   case Intrinsic::x86_sse41_ptestc:
26534   case Intrinsic::x86_sse41_ptestnzc:
26535   case Intrinsic::x86_avx_ptestz_256:
26536   case Intrinsic::x86_avx_ptestc_256:
26537   case Intrinsic::x86_avx_ptestnzc_256:
26538   case Intrinsic::x86_avx_vtestz_ps:
26539   case Intrinsic::x86_avx_vtestc_ps:
26540   case Intrinsic::x86_avx_vtestnzc_ps:
26541   case Intrinsic::x86_avx_vtestz_pd:
26542   case Intrinsic::x86_avx_vtestc_pd:
26543   case Intrinsic::x86_avx_vtestnzc_pd:
26544   case Intrinsic::x86_avx_vtestz_ps_256:
26545   case Intrinsic::x86_avx_vtestc_ps_256:
26546   case Intrinsic::x86_avx_vtestnzc_ps_256:
26547   case Intrinsic::x86_avx_vtestz_pd_256:
26548   case Intrinsic::x86_avx_vtestc_pd_256:
26549   case Intrinsic::x86_avx_vtestnzc_pd_256: {
26550     unsigned TestOpc = X86ISD::PTEST;
26551     X86::CondCode X86CC;
26552     switch (IntNo) {
26553     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
26554     case Intrinsic::x86_avx512_ktestc_b:
26555     case Intrinsic::x86_avx512_ktestc_w:
26556     case Intrinsic::x86_avx512_ktestc_d:
26557     case Intrinsic::x86_avx512_ktestc_q:
26558       // CF = 1
26559       TestOpc = X86ISD::KTEST;
26560       X86CC = X86::COND_B;
26561       break;
26562     case Intrinsic::x86_avx512_ktestz_b:
26563     case Intrinsic::x86_avx512_ktestz_w:
26564     case Intrinsic::x86_avx512_ktestz_d:
26565     case Intrinsic::x86_avx512_ktestz_q:
26566       TestOpc = X86ISD::KTEST;
26567       X86CC = X86::COND_E;
26568       break;
26569     case Intrinsic::x86_avx_vtestz_ps:
26570     case Intrinsic::x86_avx_vtestz_pd:
26571     case Intrinsic::x86_avx_vtestz_ps_256:
26572     case Intrinsic::x86_avx_vtestz_pd_256:
26573       TestOpc = X86ISD::TESTP;
26574       LLVM_FALLTHROUGH;
26575     case Intrinsic::x86_sse41_ptestz:
26576     case Intrinsic::x86_avx_ptestz_256:
26577       // ZF = 1
26578       X86CC = X86::COND_E;
26579       break;
26580     case Intrinsic::x86_avx_vtestc_ps:
26581     case Intrinsic::x86_avx_vtestc_pd:
26582     case Intrinsic::x86_avx_vtestc_ps_256:
26583     case Intrinsic::x86_avx_vtestc_pd_256:
26584       TestOpc = X86ISD::TESTP;
26585       LLVM_FALLTHROUGH;
26586     case Intrinsic::x86_sse41_ptestc:
26587     case Intrinsic::x86_avx_ptestc_256:
26588       // CF = 1
26589       X86CC = X86::COND_B;
26590       break;
26591     case Intrinsic::x86_avx_vtestnzc_ps:
26592     case Intrinsic::x86_avx_vtestnzc_pd:
26593     case Intrinsic::x86_avx_vtestnzc_ps_256:
26594     case Intrinsic::x86_avx_vtestnzc_pd_256:
26595       TestOpc = X86ISD::TESTP;
26596       LLVM_FALLTHROUGH;
26597     case Intrinsic::x86_sse41_ptestnzc:
26598     case Intrinsic::x86_avx_ptestnzc_256:
26599       // ZF and CF = 0
26600       X86CC = X86::COND_A;
26601       break;
26602     }
26603 
26604     SDValue LHS = Op.getOperand(1);
26605     SDValue RHS = Op.getOperand(2);
26606     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
26607     SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
26608     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26609   }
26610 
26611   case Intrinsic::x86_sse42_pcmpistria128:
26612   case Intrinsic::x86_sse42_pcmpestria128:
26613   case Intrinsic::x86_sse42_pcmpistric128:
26614   case Intrinsic::x86_sse42_pcmpestric128:
26615   case Intrinsic::x86_sse42_pcmpistrio128:
26616   case Intrinsic::x86_sse42_pcmpestrio128:
26617   case Intrinsic::x86_sse42_pcmpistris128:
26618   case Intrinsic::x86_sse42_pcmpestris128:
26619   case Intrinsic::x86_sse42_pcmpistriz128:
26620   case Intrinsic::x86_sse42_pcmpestriz128: {
26621     unsigned Opcode;
26622     X86::CondCode X86CC;
26623     switch (IntNo) {
26624     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
26625     case Intrinsic::x86_sse42_pcmpistria128:
26626       Opcode = X86ISD::PCMPISTR;
26627       X86CC = X86::COND_A;
26628       break;
26629     case Intrinsic::x86_sse42_pcmpestria128:
26630       Opcode = X86ISD::PCMPESTR;
26631       X86CC = X86::COND_A;
26632       break;
26633     case Intrinsic::x86_sse42_pcmpistric128:
26634       Opcode = X86ISD::PCMPISTR;
26635       X86CC = X86::COND_B;
26636       break;
26637     case Intrinsic::x86_sse42_pcmpestric128:
26638       Opcode = X86ISD::PCMPESTR;
26639       X86CC = X86::COND_B;
26640       break;
26641     case Intrinsic::x86_sse42_pcmpistrio128:
26642       Opcode = X86ISD::PCMPISTR;
26643       X86CC = X86::COND_O;
26644       break;
26645     case Intrinsic::x86_sse42_pcmpestrio128:
26646       Opcode = X86ISD::PCMPESTR;
26647       X86CC = X86::COND_O;
26648       break;
26649     case Intrinsic::x86_sse42_pcmpistris128:
26650       Opcode = X86ISD::PCMPISTR;
26651       X86CC = X86::COND_S;
26652       break;
26653     case Intrinsic::x86_sse42_pcmpestris128:
26654       Opcode = X86ISD::PCMPESTR;
26655       X86CC = X86::COND_S;
26656       break;
26657     case Intrinsic::x86_sse42_pcmpistriz128:
26658       Opcode = X86ISD::PCMPISTR;
26659       X86CC = X86::COND_E;
26660       break;
26661     case Intrinsic::x86_sse42_pcmpestriz128:
26662       Opcode = X86ISD::PCMPESTR;
26663       X86CC = X86::COND_E;
26664       break;
26665     }
26666     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26667     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26668     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
26669     SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
26670     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26671   }
26672 
26673   case Intrinsic::x86_sse42_pcmpistri128:
26674   case Intrinsic::x86_sse42_pcmpestri128: {
26675     unsigned Opcode;
26676     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
26677       Opcode = X86ISD::PCMPISTR;
26678     else
26679       Opcode = X86ISD::PCMPESTR;
26680 
26681     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26682     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26683     return DAG.getNode(Opcode, dl, VTs, NewOps);
26684   }
26685 
26686   case Intrinsic::x86_sse42_pcmpistrm128:
26687   case Intrinsic::x86_sse42_pcmpestrm128: {
26688     unsigned Opcode;
26689     if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
26690       Opcode = X86ISD::PCMPISTR;
26691     else
26692       Opcode = X86ISD::PCMPESTR;
26693 
26694     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26695     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26696     return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
26697   }
26698 
26699   case Intrinsic::eh_sjlj_lsda: {
26700     MachineFunction &MF = DAG.getMachineFunction();
26701     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26702     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
26703     auto &Context = MF.getMMI().getContext();
26704     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
26705                                             Twine(MF.getFunctionNumber()));
26706     return DAG.getNode(getGlobalWrapperKind(), dl, VT,
26707                        DAG.getMCSymbol(S, PtrVT));
26708   }
26709 
26710   case Intrinsic::x86_seh_lsda: {
26711     // Compute the symbol for the LSDA. We know it'll get emitted later.
26712     MachineFunction &MF = DAG.getMachineFunction();
26713     SDValue Op1 = Op.getOperand(1);
26714     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
26715     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
26716         GlobalValue::dropLLVMManglingEscape(Fn->getName()));
26717 
26718     // Generate a simple absolute symbol reference. This intrinsic is only
26719     // supported on 32-bit Windows, which isn't PIC.
26720     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
26721     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
26722   }
26723 
26724   case Intrinsic::eh_recoverfp: {
26725     SDValue FnOp = Op.getOperand(1);
26726     SDValue IncomingFPOp = Op.getOperand(2);
26727     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
26728     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
26729     if (!Fn)
26730       report_fatal_error(
26731           "llvm.eh.recoverfp must take a function as the first argument");
26732     return recoverFramePointer(DAG, Fn, IncomingFPOp);
26733   }
26734 
26735   case Intrinsic::localaddress: {
26736     // Returns one of the stack, base, or frame pointer registers, depending on
26737     // which is used to reference local variables.
26738     MachineFunction &MF = DAG.getMachineFunction();
26739     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26740     unsigned Reg;
26741     if (RegInfo->hasBasePointer(MF))
26742       Reg = RegInfo->getBaseRegister();
26743     else { // Handles the SP or FP case.
26744       bool CantUseFP = RegInfo->hasStackRealignment(MF);
26745       if (CantUseFP)
26746         Reg = RegInfo->getPtrSizedStackRegister(MF);
26747       else
26748         Reg = RegInfo->getPtrSizedFrameRegister(MF);
26749     }
26750     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
26751   }
26752   case Intrinsic::swift_async_context_addr: {
26753     auto &MF = DAG.getMachineFunction();
26754     auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
26755     if (Subtarget.is64Bit()) {
26756       MF.getFrameInfo().setFrameAddressIsTaken(true);
26757       X86FI->setHasSwiftAsyncContext(true);
26758       return SDValue(
26759           DAG.getMachineNode(
26760               X86::SUB64ri8, dl, MVT::i64,
26761               DAG.getCopyFromReg(DAG.getEntryNode(), dl, X86::RBP, MVT::i64),
26762               DAG.getTargetConstant(8, dl, MVT::i32)),
26763           0);
26764     } else {
26765       // 32-bit so no special extended frame, create or reuse an existing stack
26766       // slot.
26767       if (!X86FI->getSwiftAsyncContextFrameIdx())
26768         X86FI->setSwiftAsyncContextFrameIdx(
26769             MF.getFrameInfo().CreateStackObject(4, Align(4), false));
26770       return DAG.getFrameIndex(*X86FI->getSwiftAsyncContextFrameIdx(), MVT::i32);
26771     }
26772   }
26773   case Intrinsic::x86_avx512_vp2intersect_q_512:
26774   case Intrinsic::x86_avx512_vp2intersect_q_256:
26775   case Intrinsic::x86_avx512_vp2intersect_q_128:
26776   case Intrinsic::x86_avx512_vp2intersect_d_512:
26777   case Intrinsic::x86_avx512_vp2intersect_d_256:
26778   case Intrinsic::x86_avx512_vp2intersect_d_128: {
26779     MVT MaskVT = Op.getSimpleValueType();
26780 
26781     SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
26782     SDLoc DL(Op);
26783 
26784     SDValue Operation =
26785         DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
26786                     Op->getOperand(1), Op->getOperand(2));
26787 
26788     SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
26789                                                  MaskVT, Operation);
26790     SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
26791                                                  MaskVT, Operation);
26792     return DAG.getMergeValues({Result0, Result1}, DL);
26793   }
26794   case Intrinsic::x86_mmx_pslli_w:
26795   case Intrinsic::x86_mmx_pslli_d:
26796   case Intrinsic::x86_mmx_pslli_q:
26797   case Intrinsic::x86_mmx_psrli_w:
26798   case Intrinsic::x86_mmx_psrli_d:
26799   case Intrinsic::x86_mmx_psrli_q:
26800   case Intrinsic::x86_mmx_psrai_w:
26801   case Intrinsic::x86_mmx_psrai_d: {
26802     SDLoc DL(Op);
26803     SDValue ShAmt = Op.getOperand(2);
26804     // If the argument is a constant, convert it to a target constant.
26805     if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
26806       // Clamp out of bounds shift amounts since they will otherwise be masked
26807       // to 8-bits which may make it no longer out of bounds.
26808       unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
26809       if (ShiftAmount == 0)
26810         return Op.getOperand(1);
26811 
26812       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
26813                          Op.getOperand(0), Op.getOperand(1),
26814                          DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
26815     }
26816 
26817     unsigned NewIntrinsic;
26818     switch (IntNo) {
26819     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
26820     case Intrinsic::x86_mmx_pslli_w:
26821       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
26822       break;
26823     case Intrinsic::x86_mmx_pslli_d:
26824       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
26825       break;
26826     case Intrinsic::x86_mmx_pslli_q:
26827       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
26828       break;
26829     case Intrinsic::x86_mmx_psrli_w:
26830       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
26831       break;
26832     case Intrinsic::x86_mmx_psrli_d:
26833       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
26834       break;
26835     case Intrinsic::x86_mmx_psrli_q:
26836       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
26837       break;
26838     case Intrinsic::x86_mmx_psrai_w:
26839       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
26840       break;
26841     case Intrinsic::x86_mmx_psrai_d:
26842       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
26843       break;
26844     }
26845 
26846     // The vector shift intrinsics with scalars uses 32b shift amounts but
26847     // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
26848     // MMX register.
26849     ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
26850     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
26851                        DAG.getTargetConstant(NewIntrinsic, DL,
26852                                              getPointerTy(DAG.getDataLayout())),
26853                        Op.getOperand(1), ShAmt);
26854   }
26855   case Intrinsic::thread_pointer: {
26856     if (Subtarget.isTargetELF()) {
26857       SDLoc dl(Op);
26858       EVT PtrVT = getPointerTy(DAG.getDataLayout());
26859       // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
26860       Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(
26861           *DAG.getContext(), Subtarget.is64Bit() ? X86AS::FS : X86AS::GS));
26862       return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
26863                          DAG.getIntPtrConstant(0, dl), MachinePointerInfo(Ptr));
26864     }
26865     report_fatal_error(
26866         "Target OS doesn't support __builtin_thread_pointer() yet.");
26867   }
26868   }
26869 }
26870 
26871 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26872                                  SDValue Src, SDValue Mask, SDValue Base,
26873                                  SDValue Index, SDValue ScaleOp, SDValue Chain,
26874                                  const X86Subtarget &Subtarget) {
26875   SDLoc dl(Op);
26876   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26877   // Scale must be constant.
26878   if (!C)
26879     return SDValue();
26880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26881   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26882                                         TLI.getPointerTy(DAG.getDataLayout()));
26883   EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
26884   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
26885   // If source is undef or we know it won't be used, use a zero vector
26886   // to break register dependency.
26887   // TODO: use undef instead and let BreakFalseDeps deal with it?
26888   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
26889     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
26890 
26891   // Cast mask to an integer type.
26892   Mask = DAG.getBitcast(MaskVT, Mask);
26893 
26894   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26895 
26896   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
26897   SDValue Res =
26898       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
26899                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26900   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
26901 }
26902 
26903 static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
26904                              SDValue Src, SDValue Mask, SDValue Base,
26905                              SDValue Index, SDValue ScaleOp, SDValue Chain,
26906                              const X86Subtarget &Subtarget) {
26907   MVT VT = Op.getSimpleValueType();
26908   SDLoc dl(Op);
26909   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26910   // Scale must be constant.
26911   if (!C)
26912     return SDValue();
26913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26914   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26915                                         TLI.getPointerTy(DAG.getDataLayout()));
26916   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
26917                               VT.getVectorNumElements());
26918   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
26919 
26920   // We support two versions of the gather intrinsics. One with scalar mask and
26921   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26922   if (Mask.getValueType() != MaskVT)
26923     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26924 
26925   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
26926   // If source is undef or we know it won't be used, use a zero vector
26927   // to break register dependency.
26928   // TODO: use undef instead and let BreakFalseDeps deal with it?
26929   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
26930     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
26931 
26932   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26933 
26934   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
26935   SDValue Res =
26936       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
26937                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26938   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
26939 }
26940 
26941 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26942                                SDValue Src, SDValue Mask, SDValue Base,
26943                                SDValue Index, SDValue ScaleOp, SDValue Chain,
26944                                const X86Subtarget &Subtarget) {
26945   SDLoc dl(Op);
26946   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26947   // Scale must be constant.
26948   if (!C)
26949     return SDValue();
26950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26951   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26952                                         TLI.getPointerTy(DAG.getDataLayout()));
26953   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
26954                               Src.getSimpleValueType().getVectorNumElements());
26955   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
26956 
26957   // We support two versions of the scatter intrinsics. One with scalar mask and
26958   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26959   if (Mask.getValueType() != MaskVT)
26960     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26961 
26962   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26963 
26964   SDVTList VTs = DAG.getVTList(MVT::Other);
26965   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
26966   SDValue Res =
26967       DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
26968                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26969   return Res;
26970 }
26971 
26972 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26973                                SDValue Mask, SDValue Base, SDValue Index,
26974                                SDValue ScaleOp, SDValue Chain,
26975                                const X86Subtarget &Subtarget) {
26976   SDLoc dl(Op);
26977   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26978   // Scale must be constant.
26979   if (!C)
26980     return SDValue();
26981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26982   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26983                                         TLI.getPointerTy(DAG.getDataLayout()));
26984   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
26985   SDValue Segment = DAG.getRegister(0, MVT::i32);
26986   MVT MaskVT =
26987     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
26988   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26989   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
26990   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
26991   return SDValue(Res, 0);
26992 }
26993 
26994 /// Handles the lowering of builtin intrinsics with chain that return their
26995 /// value into registers EDX:EAX.
26996 /// If operand ScrReg is a valid register identifier, then operand 2 of N is
26997 /// copied to SrcReg. The assumption is that SrcReg is an implicit input to
26998 /// TargetOpcode.
26999 /// Returns a Glue value which can be used to add extra copy-from-reg if the
27000 /// expanded intrinsics implicitly defines extra registers (i.e. not just
27001 /// EDX:EAX).
27002 static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
27003                                         SelectionDAG &DAG,
27004                                         unsigned TargetOpcode,
27005                                         unsigned SrcReg,
27006                                         const X86Subtarget &Subtarget,
27007                                         SmallVectorImpl<SDValue> &Results) {
27008   SDValue Chain = N->getOperand(0);
27009   SDValue Glue;
27010 
27011   if (SrcReg) {
27012     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
27013     Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
27014     Glue = Chain.getValue(1);
27015   }
27016 
27017   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
27018   SDValue N1Ops[] = {Chain, Glue};
27019   SDNode *N1 = DAG.getMachineNode(
27020       TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
27021   Chain = SDValue(N1, 0);
27022 
27023   // Reads the content of XCR and returns it in registers EDX:EAX.
27024   SDValue LO, HI;
27025   if (Subtarget.is64Bit()) {
27026     LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
27027     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
27028                             LO.getValue(2));
27029   } else {
27030     LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
27031     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
27032                             LO.getValue(2));
27033   }
27034   Chain = HI.getValue(1);
27035   Glue = HI.getValue(2);
27036 
27037   if (Subtarget.is64Bit()) {
27038     // Merge the two 32-bit values into a 64-bit one.
27039     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
27040                               DAG.getConstant(32, DL, MVT::i8));
27041     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
27042     Results.push_back(Chain);
27043     return Glue;
27044   }
27045 
27046   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
27047   SDValue Ops[] = { LO, HI };
27048   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
27049   Results.push_back(Pair);
27050   Results.push_back(Chain);
27051   return Glue;
27052 }
27053 
27054 /// Handles the lowering of builtin intrinsics that read the time stamp counter
27055 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
27056 /// READCYCLECOUNTER nodes.
27057 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
27058                                     SelectionDAG &DAG,
27059                                     const X86Subtarget &Subtarget,
27060                                     SmallVectorImpl<SDValue> &Results) {
27061   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
27062   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
27063   // and the EAX register is loaded with the low-order 32 bits.
27064   SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
27065                                              /* NoRegister */0, Subtarget,
27066                                              Results);
27067   if (Opcode != X86::RDTSCP)
27068     return;
27069 
27070   SDValue Chain = Results[1];
27071   // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
27072   // the ECX register. Add 'ecx' explicitly to the chain.
27073   SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
27074   Results[1] = ecx;
27075   Results.push_back(ecx.getValue(1));
27076 }
27077 
27078 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
27079                                      SelectionDAG &DAG) {
27080   SmallVector<SDValue, 3> Results;
27081   SDLoc DL(Op);
27082   getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
27083                           Results);
27084   return DAG.getMergeValues(Results, DL);
27085 }
27086 
27087 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
27088   MachineFunction &MF = DAG.getMachineFunction();
27089   SDValue Chain = Op.getOperand(0);
27090   SDValue RegNode = Op.getOperand(2);
27091   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
27092   if (!EHInfo)
27093     report_fatal_error("EH registrations only live in functions using WinEH");
27094 
27095   // Cast the operand to an alloca, and remember the frame index.
27096   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
27097   if (!FINode)
27098     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
27099   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
27100 
27101   // Return the chain operand without making any DAG nodes.
27102   return Chain;
27103 }
27104 
27105 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
27106   MachineFunction &MF = DAG.getMachineFunction();
27107   SDValue Chain = Op.getOperand(0);
27108   SDValue EHGuard = Op.getOperand(2);
27109   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
27110   if (!EHInfo)
27111     report_fatal_error("EHGuard only live in functions using WinEH");
27112 
27113   // Cast the operand to an alloca, and remember the frame index.
27114   auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
27115   if (!FINode)
27116     report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
27117   EHInfo->EHGuardFrameIndex = FINode->getIndex();
27118 
27119   // Return the chain operand without making any DAG nodes.
27120   return Chain;
27121 }
27122 
27123 /// Emit Truncating Store with signed or unsigned saturation.
27124 static SDValue
27125 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl, SDValue Val,
27126                 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
27127                 SelectionDAG &DAG) {
27128   SDVTList VTs = DAG.getVTList(MVT::Other);
27129   SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
27130   SDValue Ops[] = { Chain, Val, Ptr, Undef };
27131   unsigned Opc = SignedSat ? X86ISD::VTRUNCSTORES : X86ISD::VTRUNCSTOREUS;
27132   return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
27133 }
27134 
27135 /// Emit Masked Truncating Store with signed or unsigned saturation.
27136 static SDValue
27137 EmitMaskedTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl,
27138                       SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
27139                       MachineMemOperand *MMO, SelectionDAG &DAG) {
27140   SDVTList VTs = DAG.getVTList(MVT::Other);
27141   SDValue Ops[] = { Chain, Val, Ptr, Mask };
27142   unsigned Opc = SignedSat ? X86ISD::VMTRUNCSTORES : X86ISD::VMTRUNCSTOREUS;
27143   return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
27144 }
27145 
27146 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
27147                                       SelectionDAG &DAG) {
27148   unsigned IntNo = Op.getConstantOperandVal(1);
27149   const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
27150   if (!IntrData) {
27151     switch (IntNo) {
27152     case llvm::Intrinsic::x86_seh_ehregnode:
27153       return MarkEHRegistrationNode(Op, DAG);
27154     case llvm::Intrinsic::x86_seh_ehguard:
27155       return MarkEHGuard(Op, DAG);
27156     case llvm::Intrinsic::x86_rdpkru: {
27157       SDLoc dl(Op);
27158       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27159       // Create a RDPKRU node and pass 0 to the ECX parameter.
27160       return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
27161                          DAG.getConstant(0, dl, MVT::i32));
27162     }
27163     case llvm::Intrinsic::x86_wrpkru: {
27164       SDLoc dl(Op);
27165       // Create a WRPKRU node, pass the input to the EAX parameter,  and pass 0
27166       // to the EDX and ECX parameters.
27167       return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
27168                          Op.getOperand(0), Op.getOperand(2),
27169                          DAG.getConstant(0, dl, MVT::i32),
27170                          DAG.getConstant(0, dl, MVT::i32));
27171     }
27172     case llvm::Intrinsic::asan_check_memaccess: {
27173       // Mark this as adjustsStack because it will be lowered to a call.
27174       DAG.getMachineFunction().getFrameInfo().setAdjustsStack(true);
27175       // Don't do anything here, we will expand these intrinsics out later.
27176       return Op;
27177     }
27178     case llvm::Intrinsic::x86_flags_read_u32:
27179     case llvm::Intrinsic::x86_flags_read_u64:
27180     case llvm::Intrinsic::x86_flags_write_u32:
27181     case llvm::Intrinsic::x86_flags_write_u64: {
27182       // We need a frame pointer because this will get lowered to a PUSH/POP
27183       // sequence.
27184       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
27185       MFI.setHasCopyImplyingStackAdjustment(true);
27186       // Don't do anything here, we will expand these intrinsics out later
27187       // during FinalizeISel in EmitInstrWithCustomInserter.
27188       return Op;
27189     }
27190     case Intrinsic::x86_lwpins32:
27191     case Intrinsic::x86_lwpins64:
27192     case Intrinsic::x86_umwait:
27193     case Intrinsic::x86_tpause: {
27194       SDLoc dl(Op);
27195       SDValue Chain = Op->getOperand(0);
27196       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27197       unsigned Opcode;
27198 
27199       switch (IntNo) {
27200       default: llvm_unreachable("Impossible intrinsic");
27201       case Intrinsic::x86_umwait:
27202         Opcode = X86ISD::UMWAIT;
27203         break;
27204       case Intrinsic::x86_tpause:
27205         Opcode = X86ISD::TPAUSE;
27206         break;
27207       case Intrinsic::x86_lwpins32:
27208       case Intrinsic::x86_lwpins64:
27209         Opcode = X86ISD::LWPINS;
27210         break;
27211       }
27212 
27213       SDValue Operation =
27214           DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
27215                       Op->getOperand(3), Op->getOperand(4));
27216       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
27217       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27218                          Operation.getValue(1));
27219     }
27220     case Intrinsic::x86_enqcmd:
27221     case Intrinsic::x86_enqcmds: {
27222       SDLoc dl(Op);
27223       SDValue Chain = Op.getOperand(0);
27224       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27225       unsigned Opcode;
27226       switch (IntNo) {
27227       default: llvm_unreachable("Impossible intrinsic!");
27228       case Intrinsic::x86_enqcmd:
27229         Opcode = X86ISD::ENQCMD;
27230         break;
27231       case Intrinsic::x86_enqcmds:
27232         Opcode = X86ISD::ENQCMDS;
27233         break;
27234       }
27235       SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
27236                                       Op.getOperand(3));
27237       SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
27238       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27239                          Operation.getValue(1));
27240     }
27241     case Intrinsic::x86_aesenc128kl:
27242     case Intrinsic::x86_aesdec128kl:
27243     case Intrinsic::x86_aesenc256kl:
27244     case Intrinsic::x86_aesdec256kl: {
27245       SDLoc DL(Op);
27246       SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
27247       SDValue Chain = Op.getOperand(0);
27248       unsigned Opcode;
27249 
27250       switch (IntNo) {
27251       default: llvm_unreachable("Impossible intrinsic");
27252       case Intrinsic::x86_aesenc128kl:
27253         Opcode = X86ISD::AESENC128KL;
27254         break;
27255       case Intrinsic::x86_aesdec128kl:
27256         Opcode = X86ISD::AESDEC128KL;
27257         break;
27258       case Intrinsic::x86_aesenc256kl:
27259         Opcode = X86ISD::AESENC256KL;
27260         break;
27261       case Intrinsic::x86_aesdec256kl:
27262         Opcode = X86ISD::AESDEC256KL;
27263         break;
27264       }
27265 
27266       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27267       MachineMemOperand *MMO = MemIntr->getMemOperand();
27268       EVT MemVT = MemIntr->getMemoryVT();
27269       SDValue Operation = DAG.getMemIntrinsicNode(
27270           Opcode, DL, VTs, {Chain, Op.getOperand(2), Op.getOperand(3)}, MemVT,
27271           MMO);
27272       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(1), DL, DAG);
27273 
27274       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
27275                          {ZF, Operation.getValue(0), Operation.getValue(2)});
27276     }
27277     case Intrinsic::x86_aesencwide128kl:
27278     case Intrinsic::x86_aesdecwide128kl:
27279     case Intrinsic::x86_aesencwide256kl:
27280     case Intrinsic::x86_aesdecwide256kl: {
27281       SDLoc DL(Op);
27282       SDVTList VTs = DAG.getVTList(
27283           {MVT::i32, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64,
27284            MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::Other});
27285       SDValue Chain = Op.getOperand(0);
27286       unsigned Opcode;
27287 
27288       switch (IntNo) {
27289       default: llvm_unreachable("Impossible intrinsic");
27290       case Intrinsic::x86_aesencwide128kl:
27291         Opcode = X86ISD::AESENCWIDE128KL;
27292         break;
27293       case Intrinsic::x86_aesdecwide128kl:
27294         Opcode = X86ISD::AESDECWIDE128KL;
27295         break;
27296       case Intrinsic::x86_aesencwide256kl:
27297         Opcode = X86ISD::AESENCWIDE256KL;
27298         break;
27299       case Intrinsic::x86_aesdecwide256kl:
27300         Opcode = X86ISD::AESDECWIDE256KL;
27301         break;
27302       }
27303 
27304       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27305       MachineMemOperand *MMO = MemIntr->getMemOperand();
27306       EVT MemVT = MemIntr->getMemoryVT();
27307       SDValue Operation = DAG.getMemIntrinsicNode(
27308           Opcode, DL, VTs,
27309           {Chain, Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
27310            Op.getOperand(5), Op.getOperand(6), Op.getOperand(7),
27311            Op.getOperand(8), Op.getOperand(9), Op.getOperand(10)},
27312           MemVT, MMO);
27313       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(0), DL, DAG);
27314 
27315       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
27316                          {ZF, Operation.getValue(1), Operation.getValue(2),
27317                           Operation.getValue(3), Operation.getValue(4),
27318                           Operation.getValue(5), Operation.getValue(6),
27319                           Operation.getValue(7), Operation.getValue(8),
27320                           Operation.getValue(9)});
27321     }
27322     case Intrinsic::x86_testui: {
27323       SDLoc dl(Op);
27324       SDValue Chain = Op.getOperand(0);
27325       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27326       SDValue Operation = DAG.getNode(X86ISD::TESTUI, dl, VTs, Chain);
27327       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
27328       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27329                          Operation.getValue(1));
27330     }
27331     }
27332     return SDValue();
27333   }
27334 
27335   SDLoc dl(Op);
27336   switch(IntrData->Type) {
27337   default: llvm_unreachable("Unknown Intrinsic Type");
27338   case RDSEED:
27339   case RDRAND: {
27340     // Emit the node with the right value type.
27341     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
27342     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
27343 
27344     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
27345     // Otherwise return the value from Rand, which is always 0, casted to i32.
27346     SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
27347                      DAG.getConstant(1, dl, Op->getValueType(1)),
27348                      DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
27349                      SDValue(Result.getNode(), 1)};
27350     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
27351 
27352     // Return { result, isValid, chain }.
27353     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
27354                        SDValue(Result.getNode(), 2));
27355   }
27356   case GATHER_AVX2: {
27357     SDValue Chain = Op.getOperand(0);
27358     SDValue Src   = Op.getOperand(2);
27359     SDValue Base  = Op.getOperand(3);
27360     SDValue Index = Op.getOperand(4);
27361     SDValue Mask  = Op.getOperand(5);
27362     SDValue Scale = Op.getOperand(6);
27363     return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
27364                              Scale, Chain, Subtarget);
27365   }
27366   case GATHER: {
27367   //gather(v1, mask, index, base, scale);
27368     SDValue Chain = Op.getOperand(0);
27369     SDValue Src   = Op.getOperand(2);
27370     SDValue Base  = Op.getOperand(3);
27371     SDValue Index = Op.getOperand(4);
27372     SDValue Mask  = Op.getOperand(5);
27373     SDValue Scale = Op.getOperand(6);
27374     return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
27375                          Chain, Subtarget);
27376   }
27377   case SCATTER: {
27378   //scatter(base, mask, index, v1, scale);
27379     SDValue Chain = Op.getOperand(0);
27380     SDValue Base  = Op.getOperand(2);
27381     SDValue Mask  = Op.getOperand(3);
27382     SDValue Index = Op.getOperand(4);
27383     SDValue Src   = Op.getOperand(5);
27384     SDValue Scale = Op.getOperand(6);
27385     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
27386                           Scale, Chain, Subtarget);
27387   }
27388   case PREFETCH: {
27389     const APInt &HintVal = Op.getConstantOperandAPInt(6);
27390     assert((HintVal == 2 || HintVal == 3) &&
27391            "Wrong prefetch hint in intrinsic: should be 2 or 3");
27392     unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
27393     SDValue Chain = Op.getOperand(0);
27394     SDValue Mask  = Op.getOperand(2);
27395     SDValue Index = Op.getOperand(3);
27396     SDValue Base  = Op.getOperand(4);
27397     SDValue Scale = Op.getOperand(5);
27398     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
27399                            Subtarget);
27400   }
27401   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
27402   case RDTSC: {
27403     SmallVector<SDValue, 2> Results;
27404     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
27405                             Results);
27406     return DAG.getMergeValues(Results, dl);
27407   }
27408   // Read Performance Monitoring Counters.
27409   case RDPMC:
27410   // GetExtended Control Register.
27411   case XGETBV: {
27412     SmallVector<SDValue, 2> Results;
27413 
27414     // RDPMC uses ECX to select the index of the performance counter to read.
27415     // XGETBV uses ECX to select the index of the XCR register to return.
27416     // The result is stored into registers EDX:EAX.
27417     expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
27418                                 Subtarget, Results);
27419     return DAG.getMergeValues(Results, dl);
27420   }
27421   // XTEST intrinsics.
27422   case XTEST: {
27423     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
27424     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
27425 
27426     SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
27427     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
27428     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
27429                        Ret, SDValue(InTrans.getNode(), 1));
27430   }
27431   case TRUNCATE_TO_MEM_VI8:
27432   case TRUNCATE_TO_MEM_VI16:
27433   case TRUNCATE_TO_MEM_VI32: {
27434     SDValue Mask = Op.getOperand(4);
27435     SDValue DataToTruncate = Op.getOperand(3);
27436     SDValue Addr = Op.getOperand(2);
27437     SDValue Chain = Op.getOperand(0);
27438 
27439     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
27440     assert(MemIntr && "Expected MemIntrinsicSDNode!");
27441 
27442     EVT MemVT  = MemIntr->getMemoryVT();
27443 
27444     uint16_t TruncationOp = IntrData->Opc0;
27445     switch (TruncationOp) {
27446     case X86ISD::VTRUNC: {
27447       if (isAllOnesConstant(Mask)) // return just a truncate store
27448         return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
27449                                  MemIntr->getMemOperand());
27450 
27451       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
27452       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27453       SDValue Offset = DAG.getUNDEF(VMask.getValueType());
27454 
27455       return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
27456                                 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
27457                                 true /* truncating */);
27458     }
27459     case X86ISD::VTRUNCUS:
27460     case X86ISD::VTRUNCS: {
27461       bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
27462       if (isAllOnesConstant(Mask))
27463         return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
27464                                MemIntr->getMemOperand(), DAG);
27465 
27466       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
27467       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27468 
27469       return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
27470                                    VMask, MemVT, MemIntr->getMemOperand(), DAG);
27471     }
27472     default:
27473       llvm_unreachable("Unsupported truncstore intrinsic");
27474     }
27475   }
27476   }
27477 }
27478 
27479 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
27480                                            SelectionDAG &DAG) const {
27481   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
27482   MFI.setReturnAddressIsTaken(true);
27483 
27484   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
27485     return SDValue();
27486 
27487   unsigned Depth = Op.getConstantOperandVal(0);
27488   SDLoc dl(Op);
27489   EVT PtrVT = getPointerTy(DAG.getDataLayout());
27490 
27491   if (Depth > 0) {
27492     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
27493     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27494     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
27495     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
27496                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
27497                        MachinePointerInfo());
27498   }
27499 
27500   // Just load the return address.
27501   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
27502   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
27503                      MachinePointerInfo());
27504 }
27505 
27506 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
27507                                                  SelectionDAG &DAG) const {
27508   DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
27509   return getReturnAddressFrameIndex(DAG);
27510 }
27511 
27512 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
27513   MachineFunction &MF = DAG.getMachineFunction();
27514   MachineFrameInfo &MFI = MF.getFrameInfo();
27515   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
27516   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27517   EVT VT = Op.getValueType();
27518 
27519   MFI.setFrameAddressIsTaken(true);
27520 
27521   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
27522     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
27523     // is not possible to crawl up the stack without looking at the unwind codes
27524     // simultaneously.
27525     int FrameAddrIndex = FuncInfo->getFAIndex();
27526     if (!FrameAddrIndex) {
27527       // Set up a frame object for the return address.
27528       unsigned SlotSize = RegInfo->getSlotSize();
27529       FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
27530           SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
27531       FuncInfo->setFAIndex(FrameAddrIndex);
27532     }
27533     return DAG.getFrameIndex(FrameAddrIndex, VT);
27534   }
27535 
27536   unsigned FrameReg =
27537       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
27538   SDLoc dl(Op);  // FIXME probably not meaningful
27539   unsigned Depth = Op.getConstantOperandVal(0);
27540   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
27541           (FrameReg == X86::EBP && VT == MVT::i32)) &&
27542          "Invalid Frame Register!");
27543   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
27544   while (Depth--)
27545     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
27546                             MachinePointerInfo());
27547   return FrameAddr;
27548 }
27549 
27550 // FIXME? Maybe this could be a TableGen attribute on some registers and
27551 // this table could be generated automatically from RegInfo.
27552 Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
27553                                               const MachineFunction &MF) const {
27554   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
27555 
27556   Register Reg = StringSwitch<unsigned>(RegName)
27557                        .Case("esp", X86::ESP)
27558                        .Case("rsp", X86::RSP)
27559                        .Case("ebp", X86::EBP)
27560                        .Case("rbp", X86::RBP)
27561                        .Default(0);
27562 
27563   if (Reg == X86::EBP || Reg == X86::RBP) {
27564     if (!TFI.hasFP(MF))
27565       report_fatal_error("register " + StringRef(RegName) +
27566                          " is allocatable: function has no frame pointer");
27567 #ifndef NDEBUG
27568     else {
27569       const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27570       Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
27571       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
27572              "Invalid Frame Register!");
27573     }
27574 #endif
27575   }
27576 
27577   if (Reg)
27578     return Reg;
27579 
27580   report_fatal_error("Invalid register name global variable");
27581 }
27582 
27583 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
27584                                                      SelectionDAG &DAG) const {
27585   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27586   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
27587 }
27588 
27589 Register X86TargetLowering::getExceptionPointerRegister(
27590     const Constant *PersonalityFn) const {
27591   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
27592     return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
27593 
27594   return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
27595 }
27596 
27597 Register X86TargetLowering::getExceptionSelectorRegister(
27598     const Constant *PersonalityFn) const {
27599   // Funclet personalities don't use selectors (the runtime does the selection).
27600   if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
27601     return X86::NoRegister;
27602   return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
27603 }
27604 
27605 bool X86TargetLowering::needsFixedCatchObjects() const {
27606   return Subtarget.isTargetWin64();
27607 }
27608 
27609 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
27610   SDValue Chain     = Op.getOperand(0);
27611   SDValue Offset    = Op.getOperand(1);
27612   SDValue Handler   = Op.getOperand(2);
27613   SDLoc dl      (Op);
27614 
27615   EVT PtrVT = getPointerTy(DAG.getDataLayout());
27616   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27617   Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
27618   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
27619           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
27620          "Invalid Frame Register!");
27621   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
27622   Register StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
27623 
27624   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
27625                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
27626                                                        dl));
27627   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
27628   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
27629   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
27630 
27631   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
27632                      DAG.getRegister(StoreAddrReg, PtrVT));
27633 }
27634 
27635 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
27636                                                SelectionDAG &DAG) const {
27637   SDLoc DL(Op);
27638   // If the subtarget is not 64bit, we may need the global base reg
27639   // after isel expand pseudo, i.e., after CGBR pass ran.
27640   // Therefore, ask for the GlobalBaseReg now, so that the pass
27641   // inserts the code for us in case we need it.
27642   // Otherwise, we will end up in a situation where we will
27643   // reference a virtual register that is not defined!
27644   if (!Subtarget.is64Bit()) {
27645     const X86InstrInfo *TII = Subtarget.getInstrInfo();
27646     (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
27647   }
27648   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
27649                      DAG.getVTList(MVT::i32, MVT::Other),
27650                      Op.getOperand(0), Op.getOperand(1));
27651 }
27652 
27653 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
27654                                                 SelectionDAG &DAG) const {
27655   SDLoc DL(Op);
27656   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
27657                      Op.getOperand(0), Op.getOperand(1));
27658 }
27659 
27660 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
27661                                                        SelectionDAG &DAG) const {
27662   SDLoc DL(Op);
27663   return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
27664                      Op.getOperand(0));
27665 }
27666 
27667 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
27668   return Op.getOperand(0);
27669 }
27670 
27671 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
27672                                                 SelectionDAG &DAG) const {
27673   SDValue Root = Op.getOperand(0);
27674   SDValue Trmp = Op.getOperand(1); // trampoline
27675   SDValue FPtr = Op.getOperand(2); // nested function
27676   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
27677   SDLoc dl (Op);
27678 
27679   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
27680   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
27681 
27682   if (Subtarget.is64Bit()) {
27683     SDValue OutChains[6];
27684 
27685     // Large code-model.
27686     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
27687     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
27688 
27689     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
27690     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
27691 
27692     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
27693 
27694     // Load the pointer to the nested function into R11.
27695     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
27696     SDValue Addr = Trmp;
27697     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27698                                 Addr, MachinePointerInfo(TrmpAddr));
27699 
27700     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27701                        DAG.getConstant(2, dl, MVT::i64));
27702     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
27703                                 MachinePointerInfo(TrmpAddr, 2), Align(2));
27704 
27705     // Load the 'nest' parameter value into R10.
27706     // R10 is specified in X86CallingConv.td
27707     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
27708     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27709                        DAG.getConstant(10, dl, MVT::i64));
27710     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27711                                 Addr, MachinePointerInfo(TrmpAddr, 10));
27712 
27713     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27714                        DAG.getConstant(12, dl, MVT::i64));
27715     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
27716                                 MachinePointerInfo(TrmpAddr, 12), Align(2));
27717 
27718     // Jump to the nested function.
27719     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
27720     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27721                        DAG.getConstant(20, dl, MVT::i64));
27722     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27723                                 Addr, MachinePointerInfo(TrmpAddr, 20));
27724 
27725     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
27726     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27727                        DAG.getConstant(22, dl, MVT::i64));
27728     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
27729                                 Addr, MachinePointerInfo(TrmpAddr, 22));
27730 
27731     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
27732   } else {
27733     const Function *Func =
27734       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
27735     CallingConv::ID CC = Func->getCallingConv();
27736     unsigned NestReg;
27737 
27738     switch (CC) {
27739     default:
27740       llvm_unreachable("Unsupported calling convention");
27741     case CallingConv::C:
27742     case CallingConv::X86_StdCall: {
27743       // Pass 'nest' parameter in ECX.
27744       // Must be kept in sync with X86CallingConv.td
27745       NestReg = X86::ECX;
27746 
27747       // Check that ECX wasn't needed by an 'inreg' parameter.
27748       FunctionType *FTy = Func->getFunctionType();
27749       const AttributeList &Attrs = Func->getAttributes();
27750 
27751       if (!Attrs.isEmpty() && !Func->isVarArg()) {
27752         unsigned InRegCount = 0;
27753         unsigned Idx = 0;
27754 
27755         for (FunctionType::param_iterator I = FTy->param_begin(),
27756              E = FTy->param_end(); I != E; ++I, ++Idx)
27757           if (Attrs.hasParamAttr(Idx, Attribute::InReg)) {
27758             const DataLayout &DL = DAG.getDataLayout();
27759             // FIXME: should only count parameters that are lowered to integers.
27760             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
27761           }
27762 
27763         if (InRegCount > 2) {
27764           report_fatal_error("Nest register in use - reduce number of inreg"
27765                              " parameters!");
27766         }
27767       }
27768       break;
27769     }
27770     case CallingConv::X86_FastCall:
27771     case CallingConv::X86_ThisCall:
27772     case CallingConv::Fast:
27773     case CallingConv::Tail:
27774     case CallingConv::SwiftTail:
27775       // Pass 'nest' parameter in EAX.
27776       // Must be kept in sync with X86CallingConv.td
27777       NestReg = X86::EAX;
27778       break;
27779     }
27780 
27781     SDValue OutChains[4];
27782     SDValue Addr, Disp;
27783 
27784     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27785                        DAG.getConstant(10, dl, MVT::i32));
27786     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
27787 
27788     // This is storing the opcode for MOV32ri.
27789     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
27790     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
27791     OutChains[0] =
27792         DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
27793                      Trmp, MachinePointerInfo(TrmpAddr));
27794 
27795     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27796                        DAG.getConstant(1, dl, MVT::i32));
27797     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
27798                                 MachinePointerInfo(TrmpAddr, 1), Align(1));
27799 
27800     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
27801     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27802                        DAG.getConstant(5, dl, MVT::i32));
27803     OutChains[2] =
27804         DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8), Addr,
27805                      MachinePointerInfo(TrmpAddr, 5), Align(1));
27806 
27807     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27808                        DAG.getConstant(6, dl, MVT::i32));
27809     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
27810                                 MachinePointerInfo(TrmpAddr, 6), Align(1));
27811 
27812     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
27813   }
27814 }
27815 
27816 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
27817                                             SelectionDAG &DAG) const {
27818   /*
27819    The rounding mode is in bits 11:10 of FPSR, and has the following
27820    settings:
27821      00 Round to nearest
27822      01 Round to -inf
27823      10 Round to +inf
27824      11 Round to 0
27825 
27826   FLT_ROUNDS, on the other hand, expects the following:
27827     -1 Undefined
27828      0 Round to 0
27829      1 Round to nearest
27830      2 Round to +inf
27831      3 Round to -inf
27832 
27833   To perform the conversion, we use a packed lookup table of the four 2-bit
27834   values that we can index by FPSP[11:10]
27835     0x2d --> (0b00,10,11,01) --> (0,2,3,1) >> FPSR[11:10]
27836 
27837     (0x2d >> ((FPSR & 0xc00) >> 9)) & 3
27838   */
27839 
27840   MachineFunction &MF = DAG.getMachineFunction();
27841   MVT VT = Op.getSimpleValueType();
27842   SDLoc DL(Op);
27843 
27844   // Save FP Control Word to stack slot
27845   int SSFI = MF.getFrameInfo().CreateStackObject(2, Align(2), false);
27846   SDValue StackSlot =
27847       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
27848 
27849   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
27850 
27851   SDValue Chain = Op.getOperand(0);
27852   SDValue Ops[] = {Chain, StackSlot};
27853   Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
27854                                   DAG.getVTList(MVT::Other), Ops, MVT::i16, MPI,
27855                                   Align(2), MachineMemOperand::MOStore);
27856 
27857   // Load FP Control Word from stack slot
27858   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI, Align(2));
27859   Chain = CWD.getValue(1);
27860 
27861   // Mask and turn the control bits into a shift for the lookup table.
27862   SDValue Shift =
27863     DAG.getNode(ISD::SRL, DL, MVT::i16,
27864                 DAG.getNode(ISD::AND, DL, MVT::i16,
27865                             CWD, DAG.getConstant(0xc00, DL, MVT::i16)),
27866                 DAG.getConstant(9, DL, MVT::i8));
27867   Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Shift);
27868 
27869   SDValue LUT = DAG.getConstant(0x2d, DL, MVT::i32);
27870   SDValue RetVal =
27871     DAG.getNode(ISD::AND, DL, MVT::i32,
27872                 DAG.getNode(ISD::SRL, DL, MVT::i32, LUT, Shift),
27873                 DAG.getConstant(3, DL, MVT::i32));
27874 
27875   RetVal = DAG.getZExtOrTrunc(RetVal, DL, VT);
27876 
27877   return DAG.getMergeValues({RetVal, Chain}, DL);
27878 }
27879 
27880 SDValue X86TargetLowering::LowerSET_ROUNDING(SDValue Op,
27881                                              SelectionDAG &DAG) const {
27882   MachineFunction &MF = DAG.getMachineFunction();
27883   SDLoc DL(Op);
27884   SDValue Chain = Op.getNode()->getOperand(0);
27885 
27886   // FP control word may be set only from data in memory. So we need to allocate
27887   // stack space to save/load FP control word.
27888   int OldCWFrameIdx = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
27889   SDValue StackSlot =
27890       DAG.getFrameIndex(OldCWFrameIdx, getPointerTy(DAG.getDataLayout()));
27891   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, OldCWFrameIdx);
27892   MachineMemOperand *MMO =
27893       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 2, Align(2));
27894 
27895   // Store FP control word into memory.
27896   SDValue Ops[] = {Chain, StackSlot};
27897   Chain = DAG.getMemIntrinsicNode(
27898       X86ISD::FNSTCW16m, DL, DAG.getVTList(MVT::Other), Ops, MVT::i16, MMO);
27899 
27900   // Load FP Control Word from stack slot and clear RM field (bits 11:10).
27901   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI);
27902   Chain = CWD.getValue(1);
27903   CWD = DAG.getNode(ISD::AND, DL, MVT::i16, CWD.getValue(0),
27904                     DAG.getConstant(0xf3ff, DL, MVT::i16));
27905 
27906   // Calculate new rounding mode.
27907   SDValue NewRM = Op.getNode()->getOperand(1);
27908   SDValue RMBits;
27909   if (auto *CVal = dyn_cast<ConstantSDNode>(NewRM)) {
27910     uint64_t RM = CVal->getZExtValue();
27911     int FieldVal;
27912     switch (static_cast<RoundingMode>(RM)) {
27913     case RoundingMode::NearestTiesToEven: FieldVal = X86::rmToNearest; break;
27914     case RoundingMode::TowardNegative:    FieldVal = X86::rmDownward; break;
27915     case RoundingMode::TowardPositive:    FieldVal = X86::rmUpward; break;
27916     case RoundingMode::TowardZero:        FieldVal = X86::rmTowardZero; break;
27917     default:
27918       llvm_unreachable("rounding mode is not supported by X86 hardware");
27919     }
27920     RMBits = DAG.getConstant(FieldVal, DL, MVT::i16);
27921   } else {
27922     // Need to convert argument into bits of control word:
27923     //    0 Round to 0       -> 11
27924     //    1 Round to nearest -> 00
27925     //    2 Round to +inf    -> 10
27926     //    3 Round to -inf    -> 01
27927     // The 2-bit value needs then to be shifted so that it occupies bits 11:10.
27928     // To make the conversion, put all these values into a value 0xc9 and shift
27929     // it left depending on the rounding mode:
27930     //    (0xc9 << 4) & 0xc00 = X86::rmTowardZero
27931     //    (0xc9 << 6) & 0xc00 = X86::rmToNearest
27932     //    ...
27933     // (0xc9 << (2 * NewRM + 4)) & 0xc00
27934     SDValue ShiftValue =
27935         DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
27936                     DAG.getNode(ISD::ADD, DL, MVT::i32,
27937                                 DAG.getNode(ISD::SHL, DL, MVT::i32, NewRM,
27938                                             DAG.getConstant(1, DL, MVT::i8)),
27939                                 DAG.getConstant(4, DL, MVT::i32)));
27940     SDValue Shifted =
27941         DAG.getNode(ISD::SHL, DL, MVT::i16, DAG.getConstant(0xc9, DL, MVT::i16),
27942                     ShiftValue);
27943     RMBits = DAG.getNode(ISD::AND, DL, MVT::i16, Shifted,
27944                          DAG.getConstant(0xc00, DL, MVT::i16));
27945   }
27946 
27947   // Update rounding mode bits and store the new FP Control Word into stack.
27948   CWD = DAG.getNode(ISD::OR, DL, MVT::i16, CWD, RMBits);
27949   Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, /* Alignment = */ 2);
27950 
27951   // Load FP control word from the slot.
27952   SDValue OpsLD[] = {Chain, StackSlot};
27953   MachineMemOperand *MMOL =
27954       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 2, Align(2));
27955   Chain = DAG.getMemIntrinsicNode(
27956       X86ISD::FLDCW16m, DL, DAG.getVTList(MVT::Other), OpsLD, MVT::i16, MMOL);
27957 
27958   // If target supports SSE, set MXCSR as well. Rounding mode is encoded in the
27959   // same way but in bits 14:13.
27960   if (Subtarget.hasSSE1()) {
27961     // Store MXCSR into memory.
27962     Chain = DAG.getNode(
27963         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
27964         DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
27965         StackSlot);
27966 
27967     // Load MXCSR from stack slot and clear RM field (bits 14:13).
27968     SDValue CWD = DAG.getLoad(MVT::i32, DL, Chain, StackSlot, MPI);
27969     Chain = CWD.getValue(1);
27970     CWD = DAG.getNode(ISD::AND, DL, MVT::i32, CWD.getValue(0),
27971                       DAG.getConstant(0xffff9fff, DL, MVT::i32));
27972 
27973     // Shift X87 RM bits from 11:10 to 14:13.
27974     RMBits = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, RMBits);
27975     RMBits = DAG.getNode(ISD::SHL, DL, MVT::i32, RMBits,
27976                          DAG.getConstant(3, DL, MVT::i8));
27977 
27978     // Update rounding mode bits and store the new FP Control Word into stack.
27979     CWD = DAG.getNode(ISD::OR, DL, MVT::i32, CWD, RMBits);
27980     Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, /* Alignment = */ 4);
27981 
27982     // Load MXCSR from the slot.
27983     Chain = DAG.getNode(
27984         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
27985         DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
27986         StackSlot);
27987   }
27988 
27989   return Chain;
27990 }
27991 
27992 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
27993 //
27994 // i8/i16 vector implemented using dword LZCNT vector instruction
27995 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
27996 // split the vector, perform operation on it's Lo a Hi part and
27997 // concatenate the results.
27998 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
27999                                          const X86Subtarget &Subtarget) {
28000   assert(Op.getOpcode() == ISD::CTLZ);
28001   SDLoc dl(Op);
28002   MVT VT = Op.getSimpleValueType();
28003   MVT EltVT = VT.getVectorElementType();
28004   unsigned NumElems = VT.getVectorNumElements();
28005 
28006   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
28007           "Unsupported element type");
28008 
28009   // Split vector, it's Lo and Hi parts will be handled in next iteration.
28010   if (NumElems > 16 ||
28011       (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
28012     return splitVectorIntUnary(Op, DAG);
28013 
28014   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
28015   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
28016           "Unsupported value type for operation");
28017 
28018   // Use native supported vector instruction vplzcntd.
28019   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
28020   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
28021   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
28022   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
28023 
28024   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
28025 }
28026 
28027 // Lower CTLZ using a PSHUFB lookup table implementation.
28028 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
28029                                        const X86Subtarget &Subtarget,
28030                                        SelectionDAG &DAG) {
28031   MVT VT = Op.getSimpleValueType();
28032   int NumElts = VT.getVectorNumElements();
28033   int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
28034   MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
28035 
28036   // Per-nibble leading zero PSHUFB lookup table.
28037   const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
28038                        /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
28039                        /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
28040                        /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
28041 
28042   SmallVector<SDValue, 64> LUTVec;
28043   for (int i = 0; i < NumBytes; ++i)
28044     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
28045   SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
28046 
28047   // Begin by bitcasting the input to byte vector, then split those bytes
28048   // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
28049   // If the hi input nibble is zero then we add both results together, otherwise
28050   // we just take the hi result (by masking the lo result to zero before the
28051   // add).
28052   SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
28053   SDValue Zero = DAG.getConstant(0, DL, CurrVT);
28054 
28055   SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
28056   SDValue Lo = Op0;
28057   SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
28058   SDValue HiZ;
28059   if (CurrVT.is512BitVector()) {
28060     MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
28061     HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
28062     HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
28063   } else {
28064     HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
28065   }
28066 
28067   Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
28068   Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
28069   Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
28070   SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
28071 
28072   // Merge result back from vXi8 back to VT, working on the lo/hi halves
28073   // of the current vector width in the same way we did for the nibbles.
28074   // If the upper half of the input element is zero then add the halves'
28075   // leading zero counts together, otherwise just use the upper half's.
28076   // Double the width of the result until we are at target width.
28077   while (CurrVT != VT) {
28078     int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
28079     int CurrNumElts = CurrVT.getVectorNumElements();
28080     MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
28081     MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
28082     SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
28083 
28084     // Check if the upper half of the input element is zero.
28085     if (CurrVT.is512BitVector()) {
28086       MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
28087       HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
28088                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
28089       HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
28090     } else {
28091       HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
28092                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
28093     }
28094     HiZ = DAG.getBitcast(NextVT, HiZ);
28095 
28096     // Move the upper/lower halves to the lower bits as we'll be extending to
28097     // NextVT. Mask the lower result to zero if HiZ is true and add the results
28098     // together.
28099     SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
28100     SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
28101     SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
28102     R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
28103     Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
28104     CurrVT = NextVT;
28105   }
28106 
28107   return Res;
28108 }
28109 
28110 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
28111                                const X86Subtarget &Subtarget,
28112                                SelectionDAG &DAG) {
28113   MVT VT = Op.getSimpleValueType();
28114 
28115   if (Subtarget.hasCDI() &&
28116       // vXi8 vectors need to be promoted to 512-bits for vXi32.
28117       (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
28118     return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
28119 
28120   // Decompose 256-bit ops into smaller 128-bit ops.
28121   if (VT.is256BitVector() && !Subtarget.hasInt256())
28122     return splitVectorIntUnary(Op, DAG);
28123 
28124   // Decompose 512-bit ops into smaller 256-bit ops.
28125   if (VT.is512BitVector() && !Subtarget.hasBWI())
28126     return splitVectorIntUnary(Op, DAG);
28127 
28128   assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
28129   return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
28130 }
28131 
28132 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
28133                          SelectionDAG &DAG) {
28134   MVT VT = Op.getSimpleValueType();
28135   MVT OpVT = VT;
28136   unsigned NumBits = VT.getSizeInBits();
28137   SDLoc dl(Op);
28138   unsigned Opc = Op.getOpcode();
28139 
28140   if (VT.isVector())
28141     return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
28142 
28143   Op = Op.getOperand(0);
28144   if (VT == MVT::i8) {
28145     // Zero extend to i32 since there is not an i8 bsr.
28146     OpVT = MVT::i32;
28147     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
28148   }
28149 
28150   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
28151   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
28152   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
28153 
28154   if (Opc == ISD::CTLZ) {
28155     // If src is zero (i.e. bsr sets ZF), returns NumBits.
28156     SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
28157                      DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
28158                      Op.getValue(1)};
28159     Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
28160   }
28161 
28162   // Finally xor with NumBits-1.
28163   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
28164                    DAG.getConstant(NumBits - 1, dl, OpVT));
28165 
28166   if (VT == MVT::i8)
28167     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
28168   return Op;
28169 }
28170 
28171 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
28172                          SelectionDAG &DAG) {
28173   MVT VT = Op.getSimpleValueType();
28174   unsigned NumBits = VT.getScalarSizeInBits();
28175   SDValue N0 = Op.getOperand(0);
28176   SDLoc dl(Op);
28177 
28178   assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
28179          "Only scalar CTTZ requires custom lowering");
28180 
28181   // Issue a bsf (scan bits forward) which also sets EFLAGS.
28182   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
28183   Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
28184 
28185   // If src is zero (i.e. bsf sets ZF), returns NumBits.
28186   SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
28187                    DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
28188                    Op.getValue(1)};
28189   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
28190 }
28191 
28192 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
28193                            const X86Subtarget &Subtarget) {
28194   MVT VT = Op.getSimpleValueType();
28195   if (VT == MVT::i16 || VT == MVT::i32)
28196     return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
28197 
28198   if (VT == MVT::v32i16 || VT == MVT::v64i8)
28199     return splitVectorIntBinary(Op, DAG);
28200 
28201   assert(Op.getSimpleValueType().is256BitVector() &&
28202          Op.getSimpleValueType().isInteger() &&
28203          "Only handle AVX 256-bit vector integer operation");
28204   return splitVectorIntBinary(Op, DAG);
28205 }
28206 
28207 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
28208                                   const X86Subtarget &Subtarget) {
28209   MVT VT = Op.getSimpleValueType();
28210   SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
28211   unsigned Opcode = Op.getOpcode();
28212   SDLoc DL(Op);
28213 
28214   if (VT == MVT::v32i16 || VT == MVT::v64i8 ||
28215       (VT.is256BitVector() && !Subtarget.hasInt256())) {
28216     assert(Op.getSimpleValueType().isInteger() &&
28217            "Only handle AVX vector integer operation");
28218     return splitVectorIntBinary(Op, DAG);
28219   }
28220 
28221   // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
28222   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28223   EVT SetCCResultType =
28224       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
28225 
28226   unsigned BitWidth = VT.getScalarSizeInBits();
28227   if (Opcode == ISD::USUBSAT) {
28228     if (!TLI.isOperationLegal(ISD::UMAX, VT) || useVPTERNLOG(Subtarget, VT)) {
28229       // Handle a special-case with a bit-hack instead of cmp+select:
28230       // usubsat X, SMIN --> (X ^ SMIN) & (X s>> BW-1)
28231       // If the target can use VPTERNLOG, DAGToDAG will match this as
28232       // "vpsra + vpternlog" which is better than "vpmax + vpsub" with a
28233       // "broadcast" constant load.
28234       ConstantSDNode *C = isConstOrConstSplat(Y, true);
28235       if (C && C->getAPIntValue().isSignMask()) {
28236         SDValue SignMask = DAG.getConstant(C->getAPIntValue(), DL, VT);
28237         SDValue ShiftAmt = DAG.getConstant(BitWidth - 1, DL, VT);
28238         SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, SignMask);
28239         SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShiftAmt);
28240         return DAG.getNode(ISD::AND, DL, VT, Xor, Sra);
28241       }
28242     }
28243     if (!TLI.isOperationLegal(ISD::UMAX, VT)) {
28244       // usubsat X, Y --> (X >u Y) ? X - Y : 0
28245       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
28246       SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
28247       // TODO: Move this to DAGCombiner?
28248       if (SetCCResultType == VT &&
28249           DAG.ComputeNumSignBits(Cmp) == VT.getScalarSizeInBits())
28250         return DAG.getNode(ISD::AND, DL, VT, Cmp, Sub);
28251       return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
28252     }
28253   }
28254 
28255   if ((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
28256       (!VT.isVector() || VT == MVT::v2i64)) {
28257     APInt MinVal = APInt::getSignedMinValue(BitWidth);
28258     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
28259     SDValue Zero = DAG.getConstant(0, DL, VT);
28260     SDValue Result =
28261         DAG.getNode(Opcode == ISD::SADDSAT ? ISD::SADDO : ISD::SSUBO, DL,
28262                     DAG.getVTList(VT, SetCCResultType), X, Y);
28263     SDValue SumDiff = Result.getValue(0);
28264     SDValue Overflow = Result.getValue(1);
28265     SDValue SatMin = DAG.getConstant(MinVal, DL, VT);
28266     SDValue SatMax = DAG.getConstant(MaxVal, DL, VT);
28267     SDValue SumNeg =
28268         DAG.getSetCC(DL, SetCCResultType, SumDiff, Zero, ISD::SETLT);
28269     Result = DAG.getSelect(DL, VT, SumNeg, SatMax, SatMin);
28270     return DAG.getSelect(DL, VT, Overflow, Result, SumDiff);
28271   }
28272 
28273   // Use default expansion.
28274   return SDValue();
28275 }
28276 
28277 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
28278                         SelectionDAG &DAG) {
28279   MVT VT = Op.getSimpleValueType();
28280   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
28281     // Since X86 does not have CMOV for 8-bit integer, we don't convert
28282     // 8-bit integer abs to NEG and CMOV.
28283     SDLoc DL(Op);
28284     SDValue N0 = Op.getOperand(0);
28285     SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
28286                               DAG.getConstant(0, DL, VT), N0);
28287     SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_NS, DL, MVT::i8),
28288                      SDValue(Neg.getNode(), 1)};
28289     return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
28290   }
28291 
28292   // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
28293   if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
28294     SDLoc DL(Op);
28295     SDValue Src = Op.getOperand(0);
28296     SDValue Sub =
28297         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
28298     return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
28299   }
28300 
28301   if (VT.is256BitVector() && !Subtarget.hasInt256()) {
28302     assert(VT.isInteger() &&
28303            "Only handle AVX 256-bit vector integer operation");
28304     return splitVectorIntUnary(Op, DAG);
28305   }
28306 
28307   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28308     return splitVectorIntUnary(Op, DAG);
28309 
28310   // Default to expand.
28311   return SDValue();
28312 }
28313 
28314 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
28315   MVT VT = Op.getSimpleValueType();
28316 
28317   // For AVX1 cases, split to use legal ops (everything but v4i64).
28318   if (VT.getScalarType() != MVT::i64 && VT.is256BitVector())
28319     return splitVectorIntBinary(Op, DAG);
28320 
28321   if (VT == MVT::v32i16 || VT == MVT::v64i8)
28322     return splitVectorIntBinary(Op, DAG);
28323 
28324   // Default to expand.
28325   return SDValue();
28326 }
28327 
28328 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
28329                         SelectionDAG &DAG) {
28330   SDLoc dl(Op);
28331   MVT VT = Op.getSimpleValueType();
28332 
28333   // Decompose 256-bit ops into 128-bit ops.
28334   if (VT.is256BitVector() && !Subtarget.hasInt256())
28335     return splitVectorIntBinary(Op, DAG);
28336 
28337   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28338     return splitVectorIntBinary(Op, DAG);
28339 
28340   SDValue A = Op.getOperand(0);
28341   SDValue B = Op.getOperand(1);
28342 
28343   // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
28344   // vector pairs, multiply and truncate.
28345   if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
28346     unsigned NumElts = VT.getVectorNumElements();
28347 
28348     if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
28349         (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
28350       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
28351       return DAG.getNode(
28352           ISD::TRUNCATE, dl, VT,
28353           DAG.getNode(ISD::MUL, dl, ExVT,
28354                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
28355                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
28356     }
28357 
28358     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28359 
28360     // Extract the lo/hi parts to any extend to i16.
28361     // We're going to mask off the low byte of each result element of the
28362     // pmullw, so it doesn't matter what's in the high byte of each 16-bit
28363     // element.
28364     SDValue Undef = DAG.getUNDEF(VT);
28365     SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
28366     SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
28367 
28368     SDValue BLo, BHi;
28369     if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
28370       // If the RHS is a constant, manually unpackl/unpackh.
28371       SmallVector<SDValue, 16> LoOps, HiOps;
28372       for (unsigned i = 0; i != NumElts; i += 16) {
28373         for (unsigned j = 0; j != 8; ++j) {
28374           LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
28375                                                MVT::i16));
28376           HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
28377                                                MVT::i16));
28378         }
28379       }
28380 
28381       BLo = DAG.getBuildVector(ExVT, dl, LoOps);
28382       BHi = DAG.getBuildVector(ExVT, dl, HiOps);
28383     } else {
28384       BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
28385       BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
28386     }
28387 
28388     // Multiply, mask the lower 8bits of the lo/hi results and pack.
28389     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
28390     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
28391     return getPack(DAG, Subtarget, dl, VT, RLo, RHi);
28392   }
28393 
28394   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
28395   if (VT == MVT::v4i32) {
28396     assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
28397            "Should not custom lower when pmulld is available!");
28398 
28399     // Extract the odd parts.
28400     static const int UnpackMask[] = { 1, -1, 3, -1 };
28401     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
28402     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
28403 
28404     // Multiply the even parts.
28405     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
28406                                 DAG.getBitcast(MVT::v2i64, A),
28407                                 DAG.getBitcast(MVT::v2i64, B));
28408     // Now multiply odd parts.
28409     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
28410                                DAG.getBitcast(MVT::v2i64, Aodds),
28411                                DAG.getBitcast(MVT::v2i64, Bodds));
28412 
28413     Evens = DAG.getBitcast(VT, Evens);
28414     Odds = DAG.getBitcast(VT, Odds);
28415 
28416     // Merge the two vectors back together with a shuffle. This expands into 2
28417     // shuffles.
28418     static const int ShufMask[] = { 0, 4, 2, 6 };
28419     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
28420   }
28421 
28422   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
28423          "Only know how to lower V2I64/V4I64/V8I64 multiply");
28424   assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
28425 
28426   //  Ahi = psrlqi(a, 32);
28427   //  Bhi = psrlqi(b, 32);
28428   //
28429   //  AloBlo = pmuludq(a, b);
28430   //  AloBhi = pmuludq(a, Bhi);
28431   //  AhiBlo = pmuludq(Ahi, b);
28432   //
28433   //  Hi = psllqi(AloBhi + AhiBlo, 32);
28434   //  return AloBlo + Hi;
28435   KnownBits AKnown = DAG.computeKnownBits(A);
28436   KnownBits BKnown = DAG.computeKnownBits(B);
28437 
28438   APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
28439   bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
28440   bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
28441 
28442   APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
28443   bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
28444   bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
28445 
28446   SDValue Zero = DAG.getConstant(0, dl, VT);
28447 
28448   // Only multiply lo/hi halves that aren't known to be zero.
28449   SDValue AloBlo = Zero;
28450   if (!ALoIsZero && !BLoIsZero)
28451     AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
28452 
28453   SDValue AloBhi = Zero;
28454   if (!ALoIsZero && !BHiIsZero) {
28455     SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
28456     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
28457   }
28458 
28459   SDValue AhiBlo = Zero;
28460   if (!AHiIsZero && !BLoIsZero) {
28461     SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
28462     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
28463   }
28464 
28465   SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
28466   Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
28467 
28468   return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
28469 }
28470 
28471 static SDValue LowervXi8MulWithUNPCK(SDValue A, SDValue B, const SDLoc &dl,
28472                                      MVT VT, bool IsSigned,
28473                                      const X86Subtarget &Subtarget,
28474                                      SelectionDAG &DAG,
28475                                      SDValue *Low = nullptr) {
28476   unsigned NumElts = VT.getVectorNumElements();
28477 
28478   // For vXi8 we will unpack the low and high half of each 128 bit lane to widen
28479   // to a vXi16 type. Do the multiplies, shift the results and pack the half
28480   // lane results back together.
28481 
28482   // We'll take different approaches for signed and unsigned.
28483   // For unsigned we'll use punpcklbw/punpckhbw to put zero extend the bytes
28484   // and use pmullw to calculate the full 16-bit product.
28485   // For signed we'll use punpcklbw/punpckbw to extend the bytes to words and
28486   // shift them left into the upper byte of each word. This allows us to use
28487   // pmulhw to calculate the full 16-bit product. This trick means we don't
28488   // need to sign extend the bytes to use pmullw.
28489 
28490   MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28491   SDValue Zero = DAG.getConstant(0, dl, VT);
28492 
28493   SDValue ALo, AHi;
28494   if (IsSigned) {
28495     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, A));
28496     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, A));
28497   } else {
28498     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Zero));
28499     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Zero));
28500   }
28501 
28502   SDValue BLo, BHi;
28503   if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
28504     // If the RHS is a constant, manually unpackl/unpackh and extend.
28505     SmallVector<SDValue, 16> LoOps, HiOps;
28506     for (unsigned i = 0; i != NumElts; i += 16) {
28507       for (unsigned j = 0; j != 8; ++j) {
28508         SDValue LoOp = B.getOperand(i + j);
28509         SDValue HiOp = B.getOperand(i + j + 8);
28510 
28511         if (IsSigned) {
28512           LoOp = DAG.getAnyExtOrTrunc(LoOp, dl, MVT::i16);
28513           HiOp = DAG.getAnyExtOrTrunc(HiOp, dl, MVT::i16);
28514           LoOp = DAG.getNode(ISD::SHL, dl, MVT::i16, LoOp,
28515                              DAG.getConstant(8, dl, MVT::i16));
28516           HiOp = DAG.getNode(ISD::SHL, dl, MVT::i16, HiOp,
28517                              DAG.getConstant(8, dl, MVT::i16));
28518         } else {
28519           LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
28520           HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
28521         }
28522 
28523         LoOps.push_back(LoOp);
28524         HiOps.push_back(HiOp);
28525       }
28526     }
28527 
28528     BLo = DAG.getBuildVector(ExVT, dl, LoOps);
28529     BHi = DAG.getBuildVector(ExVT, dl, HiOps);
28530   } else if (IsSigned) {
28531     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, B));
28532     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, B));
28533   } else {
28534     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Zero));
28535     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Zero));
28536   }
28537 
28538   // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
28539   // pack back to vXi8.
28540   unsigned MulOpc = IsSigned ? ISD::MULHS : ISD::MUL;
28541   SDValue RLo = DAG.getNode(MulOpc, dl, ExVT, ALo, BLo);
28542   SDValue RHi = DAG.getNode(MulOpc, dl, ExVT, AHi, BHi);
28543 
28544   if (Low)
28545     *Low = getPack(DAG, Subtarget, dl, VT, RLo, RHi);
28546 
28547   return getPack(DAG, Subtarget, dl, VT, RLo, RHi, /*PackHiHalf*/ true);
28548 }
28549 
28550 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
28551                          SelectionDAG &DAG) {
28552   SDLoc dl(Op);
28553   MVT VT = Op.getSimpleValueType();
28554   bool IsSigned = Op->getOpcode() == ISD::MULHS;
28555   unsigned NumElts = VT.getVectorNumElements();
28556   SDValue A = Op.getOperand(0);
28557   SDValue B = Op.getOperand(1);
28558 
28559   // Decompose 256-bit ops into 128-bit ops.
28560   if (VT.is256BitVector() && !Subtarget.hasInt256())
28561     return splitVectorIntBinary(Op, DAG);
28562 
28563   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28564     return splitVectorIntBinary(Op, DAG);
28565 
28566   if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
28567     assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
28568            (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
28569            (VT == MVT::v16i32 && Subtarget.hasAVX512()));
28570 
28571     // PMULxD operations multiply each even value (starting at 0) of LHS with
28572     // the related value of RHS and produce a widen result.
28573     // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
28574     // => <2 x i64> <ae|cg>
28575     //
28576     // In other word, to have all the results, we need to perform two PMULxD:
28577     // 1. one with the even values.
28578     // 2. one with the odd values.
28579     // To achieve #2, with need to place the odd values at an even position.
28580     //
28581     // Place the odd value at an even position (basically, shift all values 1
28582     // step to the left):
28583     const int Mask[] = {1, -1,  3, -1,  5, -1,  7, -1,
28584                         9, -1, 11, -1, 13, -1, 15, -1};
28585     // <a|b|c|d> => <b|undef|d|undef>
28586     SDValue Odd0 = DAG.getVectorShuffle(VT, dl, A, A,
28587                                         makeArrayRef(&Mask[0], NumElts));
28588     // <e|f|g|h> => <f|undef|h|undef>
28589     SDValue Odd1 = DAG.getVectorShuffle(VT, dl, B, B,
28590                                         makeArrayRef(&Mask[0], NumElts));
28591 
28592     // Emit two multiplies, one for the lower 2 ints and one for the higher 2
28593     // ints.
28594     MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
28595     unsigned Opcode =
28596         (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
28597     // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
28598     // => <2 x i64> <ae|cg>
28599     SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
28600                                                   DAG.getBitcast(MulVT, A),
28601                                                   DAG.getBitcast(MulVT, B)));
28602     // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
28603     // => <2 x i64> <bf|dh>
28604     SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
28605                                                   DAG.getBitcast(MulVT, Odd0),
28606                                                   DAG.getBitcast(MulVT, Odd1)));
28607 
28608     // Shuffle it back into the right order.
28609     SmallVector<int, 16> ShufMask(NumElts);
28610     for (int i = 0; i != (int)NumElts; ++i)
28611       ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
28612 
28613     SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
28614 
28615     // If we have a signed multiply but no PMULDQ fix up the result of an
28616     // unsigned multiply.
28617     if (IsSigned && !Subtarget.hasSSE41()) {
28618       SDValue Zero = DAG.getConstant(0, dl, VT);
28619       SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
28620                                DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
28621       SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
28622                                DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
28623 
28624       SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
28625       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
28626     }
28627 
28628     return Res;
28629   }
28630 
28631   // Only i8 vectors should need custom lowering after this.
28632   assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
28633          (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
28634          "Unsupported vector type");
28635 
28636   // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
28637   // logical shift down the upper half and pack back to i8.
28638 
28639   // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
28640   // and then ashr/lshr the upper bits down to the lower bits before multiply.
28641 
28642   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
28643       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
28644     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
28645     unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
28646     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
28647     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
28648     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
28649     Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
28650     return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
28651   }
28652 
28653   return LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG);
28654 }
28655 
28656 // Custom lowering for SMULO/UMULO.
28657 static SDValue LowerMULO(SDValue Op, const X86Subtarget &Subtarget,
28658                          SelectionDAG &DAG) {
28659   MVT VT = Op.getSimpleValueType();
28660 
28661   // Scalars defer to LowerXALUO.
28662   if (!VT.isVector())
28663     return LowerXALUO(Op, DAG);
28664 
28665   SDLoc dl(Op);
28666   bool IsSigned = Op->getOpcode() == ISD::SMULO;
28667   SDValue A = Op.getOperand(0);
28668   SDValue B = Op.getOperand(1);
28669   EVT OvfVT = Op->getValueType(1);
28670 
28671   if ((VT == MVT::v32i8 && !Subtarget.hasInt256()) ||
28672       (VT == MVT::v64i8 && !Subtarget.hasBWI())) {
28673     // Extract the LHS Lo/Hi vectors
28674     SDValue LHSLo, LHSHi;
28675     std::tie(LHSLo, LHSHi) = splitVector(A, DAG, dl);
28676 
28677     // Extract the RHS Lo/Hi vectors
28678     SDValue RHSLo, RHSHi;
28679     std::tie(RHSLo, RHSHi) = splitVector(B, DAG, dl);
28680 
28681     EVT LoOvfVT, HiOvfVT;
28682     std::tie(LoOvfVT, HiOvfVT) = DAG.GetSplitDestVTs(OvfVT);
28683     SDVTList LoVTs = DAG.getVTList(LHSLo.getValueType(), LoOvfVT);
28684     SDVTList HiVTs = DAG.getVTList(LHSHi.getValueType(), HiOvfVT);
28685 
28686     // Issue the split operations.
28687     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, LoVTs, LHSLo, RHSLo);
28688     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, HiVTs, LHSHi, RHSHi);
28689 
28690     // Join the separate data results and the overflow results.
28691     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
28692     SDValue Ovf = DAG.getNode(ISD::CONCAT_VECTORS, dl, OvfVT, Lo.getValue(1),
28693                               Hi.getValue(1));
28694 
28695     return DAG.getMergeValues({Res, Ovf}, dl);
28696   }
28697 
28698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28699   EVT SetccVT =
28700       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
28701 
28702   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
28703       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
28704     unsigned NumElts = VT.getVectorNumElements();
28705     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
28706     unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
28707     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
28708     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
28709     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
28710 
28711     SDValue Low = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
28712 
28713     SDValue Ovf;
28714     if (IsSigned) {
28715       SDValue High, LowSign;
28716       if (OvfVT.getVectorElementType() == MVT::i1 &&
28717           (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
28718         // Rather the truncating try to do the compare on vXi16 or vXi32.
28719         // Shift the high down filling with sign bits.
28720         High = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Mul, 8, DAG);
28721         // Fill all 16 bits with the sign bit from the low.
28722         LowSign =
28723             getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExVT, Mul, 8, DAG);
28724         LowSign = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, LowSign,
28725                                              15, DAG);
28726         SetccVT = OvfVT;
28727         if (!Subtarget.hasBWI()) {
28728           // We can't do a vXi16 compare so sign extend to v16i32.
28729           High = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, High);
28730           LowSign = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, LowSign);
28731         }
28732       } else {
28733         // Otherwise do the compare at vXi8.
28734         High = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
28735         High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
28736         LowSign =
28737             DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
28738       }
28739 
28740       Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
28741     } else {
28742       SDValue High =
28743           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
28744       if (OvfVT.getVectorElementType() == MVT::i1 &&
28745           (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
28746         // Rather the truncating try to do the compare on vXi16 or vXi32.
28747         SetccVT = OvfVT;
28748         if (!Subtarget.hasBWI()) {
28749           // We can't do a vXi16 compare so sign extend to v16i32.
28750           High = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, High);
28751         }
28752       } else {
28753         // Otherwise do the compare at vXi8.
28754         High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
28755       }
28756 
28757       Ovf =
28758           DAG.getSetCC(dl, SetccVT, High,
28759                        DAG.getConstant(0, dl, High.getValueType()), ISD::SETNE);
28760     }
28761 
28762     Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
28763 
28764     return DAG.getMergeValues({Low, Ovf}, dl);
28765   }
28766 
28767   SDValue Low;
28768   SDValue High =
28769       LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG, &Low);
28770 
28771   SDValue Ovf;
28772   if (IsSigned) {
28773     // SMULO overflows if the high bits don't match the sign of the low.
28774     SDValue LowSign =
28775         DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
28776     Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
28777   } else {
28778     // UMULO overflows if the high bits are non-zero.
28779     Ovf =
28780         DAG.getSetCC(dl, SetccVT, High, DAG.getConstant(0, dl, VT), ISD::SETNE);
28781   }
28782 
28783   Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
28784 
28785   return DAG.getMergeValues({Low, Ovf}, dl);
28786 }
28787 
28788 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
28789   assert(Subtarget.isTargetWin64() && "Unexpected target");
28790   EVT VT = Op.getValueType();
28791   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
28792          "Unexpected return type for lowering");
28793 
28794   RTLIB::Libcall LC;
28795   bool isSigned;
28796   switch (Op->getOpcode()) {
28797   default: llvm_unreachable("Unexpected request for libcall!");
28798   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
28799   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
28800   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
28801   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
28802   }
28803 
28804   SDLoc dl(Op);
28805   SDValue InChain = DAG.getEntryNode();
28806 
28807   TargetLowering::ArgListTy Args;
28808   TargetLowering::ArgListEntry Entry;
28809   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
28810     EVT ArgVT = Op->getOperand(i).getValueType();
28811     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
28812            "Unexpected argument type for lowering");
28813     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
28814     int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
28815     MachinePointerInfo MPI =
28816         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
28817     Entry.Node = StackPtr;
28818     InChain =
28819         DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MPI, Align(16));
28820     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
28821     Entry.Ty = PointerType::get(ArgTy,0);
28822     Entry.IsSExt = false;
28823     Entry.IsZExt = false;
28824     Args.push_back(Entry);
28825   }
28826 
28827   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
28828                                          getPointerTy(DAG.getDataLayout()));
28829 
28830   TargetLowering::CallLoweringInfo CLI(DAG);
28831   CLI.setDebugLoc(dl)
28832       .setChain(InChain)
28833       .setLibCallee(
28834           getLibcallCallingConv(LC),
28835           static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
28836           std::move(Args))
28837       .setInRegister()
28838       .setSExtResult(isSigned)
28839       .setZExtResult(!isSigned);
28840 
28841   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
28842   return DAG.getBitcast(VT, CallInfo.first);
28843 }
28844 
28845 SDValue X86TargetLowering::LowerWin64_FP_TO_INT128(SDValue Op,
28846                                                    SelectionDAG &DAG,
28847                                                    SDValue &Chain) const {
28848   assert(Subtarget.isTargetWin64() && "Unexpected target");
28849   EVT VT = Op.getValueType();
28850   bool IsStrict = Op->isStrictFPOpcode();
28851 
28852   SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
28853   EVT ArgVT = Arg.getValueType();
28854 
28855   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
28856          "Unexpected return type for lowering");
28857 
28858   RTLIB::Libcall LC;
28859   if (Op->getOpcode() == ISD::FP_TO_SINT ||
28860       Op->getOpcode() == ISD::STRICT_FP_TO_SINT)
28861     LC = RTLIB::getFPTOSINT(ArgVT, VT);
28862   else
28863     LC = RTLIB::getFPTOUINT(ArgVT, VT);
28864   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
28865 
28866   SDLoc dl(Op);
28867   MakeLibCallOptions CallOptions;
28868   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
28869 
28870   SDValue Result;
28871   // Expect the i128 argument returned as a v2i64 in xmm0, cast back to the
28872   // expected VT (i128).
28873   std::tie(Result, Chain) =
28874       makeLibCall(DAG, LC, MVT::v2i64, Arg, CallOptions, dl, Chain);
28875   Result = DAG.getBitcast(VT, Result);
28876   return Result;
28877 }
28878 
28879 SDValue X86TargetLowering::LowerWin64_INT128_TO_FP(SDValue Op,
28880                                                    SelectionDAG &DAG) const {
28881   assert(Subtarget.isTargetWin64() && "Unexpected target");
28882   EVT VT = Op.getValueType();
28883   bool IsStrict = Op->isStrictFPOpcode();
28884 
28885   SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
28886   EVT ArgVT = Arg.getValueType();
28887 
28888   assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
28889          "Unexpected argument type for lowering");
28890 
28891   RTLIB::Libcall LC;
28892   if (Op->getOpcode() == ISD::SINT_TO_FP ||
28893       Op->getOpcode() == ISD::STRICT_SINT_TO_FP)
28894     LC = RTLIB::getSINTTOFP(ArgVT, VT);
28895   else
28896     LC = RTLIB::getUINTTOFP(ArgVT, VT);
28897   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
28898 
28899   SDLoc dl(Op);
28900   MakeLibCallOptions CallOptions;
28901   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
28902 
28903   // Pass the i128 argument as an indirect argument on the stack.
28904   SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
28905   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
28906   MachinePointerInfo MPI =
28907       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
28908   Chain = DAG.getStore(Chain, dl, Arg, StackPtr, MPI, Align(16));
28909 
28910   SDValue Result;
28911   std::tie(Result, Chain) =
28912       makeLibCall(DAG, LC, VT, StackPtr, CallOptions, dl, Chain);
28913   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
28914 }
28915 
28916 // Return true if the required (according to Opcode) shift-imm form is natively
28917 // supported by the Subtarget
28918 static bool supportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
28919                                         unsigned Opcode) {
28920   if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
28921     return false;
28922 
28923   if (VT.getScalarSizeInBits() < 16)
28924     return false;
28925 
28926   if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
28927       (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
28928     return true;
28929 
28930   bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
28931                 (VT.is256BitVector() && Subtarget.hasInt256());
28932 
28933   bool AShift = LShift && (Subtarget.hasAVX512() ||
28934                            (VT != MVT::v2i64 && VT != MVT::v4i64));
28935   return (Opcode == ISD::SRA) ? AShift : LShift;
28936 }
28937 
28938 // The shift amount is a variable, but it is the same for all vector lanes.
28939 // These instructions are defined together with shift-immediate.
28940 static
28941 bool supportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
28942                                       unsigned Opcode) {
28943   return supportedVectorShiftWithImm(VT, Subtarget, Opcode);
28944 }
28945 
28946 // Return true if the required (according to Opcode) variable-shift form is
28947 // natively supported by the Subtarget
28948 static bool supportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
28949                                     unsigned Opcode) {
28950   if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
28951     return false;
28952 
28953   if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
28954     return false;
28955 
28956   // vXi16 supported only on AVX-512, BWI
28957   if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
28958     return false;
28959 
28960   if (Subtarget.hasAVX512() &&
28961       (Subtarget.useAVX512Regs() || !VT.is512BitVector()))
28962     return true;
28963 
28964   bool LShift = VT.is128BitVector() || VT.is256BitVector();
28965   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
28966   return (Opcode == ISD::SRA) ? AShift : LShift;
28967 }
28968 
28969 static SDValue LowerShiftByScalarImmediate(SDValue Op, SelectionDAG &DAG,
28970                                            const X86Subtarget &Subtarget) {
28971   MVT VT = Op.getSimpleValueType();
28972   SDLoc dl(Op);
28973   SDValue R = Op.getOperand(0);
28974   SDValue Amt = Op.getOperand(1);
28975   unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
28976 
28977   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
28978     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
28979     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
28980     SDValue Ex = DAG.getBitcast(ExVT, R);
28981 
28982     // ashr(R, 63) === cmp_slt(R, 0)
28983     if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
28984       assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
28985              "Unsupported PCMPGT op");
28986       return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
28987     }
28988 
28989     if (ShiftAmt >= 32) {
28990       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
28991       SDValue Upper =
28992           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
28993       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
28994                                                  ShiftAmt - 32, DAG);
28995       if (VT == MVT::v2i64)
28996         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
28997       if (VT == MVT::v4i64)
28998         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
28999                                   {9, 1, 11, 3, 13, 5, 15, 7});
29000     } else {
29001       // SRA upper i32, SRL whole i64 and select lower i32.
29002       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
29003                                                  ShiftAmt, DAG);
29004       SDValue Lower =
29005           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
29006       Lower = DAG.getBitcast(ExVT, Lower);
29007       if (VT == MVT::v2i64)
29008         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
29009       if (VT == MVT::v4i64)
29010         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
29011                                   {8, 1, 10, 3, 12, 5, 14, 7});
29012     }
29013     return DAG.getBitcast(VT, Ex);
29014   };
29015 
29016   // Optimize shl/srl/sra with constant shift amount.
29017   APInt APIntShiftAmt;
29018   if (!X86::isConstantSplat(Amt, APIntShiftAmt))
29019     return SDValue();
29020 
29021   // If the shift amount is out of range, return undef.
29022   if (APIntShiftAmt.uge(VT.getScalarSizeInBits()))
29023     return DAG.getUNDEF(VT);
29024 
29025   uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
29026 
29027   if (supportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
29028     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
29029 
29030   // i64 SRA needs to be performed as partial shifts.
29031   if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
29032        (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
29033       Op.getOpcode() == ISD::SRA)
29034     return ArithmeticShiftRight64(ShiftAmt);
29035 
29036   if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
29037       (Subtarget.hasBWI() && VT == MVT::v64i8)) {
29038     unsigned NumElts = VT.getVectorNumElements();
29039     MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29040 
29041     // Simple i8 add case
29042     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1) {
29043       // R may be undef at run-time, but (shl R, 1) must be an even number (LSB
29044       // must be 0). (add undef, undef) however can be any value. To make this
29045       // safe, we must freeze R to ensure that register allocation uses the same
29046       // register for an undefined value. This ensures that the result will
29047       // still be even and preserves the original semantics.
29048       R = DAG.getNode(ISD::FREEZE, dl, VT, R);
29049       return DAG.getNode(ISD::ADD, dl, VT, R, R);
29050     }
29051 
29052     // ashr(R, 7)  === cmp_slt(R, 0)
29053     if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
29054       SDValue Zeros = DAG.getConstant(0, dl, VT);
29055       if (VT.is512BitVector()) {
29056         assert(VT == MVT::v64i8 && "Unexpected element type!");
29057         SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
29058         return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
29059       }
29060       return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
29061     }
29062 
29063     // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
29064     if (VT == MVT::v16i8 && Subtarget.hasXOP())
29065       return SDValue();
29066 
29067     if (Op.getOpcode() == ISD::SHL) {
29068       // Make a large shift.
29069       SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
29070                                                ShiftAmt, DAG);
29071       SHL = DAG.getBitcast(VT, SHL);
29072       // Zero out the rightmost bits.
29073       APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
29074       return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
29075     }
29076     if (Op.getOpcode() == ISD::SRL) {
29077       // Make a large shift.
29078       SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
29079                                                ShiftAmt, DAG);
29080       SRL = DAG.getBitcast(VT, SRL);
29081       // Zero out the leftmost bits.
29082       APInt Mask = APInt::getLowBitsSet(8, 8 - ShiftAmt);
29083       return DAG.getNode(ISD::AND, dl, VT, SRL, DAG.getConstant(Mask, dl, VT));
29084     }
29085     if (Op.getOpcode() == ISD::SRA) {
29086       // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
29087       SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
29088 
29089       SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
29090       Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
29091       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
29092       return Res;
29093     }
29094     llvm_unreachable("Unknown shift opcode.");
29095   }
29096 
29097   return SDValue();
29098 }
29099 
29100 static SDValue LowerShiftByScalarVariable(SDValue Op, SelectionDAG &DAG,
29101                                           const X86Subtarget &Subtarget) {
29102   MVT VT = Op.getSimpleValueType();
29103   SDLoc dl(Op);
29104   SDValue R = Op.getOperand(0);
29105   SDValue Amt = Op.getOperand(1);
29106   unsigned Opcode = Op.getOpcode();
29107   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
29108   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opcode, true);
29109 
29110   if (SDValue BaseShAmt = DAG.getSplatValue(Amt)) {
29111     if (supportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode)) {
29112       MVT EltVT = VT.getVectorElementType();
29113       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
29114       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
29115         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
29116       else if (EltVT.bitsLT(MVT::i32))
29117         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
29118 
29119       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, Subtarget, DAG);
29120     }
29121 
29122     // vXi8 shifts - shift as v8i16 + mask result.
29123     if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
29124          (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
29125          VT == MVT::v64i8) &&
29126         !Subtarget.hasXOP()) {
29127       unsigned NumElts = VT.getVectorNumElements();
29128       MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29129       if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
29130         unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
29131         unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
29132         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
29133 
29134         // Create the mask using vXi16 shifts. For shift-rights we need to move
29135         // the upper byte down before splatting the vXi8 mask.
29136         SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
29137         BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
29138                                       BaseShAmt, Subtarget, DAG);
29139         if (Opcode != ISD::SHL)
29140           BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
29141                                                8, DAG);
29142         BitMask = DAG.getBitcast(VT, BitMask);
29143         BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
29144                                        SmallVector<int, 64>(NumElts, 0));
29145 
29146         SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
29147                                           DAG.getBitcast(ExtVT, R), BaseShAmt,
29148                                           Subtarget, DAG);
29149         Res = DAG.getBitcast(VT, Res);
29150         Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
29151 
29152         if (Opcode == ISD::SRA) {
29153           // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
29154           // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
29155           SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
29156           SignMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask,
29157                                          BaseShAmt, Subtarget, DAG);
29158           SignMask = DAG.getBitcast(VT, SignMask);
29159           Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
29160           Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
29161         }
29162         return Res;
29163       }
29164     }
29165   }
29166 
29167   // Check cases (mainly 32-bit) where i64 is expanded into high and low parts.
29168   if (VT == MVT::v2i64 && Amt.getOpcode() == ISD::BITCAST &&
29169       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
29170     Amt = Amt.getOperand(0);
29171     unsigned Ratio = 64 / Amt.getScalarValueSizeInBits();
29172     std::vector<SDValue> Vals(Ratio);
29173     for (unsigned i = 0; i != Ratio; ++i)
29174       Vals[i] = Amt.getOperand(i);
29175     for (unsigned i = Ratio, e = Amt.getNumOperands(); i != e; i += Ratio) {
29176       for (unsigned j = 0; j != Ratio; ++j)
29177         if (Vals[j] != Amt.getOperand(i + j))
29178           return SDValue();
29179     }
29180 
29181     if (supportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
29182       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
29183   }
29184   return SDValue();
29185 }
29186 
29187 // Convert a shift/rotate left amount to a multiplication scale factor.
29188 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
29189                                        const X86Subtarget &Subtarget,
29190                                        SelectionDAG &DAG) {
29191   MVT VT = Amt.getSimpleValueType();
29192   if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
29193         (Subtarget.hasInt256() && VT == MVT::v16i16) ||
29194         (Subtarget.hasAVX512() && VT == MVT::v32i16) ||
29195         (!Subtarget.hasAVX512() && VT == MVT::v16i8) ||
29196         (Subtarget.hasInt256() && VT == MVT::v32i8) ||
29197         (Subtarget.hasBWI() && VT == MVT::v64i8)))
29198     return SDValue();
29199 
29200   MVT SVT = VT.getVectorElementType();
29201   unsigned SVTBits = SVT.getSizeInBits();
29202   unsigned NumElems = VT.getVectorNumElements();
29203 
29204   APInt UndefElts;
29205   SmallVector<APInt> EltBits;
29206   if (getTargetConstantBitsFromNode(Amt, SVTBits, UndefElts, EltBits)) {
29207     APInt One(SVTBits, 1);
29208     SmallVector<SDValue> Elts(NumElems, DAG.getUNDEF(SVT));
29209     for (unsigned I = 0; I != NumElems; ++I) {
29210       if (UndefElts[I] || EltBits[I].uge(SVTBits))
29211         continue;
29212       uint64_t ShAmt = EltBits[I].getZExtValue();
29213       Elts[I] = DAG.getConstant(One.shl(ShAmt), dl, SVT);
29214     }
29215     return DAG.getBuildVector(VT, dl, Elts);
29216   }
29217 
29218   // If the target doesn't support variable shifts, use either FP conversion
29219   // or integer multiplication to avoid shifting each element individually.
29220   if (VT == MVT::v4i32) {
29221     Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
29222     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
29223                       DAG.getConstant(0x3f800000U, dl, VT));
29224     Amt = DAG.getBitcast(MVT::v4f32, Amt);
29225     return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
29226   }
29227 
29228   // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
29229   if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
29230     SDValue Z = DAG.getConstant(0, dl, VT);
29231     SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
29232     SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
29233     Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
29234     Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
29235     if (Subtarget.hasSSE41())
29236       return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
29237     return getPack(DAG, Subtarget, dl, VT, Lo, Hi);
29238   }
29239 
29240   return SDValue();
29241 }
29242 
29243 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
29244                           SelectionDAG &DAG) {
29245   MVT VT = Op.getSimpleValueType();
29246   SDLoc dl(Op);
29247   SDValue R = Op.getOperand(0);
29248   SDValue Amt = Op.getOperand(1);
29249   unsigned EltSizeInBits = VT.getScalarSizeInBits();
29250   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29251 
29252   unsigned Opc = Op.getOpcode();
29253   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
29254   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
29255 
29256   assert(VT.isVector() && "Custom lowering only for vector shifts!");
29257   assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
29258 
29259   if (SDValue V = LowerShiftByScalarImmediate(Op, DAG, Subtarget))
29260     return V;
29261 
29262   if (SDValue V = LowerShiftByScalarVariable(Op, DAG, Subtarget))
29263     return V;
29264 
29265   if (supportedVectorVarShift(VT, Subtarget, Opc))
29266     return Op;
29267 
29268   // i64 vector arithmetic shift can be emulated with the transform:
29269   // M = lshr(SIGN_MASK, Amt)
29270   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
29271   if (((VT == MVT::v2i64 && !Subtarget.hasXOP()) ||
29272        (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
29273       Opc == ISD::SRA) {
29274     SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
29275     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
29276     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
29277     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
29278     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
29279     return R;
29280   }
29281 
29282   // XOP has 128-bit variable logical/arithmetic shifts.
29283   // +ve/-ve Amt = shift left/right.
29284   if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
29285                              VT == MVT::v8i16 || VT == MVT::v16i8)) {
29286     if (Opc == ISD::SRL || Opc == ISD::SRA) {
29287       SDValue Zero = DAG.getConstant(0, dl, VT);
29288       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
29289     }
29290     if (Opc == ISD::SHL || Opc == ISD::SRL)
29291       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
29292     if (Opc == ISD::SRA)
29293       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
29294   }
29295 
29296   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
29297   // shifts per-lane and then shuffle the partial results back together.
29298   if (VT == MVT::v2i64 && Opc != ISD::SRA) {
29299     // Splat the shift amounts so the scalar shifts above will catch it.
29300     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
29301     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
29302     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
29303     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
29304     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
29305   }
29306 
29307   // If possible, lower this shift as a sequence of two shifts by
29308   // constant plus a BLENDing shuffle instead of scalarizing it.
29309   // Example:
29310   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
29311   //
29312   // Could be rewritten as:
29313   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
29314   //
29315   // The advantage is that the two shifts from the example would be
29316   // lowered as X86ISD::VSRLI nodes in parallel before blending.
29317   if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
29318                       (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
29319     SDValue Amt1, Amt2;
29320     unsigned NumElts = VT.getVectorNumElements();
29321     SmallVector<int, 8> ShuffleMask;
29322     for (unsigned i = 0; i != NumElts; ++i) {
29323       SDValue A = Amt->getOperand(i);
29324       if (A.isUndef()) {
29325         ShuffleMask.push_back(SM_SentinelUndef);
29326         continue;
29327       }
29328       if (!Amt1 || Amt1 == A) {
29329         ShuffleMask.push_back(i);
29330         Amt1 = A;
29331         continue;
29332       }
29333       if (!Amt2 || Amt2 == A) {
29334         ShuffleMask.push_back(i + NumElts);
29335         Amt2 = A;
29336         continue;
29337       }
29338       break;
29339     }
29340 
29341     // Only perform this blend if we can perform it without loading a mask.
29342     if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
29343         (VT != MVT::v16i16 ||
29344          is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
29345         (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
29346          canWidenShuffleElements(ShuffleMask))) {
29347       auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
29348       auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
29349       if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
29350           Cst2->getAPIntValue().ult(EltSizeInBits)) {
29351         SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
29352                                                     Cst1->getZExtValue(), DAG);
29353         SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
29354                                                     Cst2->getZExtValue(), DAG);
29355         return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
29356       }
29357     }
29358   }
29359 
29360   // If possible, lower this packed shift into a vector multiply instead of
29361   // expanding it into a sequence of scalar shifts.
29362   // For v32i8 cases, it might be quicker to split/extend to vXi16 shifts.
29363   if (Opc == ISD::SHL && !(VT == MVT::v32i8 && (Subtarget.hasXOP() ||
29364                                                 Subtarget.canExtendTo512BW())))
29365     if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
29366       return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
29367 
29368   // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
29369   // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
29370   if (Opc == ISD::SRL && ConstantAmt &&
29371       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
29372     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
29373     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
29374     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
29375       SDValue Zero = DAG.getConstant(0, dl, VT);
29376       SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
29377       SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
29378       return DAG.getSelect(dl, VT, ZAmt, R, Res);
29379     }
29380   }
29381 
29382   // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
29383   // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
29384   // TODO: Special case handling for shift by 0/1, really we can afford either
29385   // of these cases in pre-SSE41/XOP/AVX512 but not both.
29386   if (Opc == ISD::SRA && ConstantAmt &&
29387       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
29388       ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
29389         !Subtarget.hasAVX512()) ||
29390        DAG.isKnownNeverZero(Amt))) {
29391     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
29392     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
29393     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
29394       SDValue Amt0 =
29395           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
29396       SDValue Amt1 =
29397           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
29398       SDValue Sra1 =
29399           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
29400       SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
29401       Res = DAG.getSelect(dl, VT, Amt0, R, Res);
29402       return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
29403     }
29404   }
29405 
29406   // v4i32 Non Uniform Shifts.
29407   // If the shift amount is constant we can shift each lane using the SSE2
29408   // immediate shifts, else we need to zero-extend each lane to the lower i64
29409   // and shift using the SSE2 variable shifts.
29410   // The separate results can then be blended together.
29411   if (VT == MVT::v4i32) {
29412     SDValue Amt0, Amt1, Amt2, Amt3;
29413     if (ConstantAmt) {
29414       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
29415       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
29416       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
29417       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
29418     } else {
29419       // The SSE2 shifts use the lower i64 as the same shift amount for
29420       // all lanes and the upper i64 is ignored. On AVX we're better off
29421       // just zero-extending, but for SSE just duplicating the top 16-bits is
29422       // cheaper and has the same effect for out of range values.
29423       if (Subtarget.hasAVX()) {
29424         SDValue Z = DAG.getConstant(0, dl, VT);
29425         Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
29426         Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
29427         Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
29428         Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
29429       } else {
29430         SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
29431         SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
29432                                              {4, 5, 6, 7, -1, -1, -1, -1});
29433         Amt0 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
29434                                     {0, 1, 1, 1, -1, -1, -1, -1});
29435         Amt1 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
29436                                     {2, 3, 3, 3, -1, -1, -1, -1});
29437         Amt2 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
29438                                     {0, 1, 1, 1, -1, -1, -1, -1});
29439         Amt3 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
29440                                     {2, 3, 3, 3, -1, -1, -1, -1});
29441       }
29442     }
29443 
29444     unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
29445     SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
29446     SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
29447     SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
29448     SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
29449 
29450     // Merge the shifted lane results optimally with/without PBLENDW.
29451     // TODO - ideally shuffle combining would handle this.
29452     if (Subtarget.hasSSE41()) {
29453       SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
29454       SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
29455       return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
29456     }
29457     SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
29458     SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
29459     return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
29460   }
29461 
29462   // It's worth extending once and using the vXi16/vXi32 shifts for smaller
29463   // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
29464   // make the existing SSE solution better.
29465   // NOTE: We honor prefered vector width before promoting to 512-bits.
29466   if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
29467       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
29468       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
29469       (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
29470       (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
29471     assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
29472            "Unexpected vector type");
29473     MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
29474     MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
29475     unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
29476     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
29477     Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
29478     return DAG.getNode(ISD::TRUNCATE, dl, VT,
29479                        DAG.getNode(Opc, dl, ExtVT, R, Amt));
29480   }
29481 
29482   // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
29483   // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
29484   if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
29485       (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
29486        (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
29487       !Subtarget.hasXOP()) {
29488     int NumElts = VT.getVectorNumElements();
29489     SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
29490 
29491     // Extend constant shift amount to vXi16 (it doesn't matter if the type
29492     // isn't legal).
29493     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
29494     Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
29495     Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
29496     Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
29497     assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
29498            "Constant build vector expected");
29499 
29500     if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
29501       R = Opc == ISD::SRA ? DAG.getSExtOrTrunc(R, dl, ExVT)
29502                           : DAG.getZExtOrTrunc(R, dl, ExVT);
29503       R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
29504       R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
29505       return DAG.getZExtOrTrunc(R, dl, VT);
29506     }
29507 
29508     SmallVector<SDValue, 16> LoAmt, HiAmt;
29509     for (int i = 0; i != NumElts; i += 16) {
29510       for (int j = 0; j != 8; ++j) {
29511         LoAmt.push_back(Amt.getOperand(i + j));
29512         HiAmt.push_back(Amt.getOperand(i + j + 8));
29513       }
29514     }
29515 
29516     MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
29517     SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
29518     SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
29519 
29520     SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
29521     SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
29522     LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
29523     HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
29524     LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
29525     HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
29526     LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
29527     HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
29528     return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
29529   }
29530 
29531   if (VT == MVT::v16i8 ||
29532       (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
29533       (VT == MVT::v64i8 && Subtarget.hasBWI())) {
29534     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
29535 
29536     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
29537       if (VT.is512BitVector()) {
29538         // On AVX512BW targets we make use of the fact that VSELECT lowers
29539         // to a masked blend which selects bytes based just on the sign bit
29540         // extracted to a mask.
29541         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
29542         V0 = DAG.getBitcast(VT, V0);
29543         V1 = DAG.getBitcast(VT, V1);
29544         Sel = DAG.getBitcast(VT, Sel);
29545         Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
29546                            ISD::SETGT);
29547         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
29548       } else if (Subtarget.hasSSE41()) {
29549         // On SSE41 targets we can use PBLENDVB which selects bytes based just
29550         // on the sign bit.
29551         V0 = DAG.getBitcast(VT, V0);
29552         V1 = DAG.getBitcast(VT, V1);
29553         Sel = DAG.getBitcast(VT, Sel);
29554         return DAG.getBitcast(SelVT,
29555                               DAG.getNode(X86ISD::BLENDV, dl, VT, Sel, V0, V1));
29556       }
29557       // On pre-SSE41 targets we test for the sign bit by comparing to
29558       // zero - a negative value will set all bits of the lanes to true
29559       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
29560       SDValue Z = DAG.getConstant(0, dl, SelVT);
29561       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
29562       return DAG.getSelect(dl, SelVT, C, V0, V1);
29563     };
29564 
29565     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
29566     // We can safely do this using i16 shifts as we're only interested in
29567     // the 3 lower bits of each byte.
29568     Amt = DAG.getBitcast(ExtVT, Amt);
29569     Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
29570     Amt = DAG.getBitcast(VT, Amt);
29571 
29572     if (Opc == ISD::SHL || Opc == ISD::SRL) {
29573       // r = VSELECT(r, shift(r, 4), a);
29574       SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
29575       R = SignBitSelect(VT, Amt, M, R);
29576 
29577       // a += a
29578       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29579 
29580       // r = VSELECT(r, shift(r, 2), a);
29581       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
29582       R = SignBitSelect(VT, Amt, M, R);
29583 
29584       // a += a
29585       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29586 
29587       // return VSELECT(r, shift(r, 1), a);
29588       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
29589       R = SignBitSelect(VT, Amt, M, R);
29590       return R;
29591     }
29592 
29593     if (Opc == ISD::SRA) {
29594       // For SRA we need to unpack each byte to the higher byte of a i16 vector
29595       // so we can correctly sign extend. We don't care what happens to the
29596       // lower byte.
29597       SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
29598       SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
29599       SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
29600       SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
29601       ALo = DAG.getBitcast(ExtVT, ALo);
29602       AHi = DAG.getBitcast(ExtVT, AHi);
29603       RLo = DAG.getBitcast(ExtVT, RLo);
29604       RHi = DAG.getBitcast(ExtVT, RHi);
29605 
29606       // r = VSELECT(r, shift(r, 4), a);
29607       SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
29608       SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
29609       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
29610       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
29611 
29612       // a += a
29613       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
29614       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
29615 
29616       // r = VSELECT(r, shift(r, 2), a);
29617       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
29618       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
29619       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
29620       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
29621 
29622       // a += a
29623       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
29624       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
29625 
29626       // r = VSELECT(r, shift(r, 1), a);
29627       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
29628       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
29629       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
29630       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
29631 
29632       // Logical shift the result back to the lower byte, leaving a zero upper
29633       // byte meaning that we can safely pack with PACKUSWB.
29634       RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
29635       RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
29636       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
29637     }
29638   }
29639 
29640   if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
29641     MVT ExtVT = MVT::v8i32;
29642     SDValue Z = DAG.getConstant(0, dl, VT);
29643     SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
29644     SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
29645     SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
29646     SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
29647     ALo = DAG.getBitcast(ExtVT, ALo);
29648     AHi = DAG.getBitcast(ExtVT, AHi);
29649     RLo = DAG.getBitcast(ExtVT, RLo);
29650     RHi = DAG.getBitcast(ExtVT, RHi);
29651     SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
29652     SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
29653     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
29654     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
29655     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
29656   }
29657 
29658   if (VT == MVT::v8i16) {
29659     // If we have a constant shift amount, the non-SSE41 path is best as
29660     // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
29661     bool UseSSE41 = Subtarget.hasSSE41() &&
29662                     !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29663 
29664     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
29665       // On SSE41 targets we can use PBLENDVB which selects bytes based just on
29666       // the sign bit.
29667       if (UseSSE41) {
29668         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
29669         V0 = DAG.getBitcast(ExtVT, V0);
29670         V1 = DAG.getBitcast(ExtVT, V1);
29671         Sel = DAG.getBitcast(ExtVT, Sel);
29672         return DAG.getBitcast(
29673             VT, DAG.getNode(X86ISD::BLENDV, dl, ExtVT, Sel, V0, V1));
29674       }
29675       // On pre-SSE41 targets we splat the sign bit - a negative value will
29676       // set all bits of the lanes to true and VSELECT uses that in
29677       // its OR(AND(V0,C),AND(V1,~C)) lowering.
29678       SDValue C =
29679           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
29680       return DAG.getSelect(dl, VT, C, V0, V1);
29681     };
29682 
29683     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
29684     if (UseSSE41) {
29685       // On SSE41 targets we need to replicate the shift mask in both
29686       // bytes for PBLENDVB.
29687       Amt = DAG.getNode(
29688           ISD::OR, dl, VT,
29689           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
29690           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
29691     } else {
29692       Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
29693     }
29694 
29695     // r = VSELECT(r, shift(r, 8), a);
29696     SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
29697     R = SignBitSelect(Amt, M, R);
29698 
29699     // a += a
29700     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29701 
29702     // r = VSELECT(r, shift(r, 4), a);
29703     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
29704     R = SignBitSelect(Amt, M, R);
29705 
29706     // a += a
29707     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29708 
29709     // r = VSELECT(r, shift(r, 2), a);
29710     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
29711     R = SignBitSelect(Amt, M, R);
29712 
29713     // a += a
29714     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29715 
29716     // return VSELECT(r, shift(r, 1), a);
29717     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
29718     R = SignBitSelect(Amt, M, R);
29719     return R;
29720   }
29721 
29722   // Decompose 256-bit shifts into 128-bit shifts.
29723   if (VT.is256BitVector())
29724     return splitVectorIntBinary(Op, DAG);
29725 
29726   if (VT == MVT::v32i16 || VT == MVT::v64i8)
29727     return splitVectorIntBinary(Op, DAG);
29728 
29729   return SDValue();
29730 }
29731 
29732 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
29733                                 SelectionDAG &DAG) {
29734   MVT VT = Op.getSimpleValueType();
29735   assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
29736          "Unexpected funnel shift opcode!");
29737 
29738   SDLoc DL(Op);
29739   SDValue Op0 = Op.getOperand(0);
29740   SDValue Op1 = Op.getOperand(1);
29741   SDValue Amt = Op.getOperand(2);
29742   unsigned EltSizeInBits = VT.getScalarSizeInBits();
29743   bool IsFSHR = Op.getOpcode() == ISD::FSHR;
29744 
29745   if (VT.isVector()) {
29746     assert(Subtarget.hasVBMI2() && "Expected VBMI2");
29747 
29748     if (IsFSHR)
29749       std::swap(Op0, Op1);
29750 
29751     APInt APIntShiftAmt;
29752     if (X86::isConstantSplat(Amt, APIntShiftAmt)) {
29753       uint64_t ShiftAmt = APIntShiftAmt.urem(EltSizeInBits);
29754       SDValue Imm = DAG.getTargetConstant(ShiftAmt, DL, MVT::i8);
29755       return getAVX512Node(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT,
29756                            {Op0, Op1, Imm}, DAG, Subtarget);
29757     }
29758     return getAVX512Node(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
29759                          {Op0, Op1, Amt}, DAG, Subtarget);
29760   }
29761   assert(
29762       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
29763       "Unexpected funnel shift type!");
29764 
29765   // Expand slow SHLD/SHRD cases if we are not optimizing for size.
29766   bool OptForSize = DAG.shouldOptForSize();
29767   bool ExpandFunnel = !OptForSize && Subtarget.isSHLDSlow();
29768 
29769   // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
29770   // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
29771   if ((VT == MVT::i8 || (ExpandFunnel && VT == MVT::i16)) &&
29772       !isa<ConstantSDNode>(Amt)) {
29773     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, Amt.getValueType());
29774     SDValue HiShift = DAG.getConstant(EltSizeInBits, DL, Amt.getValueType());
29775     Op0 = DAG.getAnyExtOrTrunc(Op0, DL, MVT::i32);
29776     Op1 = DAG.getZExtOrTrunc(Op1, DL, MVT::i32);
29777     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt, Mask);
29778     SDValue Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Op0, HiShift);
29779     Res = DAG.getNode(ISD::OR, DL, MVT::i32, Res, Op1);
29780     if (IsFSHR) {
29781       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, Amt);
29782     } else {
29783       Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Res, Amt);
29784       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, HiShift);
29785     }
29786     return DAG.getZExtOrTrunc(Res, DL, VT);
29787   }
29788 
29789   if (VT == MVT::i8 || ExpandFunnel)
29790     return SDValue();
29791 
29792   // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
29793   if (VT == MVT::i16) {
29794     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
29795                       DAG.getConstant(15, DL, Amt.getValueType()));
29796     unsigned FSHOp = (IsFSHR ? X86ISD::FSHR : X86ISD::FSHL);
29797     return DAG.getNode(FSHOp, DL, VT, Op0, Op1, Amt);
29798   }
29799 
29800   return Op;
29801 }
29802 
29803 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
29804                            SelectionDAG &DAG) {
29805   MVT VT = Op.getSimpleValueType();
29806   assert(VT.isVector() && "Custom lowering only for vector rotates!");
29807 
29808   SDLoc DL(Op);
29809   SDValue R = Op.getOperand(0);
29810   SDValue Amt = Op.getOperand(1);
29811   unsigned Opcode = Op.getOpcode();
29812   unsigned EltSizeInBits = VT.getScalarSizeInBits();
29813   int NumElts = VT.getVectorNumElements();
29814   bool IsROTL = Opcode == ISD::ROTL;
29815 
29816   // Check for constant splat rotation amount.
29817   APInt CstSplatValue;
29818   bool IsCstSplat = X86::isConstantSplat(Amt, CstSplatValue);
29819 
29820   // Check for splat rotate by zero.
29821   if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
29822     return R;
29823 
29824   // AVX512 implicitly uses modulo rotation amounts.
29825   if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
29826     // Attempt to rotate by immediate.
29827     if (IsCstSplat) {
29828       unsigned RotOpc = IsROTL ? X86ISD::VROTLI : X86ISD::VROTRI;
29829       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
29830       return DAG.getNode(RotOpc, DL, VT, R,
29831                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
29832     }
29833 
29834     // Else, fall-back on VPROLV/VPRORV.
29835     return Op;
29836   }
29837 
29838   // AVX512 VBMI2 vXi16 - lower to funnel shifts.
29839   if (Subtarget.hasVBMI2() && 16 == EltSizeInBits) {
29840     unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
29841     return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
29842   }
29843 
29844   SDValue Z = DAG.getConstant(0, DL, VT);
29845 
29846   if (!IsROTL) {
29847     // If the ISD::ROTR amount is constant, we're always better converting to
29848     // ISD::ROTL.
29849     if (SDValue NegAmt = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {Z, Amt}))
29850       return DAG.getNode(ISD::ROTL, DL, VT, R, NegAmt);
29851 
29852     // XOP targets always prefers ISD::ROTL.
29853     if (Subtarget.hasXOP())
29854       return DAG.getNode(ISD::ROTL, DL, VT, R,
29855                          DAG.getNode(ISD::SUB, DL, VT, Z, Amt));
29856   }
29857 
29858   // Split 256-bit integers on XOP/pre-AVX2 targets.
29859   if (VT.is256BitVector() && (Subtarget.hasXOP() || !Subtarget.hasAVX2()))
29860     return splitVectorIntBinary(Op, DAG);
29861 
29862   // XOP has 128-bit vector variable + immediate rotates.
29863   // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
29864   // XOP implicitly uses modulo rotation amounts.
29865   if (Subtarget.hasXOP()) {
29866     assert(IsROTL && "Only ROTL expected");
29867     assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
29868 
29869     // Attempt to rotate by immediate.
29870     if (IsCstSplat) {
29871       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
29872       return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
29873                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
29874     }
29875 
29876     // Use general rotate by variable (per-element).
29877     return Op;
29878   }
29879 
29880   // Rotate by an uniform constant - expand back to shifts.
29881   if (IsCstSplat)
29882     return SDValue();
29883 
29884   // Split 512-bit integers on non 512-bit BWI targets.
29885   if (VT.is512BitVector() && !Subtarget.useBWIRegs())
29886     return splitVectorIntBinary(Op, DAG);
29887 
29888   assert(
29889       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
29890        ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&
29891         Subtarget.hasAVX2()) ||
29892        ((VT == MVT::v32i16 || VT == MVT::v64i8) && Subtarget.useBWIRegs())) &&
29893       "Only vXi32/vXi16/vXi8 vector rotates supported");
29894 
29895   MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
29896   MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
29897 
29898   SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
29899   SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
29900 
29901   // Attempt to fold as unpack(x,x) << zext(splat(y)):
29902   // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
29903   // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
29904   // TODO: Handle vXi16 cases.
29905   if (EltSizeInBits == 8 || EltSizeInBits == 32) {
29906     if (SDValue BaseRotAmt = DAG.getSplatValue(AmtMod)) {
29907       unsigned ShiftX86Opc = IsROTL ? X86ISD::VSHLI : X86ISD::VSRLI;
29908       SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
29909       SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
29910       BaseRotAmt = DAG.getZExtOrTrunc(BaseRotAmt, DL, MVT::i32);
29911       Lo = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Lo, BaseRotAmt,
29912                                Subtarget, DAG);
29913       Hi = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Hi, BaseRotAmt,
29914                                Subtarget, DAG);
29915       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
29916     }
29917   }
29918 
29919   // v16i8/v32i8/v64i8: Split rotation into rot4/rot2/rot1 stages and select by
29920   // the amount bit.
29921   // TODO: We're doing nothing here that we couldn't do for funnel shifts.
29922   if (EltSizeInBits == 8) {
29923     bool IsConstAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29924     MVT WideVT =
29925         MVT::getVectorVT(Subtarget.hasBWI() ? MVT::i16 : MVT::i32, NumElts);
29926     unsigned ShiftOpc = IsROTL ? ISD::SHL : ISD::SRL;
29927 
29928     // Attempt to fold as:
29929     // rotl(x,y) -> (((aext(x) << bw) | zext(x)) << (y & (bw-1))) >> bw.
29930     // rotr(x,y) -> (((aext(x) << bw) | zext(x)) >> (y & (bw-1))).
29931     if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
29932         supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
29933       // If we're rotating by constant, just use default promotion.
29934       if (IsConstAmt)
29935         return SDValue();
29936       // See if we can perform this by widening to vXi16 or vXi32.
29937       R = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, R);
29938       R = DAG.getNode(
29939           ISD::OR, DL, WideVT, R,
29940           getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, R, 8, DAG));
29941       Amt = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
29942       R = DAG.getNode(ShiftOpc, DL, WideVT, R, Amt);
29943       if (IsROTL)
29944         R = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, R, 8, DAG);
29945       return DAG.getNode(ISD::TRUNCATE, DL, VT, R);
29946     }
29947 
29948     // Attempt to fold as unpack(x,x) << zext(y):
29949     // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
29950     // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
29951     if (IsConstAmt || supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc)) {
29952       // See if we can perform this by unpacking to lo/hi vXi16.
29953       SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
29954       SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
29955       SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
29956       SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
29957       SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
29958       SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
29959       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
29960     }
29961     assert((VT == MVT::v16i8 || VT == MVT::v32i8) && "Unsupported vXi8 type");
29962 
29963     // We don't need ModuloAmt here as we just peek at individual bits.
29964     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
29965       if (Subtarget.hasSSE41()) {
29966         // On SSE41 targets we can use PBLENDVB which selects bytes based just
29967         // on the sign bit.
29968         V0 = DAG.getBitcast(VT, V0);
29969         V1 = DAG.getBitcast(VT, V1);
29970         Sel = DAG.getBitcast(VT, Sel);
29971         return DAG.getBitcast(SelVT,
29972                               DAG.getNode(X86ISD::BLENDV, DL, VT, Sel, V0, V1));
29973       }
29974       // On pre-SSE41 targets we test for the sign bit by comparing to
29975       // zero - a negative value will set all bits of the lanes to true
29976       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
29977       SDValue Z = DAG.getConstant(0, DL, SelVT);
29978       SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
29979       return DAG.getSelect(DL, SelVT, C, V0, V1);
29980     };
29981 
29982     // ISD::ROTR is currently only profitable on AVX512 targets with VPTERNLOG.
29983     if (!IsROTL && !useVPTERNLOG(Subtarget, VT)) {
29984       Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
29985       IsROTL = true;
29986     }
29987 
29988     unsigned ShiftLHS = IsROTL ? ISD::SHL : ISD::SRL;
29989     unsigned ShiftRHS = IsROTL ? ISD::SRL : ISD::SHL;
29990 
29991     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
29992     // We can safely do this using i16 shifts as we're only interested in
29993     // the 3 lower bits of each byte.
29994     Amt = DAG.getBitcast(ExtVT, Amt);
29995     Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
29996     Amt = DAG.getBitcast(VT, Amt);
29997 
29998     // r = VSELECT(r, rot(r, 4), a);
29999     SDValue M;
30000     M = DAG.getNode(
30001         ISD::OR, DL, VT,
30002         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(4, DL, VT)),
30003         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(4, DL, VT)));
30004     R = SignBitSelect(VT, Amt, M, R);
30005 
30006     // a += a
30007     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
30008 
30009     // r = VSELECT(r, rot(r, 2), a);
30010     M = DAG.getNode(
30011         ISD::OR, DL, VT,
30012         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(2, DL, VT)),
30013         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(6, DL, VT)));
30014     R = SignBitSelect(VT, Amt, M, R);
30015 
30016     // a += a
30017     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
30018 
30019     // return VSELECT(r, rot(r, 1), a);
30020     M = DAG.getNode(
30021         ISD::OR, DL, VT,
30022         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(1, DL, VT)),
30023         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(7, DL, VT)));
30024     return SignBitSelect(VT, Amt, M, R);
30025   }
30026 
30027   bool IsSplatAmt = DAG.isSplatValue(Amt);
30028   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
30029   bool LegalVarShifts = supportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
30030                         supportedVectorVarShift(VT, Subtarget, ISD::SRL);
30031 
30032   // Fallback for splats + all supported variable shifts.
30033   // Fallback for non-constants AVX2 vXi16 as well.
30034   if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
30035     Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30036     SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
30037     AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
30038     SDValue SHL = DAG.getNode(IsROTL ? ISD::SHL : ISD::SRL, DL, VT, R, Amt);
30039     SDValue SRL = DAG.getNode(IsROTL ? ISD::SRL : ISD::SHL, DL, VT, R, AmtR);
30040     return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
30041   }
30042 
30043   // Everything below assumes ISD::ROTL.
30044   if (!IsROTL) {
30045     Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
30046     IsROTL = true;
30047   }
30048 
30049   // ISD::ROT* uses modulo rotate amounts.
30050   Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30051 
30052   assert(IsROTL && "Only ROTL supported");
30053 
30054   // As with shifts, attempt to convert the rotation amount to a multiplication
30055   // factor, fallback to general expansion.
30056   SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
30057   if (!Scale)
30058     return SDValue();
30059 
30060   // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
30061   if (EltSizeInBits == 16) {
30062     SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
30063     SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
30064     return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
30065   }
30066 
30067   // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
30068   // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
30069   // that can then be OR'd with the lower 32-bits.
30070   assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
30071   static const int OddMask[] = {1, -1, 3, -1};
30072   SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
30073   SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
30074 
30075   SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
30076                               DAG.getBitcast(MVT::v2i64, R),
30077                               DAG.getBitcast(MVT::v2i64, Scale));
30078   SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
30079                               DAG.getBitcast(MVT::v2i64, R13),
30080                               DAG.getBitcast(MVT::v2i64, Scale13));
30081   Res02 = DAG.getBitcast(VT, Res02);
30082   Res13 = DAG.getBitcast(VT, Res13);
30083 
30084   return DAG.getNode(ISD::OR, DL, VT,
30085                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
30086                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
30087 }
30088 
30089 /// Returns true if the operand type is exactly twice the native width, and
30090 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
30091 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
30092 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
30093 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
30094   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
30095 
30096   if (OpWidth == 64)
30097     return Subtarget.hasCmpxchg8b() && !Subtarget.is64Bit();
30098   if (OpWidth == 128)
30099     return Subtarget.hasCmpxchg16b();
30100 
30101   return false;
30102 }
30103 
30104 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
30105   Type *MemType = SI->getValueOperand()->getType();
30106 
30107   bool NoImplicitFloatOps =
30108       SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
30109   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
30110       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
30111       (Subtarget.hasSSE1() || Subtarget.hasX87()))
30112     return false;
30113 
30114   return needsCmpXchgNb(MemType);
30115 }
30116 
30117 // Note: this turns large loads into lock cmpxchg8b/16b.
30118 // TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
30119 TargetLowering::AtomicExpansionKind
30120 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
30121   Type *MemType = LI->getType();
30122 
30123   // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
30124   // can use movq to do the load. If we have X87 we can load into an 80-bit
30125   // X87 register and store it to a stack temporary.
30126   bool NoImplicitFloatOps =
30127       LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
30128   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
30129       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
30130       (Subtarget.hasSSE1() || Subtarget.hasX87()))
30131     return AtomicExpansionKind::None;
30132 
30133   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
30134                                  : AtomicExpansionKind::None;
30135 }
30136 
30137 TargetLowering::AtomicExpansionKind
30138 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
30139   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
30140   Type *MemType = AI->getType();
30141 
30142   // If the operand is too big, we must see if cmpxchg8/16b is available
30143   // and default to library calls otherwise.
30144   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
30145     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
30146                                    : AtomicExpansionKind::None;
30147   }
30148 
30149   AtomicRMWInst::BinOp Op = AI->getOperation();
30150   switch (Op) {
30151   default:
30152     llvm_unreachable("Unknown atomic operation");
30153   case AtomicRMWInst::Xchg:
30154   case AtomicRMWInst::Add:
30155   case AtomicRMWInst::Sub:
30156     // It's better to use xadd, xsub or xchg for these in all cases.
30157     return AtomicExpansionKind::None;
30158   case AtomicRMWInst::Or:
30159   case AtomicRMWInst::And:
30160   case AtomicRMWInst::Xor:
30161     // If the atomicrmw's result isn't actually used, we can just add a "lock"
30162     // prefix to a normal instruction for these operations.
30163     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
30164                             : AtomicExpansionKind::None;
30165   case AtomicRMWInst::Nand:
30166   case AtomicRMWInst::Max:
30167   case AtomicRMWInst::Min:
30168   case AtomicRMWInst::UMax:
30169   case AtomicRMWInst::UMin:
30170   case AtomicRMWInst::FAdd:
30171   case AtomicRMWInst::FSub:
30172     // These always require a non-trivial set of data operations on x86. We must
30173     // use a cmpxchg loop.
30174     return AtomicExpansionKind::CmpXChg;
30175   }
30176 }
30177 
30178 LoadInst *
30179 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
30180   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
30181   Type *MemType = AI->getType();
30182   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
30183   // there is no benefit in turning such RMWs into loads, and it is actually
30184   // harmful as it introduces a mfence.
30185   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
30186     return nullptr;
30187 
30188   // If this is a canonical idempotent atomicrmw w/no uses, we have a better
30189   // lowering available in lowerAtomicArith.
30190   // TODO: push more cases through this path.
30191   if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
30192     if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
30193         AI->use_empty())
30194       return nullptr;
30195 
30196   IRBuilder<> Builder(AI);
30197   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
30198   auto SSID = AI->getSyncScopeID();
30199   // We must restrict the ordering to avoid generating loads with Release or
30200   // ReleaseAcquire orderings.
30201   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
30202 
30203   // Before the load we need a fence. Here is an example lifted from
30204   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
30205   // is required:
30206   // Thread 0:
30207   //   x.store(1, relaxed);
30208   //   r1 = y.fetch_add(0, release);
30209   // Thread 1:
30210   //   y.fetch_add(42, acquire);
30211   //   r2 = x.load(relaxed);
30212   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
30213   // lowered to just a load without a fence. A mfence flushes the store buffer,
30214   // making the optimization clearly correct.
30215   // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
30216   // otherwise, we might be able to be more aggressive on relaxed idempotent
30217   // rmw. In practice, they do not look useful, so we don't try to be
30218   // especially clever.
30219   if (SSID == SyncScope::SingleThread)
30220     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
30221     // the IR level, so we must wrap it in an intrinsic.
30222     return nullptr;
30223 
30224   if (!Subtarget.hasMFence())
30225     // FIXME: it might make sense to use a locked operation here but on a
30226     // different cache-line to prevent cache-line bouncing. In practice it
30227     // is probably a small win, and x86 processors without mfence are rare
30228     // enough that we do not bother.
30229     return nullptr;
30230 
30231   Function *MFence =
30232       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
30233   Builder.CreateCall(MFence, {});
30234 
30235   // Finally we can emit the atomic load.
30236   LoadInst *Loaded = Builder.CreateAlignedLoad(
30237       AI->getType(), AI->getPointerOperand(), AI->getAlign());
30238   Loaded->setAtomic(Order, SSID);
30239   AI->replaceAllUsesWith(Loaded);
30240   AI->eraseFromParent();
30241   return Loaded;
30242 }
30243 
30244 bool X86TargetLowering::lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
30245   if (!SI.isUnordered())
30246     return false;
30247   return ExperimentalUnorderedISEL;
30248 }
30249 bool X86TargetLowering::lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
30250   if (!LI.isUnordered())
30251     return false;
30252   return ExperimentalUnorderedISEL;
30253 }
30254 
30255 
30256 /// Emit a locked operation on a stack location which does not change any
30257 /// memory location, but does involve a lock prefix.  Location is chosen to be
30258 /// a) very likely accessed only by a single thread to minimize cache traffic,
30259 /// and b) definitely dereferenceable.  Returns the new Chain result.
30260 static SDValue emitLockedStackOp(SelectionDAG &DAG,
30261                                  const X86Subtarget &Subtarget, SDValue Chain,
30262                                  const SDLoc &DL) {
30263   // Implementation notes:
30264   // 1) LOCK prefix creates a full read/write reordering barrier for memory
30265   // operations issued by the current processor.  As such, the location
30266   // referenced is not relevant for the ordering properties of the instruction.
30267   // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
30268   // 8.2.3.9  Loads and Stores Are Not Reordered with Locked Instructions
30269   // 2) Using an immediate operand appears to be the best encoding choice
30270   // here since it doesn't require an extra register.
30271   // 3) OR appears to be very slightly faster than ADD. (Though, the difference
30272   // is small enough it might just be measurement noise.)
30273   // 4) When choosing offsets, there are several contributing factors:
30274   //   a) If there's no redzone, we default to TOS.  (We could allocate a cache
30275   //      line aligned stack object to improve this case.)
30276   //   b) To minimize our chances of introducing a false dependence, we prefer
30277   //      to offset the stack usage from TOS slightly.
30278   //   c) To minimize concerns about cross thread stack usage - in particular,
30279   //      the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
30280   //      captures state in the TOS frame and accesses it from many threads -
30281   //      we want to use an offset such that the offset is in a distinct cache
30282   //      line from the TOS frame.
30283   //
30284   // For a general discussion of the tradeoffs and benchmark results, see:
30285   // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
30286 
30287   auto &MF = DAG.getMachineFunction();
30288   auto &TFL = *Subtarget.getFrameLowering();
30289   const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
30290 
30291   if (Subtarget.is64Bit()) {
30292     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
30293     SDValue Ops[] = {
30294       DAG.getRegister(X86::RSP, MVT::i64),                  // Base
30295       DAG.getTargetConstant(1, DL, MVT::i8),                // Scale
30296       DAG.getRegister(0, MVT::i64),                         // Index
30297       DAG.getTargetConstant(SPOffset, DL, MVT::i32),        // Disp
30298       DAG.getRegister(0, MVT::i16),                         // Segment.
30299       Zero,
30300       Chain};
30301     SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
30302                                      MVT::Other, Ops);
30303     return SDValue(Res, 1);
30304   }
30305 
30306   SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
30307   SDValue Ops[] = {
30308     DAG.getRegister(X86::ESP, MVT::i32),            // Base
30309     DAG.getTargetConstant(1, DL, MVT::i8),          // Scale
30310     DAG.getRegister(0, MVT::i32),                   // Index
30311     DAG.getTargetConstant(SPOffset, DL, MVT::i32),  // Disp
30312     DAG.getRegister(0, MVT::i16),                   // Segment.
30313     Zero,
30314     Chain
30315   };
30316   SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
30317                                    MVT::Other, Ops);
30318   return SDValue(Res, 1);
30319 }
30320 
30321 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
30322                                  SelectionDAG &DAG) {
30323   SDLoc dl(Op);
30324   AtomicOrdering FenceOrdering =
30325       static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
30326   SyncScope::ID FenceSSID =
30327       static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
30328 
30329   // The only fence that needs an instruction is a sequentially-consistent
30330   // cross-thread fence.
30331   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
30332       FenceSSID == SyncScope::System) {
30333     if (Subtarget.hasMFence())
30334       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
30335 
30336     SDValue Chain = Op.getOperand(0);
30337     return emitLockedStackOp(DAG, Subtarget, Chain, dl);
30338   }
30339 
30340   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
30341   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
30342 }
30343 
30344 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
30345                              SelectionDAG &DAG) {
30346   MVT T = Op.getSimpleValueType();
30347   SDLoc DL(Op);
30348   unsigned Reg = 0;
30349   unsigned size = 0;
30350   switch(T.SimpleTy) {
30351   default: llvm_unreachable("Invalid value type!");
30352   case MVT::i8:  Reg = X86::AL;  size = 1; break;
30353   case MVT::i16: Reg = X86::AX;  size = 2; break;
30354   case MVT::i32: Reg = X86::EAX; size = 4; break;
30355   case MVT::i64:
30356     assert(Subtarget.is64Bit() && "Node not type legal!");
30357     Reg = X86::RAX; size = 8;
30358     break;
30359   }
30360   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
30361                                   Op.getOperand(2), SDValue());
30362   SDValue Ops[] = { cpIn.getValue(0),
30363                     Op.getOperand(1),
30364                     Op.getOperand(3),
30365                     DAG.getTargetConstant(size, DL, MVT::i8),
30366                     cpIn.getValue(1) };
30367   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
30368   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
30369   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
30370                                            Ops, T, MMO);
30371 
30372   SDValue cpOut =
30373     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
30374   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
30375                                       MVT::i32, cpOut.getValue(2));
30376   SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
30377 
30378   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
30379                      cpOut, Success, EFLAGS.getValue(1));
30380 }
30381 
30382 // Create MOVMSKB, taking into account whether we need to split for AVX1.
30383 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
30384                            const X86Subtarget &Subtarget) {
30385   MVT InVT = V.getSimpleValueType();
30386 
30387   if (InVT == MVT::v64i8) {
30388     SDValue Lo, Hi;
30389     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
30390     Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
30391     Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
30392     Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
30393     Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
30394     Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
30395                      DAG.getConstant(32, DL, MVT::i8));
30396     return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
30397   }
30398   if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
30399     SDValue Lo, Hi;
30400     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
30401     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
30402     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
30403     Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
30404                      DAG.getConstant(16, DL, MVT::i8));
30405     return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
30406   }
30407 
30408   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
30409 }
30410 
30411 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
30412                             SelectionDAG &DAG) {
30413   SDValue Src = Op.getOperand(0);
30414   MVT SrcVT = Src.getSimpleValueType();
30415   MVT DstVT = Op.getSimpleValueType();
30416 
30417   // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
30418   // half to v32i1 and concatenating the result.
30419   if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
30420     assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
30421     assert(Subtarget.hasBWI() && "Expected BWI target");
30422     SDLoc dl(Op);
30423     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
30424                              DAG.getIntPtrConstant(0, dl));
30425     Lo = DAG.getBitcast(MVT::v32i1, Lo);
30426     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
30427                              DAG.getIntPtrConstant(1, dl));
30428     Hi = DAG.getBitcast(MVT::v32i1, Hi);
30429     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
30430   }
30431 
30432   // Use MOVMSK for vector to scalar conversion to prevent scalarization.
30433   if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
30434     assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
30435     MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
30436     SDLoc DL(Op);
30437     SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
30438     V = getPMOVMSKB(DL, V, DAG, Subtarget);
30439     return DAG.getZExtOrTrunc(V, DL, DstVT);
30440   }
30441 
30442   assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
30443           SrcVT == MVT::i64) && "Unexpected VT!");
30444 
30445   assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
30446   if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
30447       !(DstVT == MVT::x86mmx && SrcVT.isVector()))
30448     // This conversion needs to be expanded.
30449     return SDValue();
30450 
30451   SDLoc dl(Op);
30452   if (SrcVT.isVector()) {
30453     // Widen the vector in input in the case of MVT::v2i32.
30454     // Example: from MVT::v2i32 to MVT::v4i32.
30455     MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
30456                                  SrcVT.getVectorNumElements() * 2);
30457     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
30458                       DAG.getUNDEF(SrcVT));
30459   } else {
30460     assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
30461            "Unexpected source type in LowerBITCAST");
30462     Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
30463   }
30464 
30465   MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
30466   Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
30467 
30468   if (DstVT == MVT::x86mmx)
30469     return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
30470 
30471   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
30472                      DAG.getIntPtrConstant(0, dl));
30473 }
30474 
30475 /// Compute the horizontal sum of bytes in V for the elements of VT.
30476 ///
30477 /// Requires V to be a byte vector and VT to be an integer vector type with
30478 /// wider elements than V's type. The width of the elements of VT determines
30479 /// how many bytes of V are summed horizontally to produce each element of the
30480 /// result.
30481 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
30482                                       const X86Subtarget &Subtarget,
30483                                       SelectionDAG &DAG) {
30484   SDLoc DL(V);
30485   MVT ByteVecVT = V.getSimpleValueType();
30486   MVT EltVT = VT.getVectorElementType();
30487   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
30488          "Expected value to have byte element type.");
30489   assert(EltVT != MVT::i8 &&
30490          "Horizontal byte sum only makes sense for wider elements!");
30491   unsigned VecSize = VT.getSizeInBits();
30492   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
30493 
30494   // PSADBW instruction horizontally add all bytes and leave the result in i64
30495   // chunks, thus directly computes the pop count for v2i64 and v4i64.
30496   if (EltVT == MVT::i64) {
30497     SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
30498     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
30499     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
30500     return DAG.getBitcast(VT, V);
30501   }
30502 
30503   if (EltVT == MVT::i32) {
30504     // We unpack the low half and high half into i32s interleaved with zeros so
30505     // that we can use PSADBW to horizontally sum them. The most useful part of
30506     // this is that it lines up the results of two PSADBW instructions to be
30507     // two v2i64 vectors which concatenated are the 4 population counts. We can
30508     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
30509     SDValue Zeros = DAG.getConstant(0, DL, VT);
30510     SDValue V32 = DAG.getBitcast(VT, V);
30511     SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
30512     SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
30513 
30514     // Do the horizontal sums into two v2i64s.
30515     Zeros = DAG.getConstant(0, DL, ByteVecVT);
30516     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
30517     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
30518                       DAG.getBitcast(ByteVecVT, Low), Zeros);
30519     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
30520                        DAG.getBitcast(ByteVecVT, High), Zeros);
30521 
30522     // Merge them together.
30523     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
30524     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
30525                     DAG.getBitcast(ShortVecVT, Low),
30526                     DAG.getBitcast(ShortVecVT, High));
30527 
30528     return DAG.getBitcast(VT, V);
30529   }
30530 
30531   // The only element type left is i16.
30532   assert(EltVT == MVT::i16 && "Unknown how to handle type");
30533 
30534   // To obtain pop count for each i16 element starting from the pop count for
30535   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
30536   // right by 8. It is important to shift as i16s as i8 vector shift isn't
30537   // directly supported.
30538   SDValue ShifterV = DAG.getConstant(8, DL, VT);
30539   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
30540   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
30541                   DAG.getBitcast(ByteVecVT, V));
30542   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
30543 }
30544 
30545 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
30546                                         const X86Subtarget &Subtarget,
30547                                         SelectionDAG &DAG) {
30548   MVT VT = Op.getSimpleValueType();
30549   MVT EltVT = VT.getVectorElementType();
30550   int NumElts = VT.getVectorNumElements();
30551   (void)EltVT;
30552   assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
30553 
30554   // Implement a lookup table in register by using an algorithm based on:
30555   // http://wm.ite.pl/articles/sse-popcount.html
30556   //
30557   // The general idea is that every lower byte nibble in the input vector is an
30558   // index into a in-register pre-computed pop count table. We then split up the
30559   // input vector in two new ones: (1) a vector with only the shifted-right
30560   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
30561   // masked out higher ones) for each byte. PSHUFB is used separately with both
30562   // to index the in-register table. Next, both are added and the result is a
30563   // i8 vector where each element contains the pop count for input byte.
30564   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
30565                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
30566                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
30567                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
30568 
30569   SmallVector<SDValue, 64> LUTVec;
30570   for (int i = 0; i < NumElts; ++i)
30571     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
30572   SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
30573   SDValue M0F = DAG.getConstant(0x0F, DL, VT);
30574 
30575   // High nibbles
30576   SDValue FourV = DAG.getConstant(4, DL, VT);
30577   SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
30578 
30579   // Low nibbles
30580   SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
30581 
30582   // The input vector is used as the shuffle mask that index elements into the
30583   // LUT. After counting low and high nibbles, add the vector to obtain the
30584   // final pop count per i8 element.
30585   SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
30586   SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
30587   return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
30588 }
30589 
30590 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
30591 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
30592 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
30593                                 SelectionDAG &DAG) {
30594   MVT VT = Op.getSimpleValueType();
30595   assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
30596          "Unknown CTPOP type to handle");
30597   SDLoc DL(Op.getNode());
30598   SDValue Op0 = Op.getOperand(0);
30599 
30600   // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
30601   if (Subtarget.hasVPOPCNTDQ()) {
30602     unsigned NumElems = VT.getVectorNumElements();
30603     assert((VT.getVectorElementType() == MVT::i8 ||
30604             VT.getVectorElementType() == MVT::i16) && "Unexpected type");
30605     if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
30606       MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
30607       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
30608       Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
30609       return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
30610     }
30611   }
30612 
30613   // Decompose 256-bit ops into smaller 128-bit ops.
30614   if (VT.is256BitVector() && !Subtarget.hasInt256())
30615     return splitVectorIntUnary(Op, DAG);
30616 
30617   // Decompose 512-bit ops into smaller 256-bit ops.
30618   if (VT.is512BitVector() && !Subtarget.hasBWI())
30619     return splitVectorIntUnary(Op, DAG);
30620 
30621   // For element types greater than i8, do vXi8 pop counts and a bytesum.
30622   if (VT.getScalarType() != MVT::i8) {
30623     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
30624     SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
30625     SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
30626     return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
30627   }
30628 
30629   // We can't use the fast LUT approach, so fall back on LegalizeDAG.
30630   if (!Subtarget.hasSSSE3())
30631     return SDValue();
30632 
30633   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
30634 }
30635 
30636 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
30637                           SelectionDAG &DAG) {
30638   assert(Op.getSimpleValueType().isVector() &&
30639          "We only do custom lowering for vector population count.");
30640   return LowerVectorCTPOP(Op, Subtarget, DAG);
30641 }
30642 
30643 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
30644   MVT VT = Op.getSimpleValueType();
30645   SDValue In = Op.getOperand(0);
30646   SDLoc DL(Op);
30647 
30648   // For scalars, its still beneficial to transfer to/from the SIMD unit to
30649   // perform the BITREVERSE.
30650   if (!VT.isVector()) {
30651     MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
30652     SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
30653     Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
30654     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
30655                        DAG.getIntPtrConstant(0, DL));
30656   }
30657 
30658   int NumElts = VT.getVectorNumElements();
30659   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
30660 
30661   // Decompose 256-bit ops into smaller 128-bit ops.
30662   if (VT.is256BitVector())
30663     return splitVectorIntUnary(Op, DAG);
30664 
30665   assert(VT.is128BitVector() &&
30666          "Only 128-bit vector bitreverse lowering supported.");
30667 
30668   // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
30669   // perform the BSWAP in the shuffle.
30670   // Its best to shuffle using the second operand as this will implicitly allow
30671   // memory folding for multiple vectors.
30672   SmallVector<SDValue, 16> MaskElts;
30673   for (int i = 0; i != NumElts; ++i) {
30674     for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
30675       int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
30676       int PermuteByte = SourceByte | (2 << 5);
30677       MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
30678     }
30679   }
30680 
30681   SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
30682   SDValue Res = DAG.getBitcast(MVT::v16i8, In);
30683   Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
30684                     Res, Mask);
30685   return DAG.getBitcast(VT, Res);
30686 }
30687 
30688 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
30689                                SelectionDAG &DAG) {
30690   MVT VT = Op.getSimpleValueType();
30691 
30692   if (Subtarget.hasXOP() && !VT.is512BitVector())
30693     return LowerBITREVERSE_XOP(Op, DAG);
30694 
30695   assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
30696 
30697   SDValue In = Op.getOperand(0);
30698   SDLoc DL(Op);
30699 
30700   assert(VT.getScalarType() == MVT::i8 &&
30701          "Only byte vector BITREVERSE supported");
30702 
30703   // Split v64i8 without BWI so that we can still use the PSHUFB lowering.
30704   if (VT == MVT::v64i8 && !Subtarget.hasBWI())
30705     return splitVectorIntUnary(Op, DAG);
30706 
30707   // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
30708   if (VT == MVT::v32i8 && !Subtarget.hasInt256())
30709     return splitVectorIntUnary(Op, DAG);
30710 
30711   unsigned NumElts = VT.getVectorNumElements();
30712 
30713   // If we have GFNI, we can use GF2P8AFFINEQB to reverse the bits.
30714   if (Subtarget.hasGFNI()) {
30715     MVT MatrixVT = MVT::getVectorVT(MVT::i64, NumElts / 8);
30716     SDValue Matrix = DAG.getConstant(0x8040201008040201ULL, DL, MatrixVT);
30717     Matrix = DAG.getBitcast(VT, Matrix);
30718     return DAG.getNode(X86ISD::GF2P8AFFINEQB, DL, VT, In, Matrix,
30719                        DAG.getTargetConstant(0, DL, MVT::i8));
30720   }
30721 
30722   // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
30723   // two nibbles and a PSHUFB lookup to find the bitreverse of each
30724   // 0-15 value (moved to the other nibble).
30725   SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
30726   SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
30727   SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
30728 
30729   const int LoLUT[16] = {
30730       /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
30731       /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
30732       /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
30733       /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
30734   const int HiLUT[16] = {
30735       /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
30736       /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
30737       /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
30738       /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
30739 
30740   SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
30741   for (unsigned i = 0; i < NumElts; ++i) {
30742     LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
30743     HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
30744   }
30745 
30746   SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
30747   SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
30748   Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
30749   Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
30750   return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
30751 }
30752 
30753 static SDValue LowerPARITY(SDValue Op, const X86Subtarget &Subtarget,
30754                            SelectionDAG &DAG) {
30755   SDLoc DL(Op);
30756   SDValue X = Op.getOperand(0);
30757   MVT VT = Op.getSimpleValueType();
30758 
30759   // Special case. If the input fits in 8-bits we can use a single 8-bit TEST.
30760   if (VT == MVT::i8 ||
30761       DAG.MaskedValueIsZero(X, APInt::getBitsSetFrom(VT.getSizeInBits(), 8))) {
30762     X = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
30763     SDValue Flags = DAG.getNode(X86ISD::CMP, DL, MVT::i32, X,
30764                                 DAG.getConstant(0, DL, MVT::i8));
30765     // Copy the inverse of the parity flag into a register with setcc.
30766     SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
30767     // Extend to the original type.
30768     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
30769   }
30770 
30771   // If we have POPCNT, use the default expansion.
30772   if (Subtarget.hasPOPCNT())
30773     return SDValue();
30774 
30775   if (VT == MVT::i64) {
30776     // Xor the high and low 16-bits together using a 32-bit operation.
30777     SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
30778                              DAG.getNode(ISD::SRL, DL, MVT::i64, X,
30779                                          DAG.getConstant(32, DL, MVT::i8)));
30780     SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
30781     X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
30782   }
30783 
30784   if (VT != MVT::i16) {
30785     // Xor the high and low 16-bits together using a 32-bit operation.
30786     SDValue Hi16 = DAG.getNode(ISD::SRL, DL, MVT::i32, X,
30787                                DAG.getConstant(16, DL, MVT::i8));
30788     X = DAG.getNode(ISD::XOR, DL, MVT::i32, X, Hi16);
30789   } else {
30790     // If the input is 16-bits, we need to extend to use an i32 shift below.
30791     X = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, X);
30792   }
30793 
30794   // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
30795   // This should allow an h-reg to be used to save a shift.
30796   SDValue Hi = DAG.getNode(
30797       ISD::TRUNCATE, DL, MVT::i8,
30798       DAG.getNode(ISD::SRL, DL, MVT::i32, X, DAG.getConstant(8, DL, MVT::i8)));
30799   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
30800   SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
30801   SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
30802 
30803   // Copy the inverse of the parity flag into a register with setcc.
30804   SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
30805   // Extend to the original type.
30806   return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
30807 }
30808 
30809 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
30810                                         const X86Subtarget &Subtarget) {
30811   unsigned NewOpc = 0;
30812   switch (N->getOpcode()) {
30813   case ISD::ATOMIC_LOAD_ADD:
30814     NewOpc = X86ISD::LADD;
30815     break;
30816   case ISD::ATOMIC_LOAD_SUB:
30817     NewOpc = X86ISD::LSUB;
30818     break;
30819   case ISD::ATOMIC_LOAD_OR:
30820     NewOpc = X86ISD::LOR;
30821     break;
30822   case ISD::ATOMIC_LOAD_XOR:
30823     NewOpc = X86ISD::LXOR;
30824     break;
30825   case ISD::ATOMIC_LOAD_AND:
30826     NewOpc = X86ISD::LAND;
30827     break;
30828   default:
30829     llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
30830   }
30831 
30832   MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
30833 
30834   return DAG.getMemIntrinsicNode(
30835       NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
30836       {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
30837       /*MemVT=*/N->getSimpleValueType(0), MMO);
30838 }
30839 
30840 /// Lower atomic_load_ops into LOCK-prefixed operations.
30841 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
30842                                 const X86Subtarget &Subtarget) {
30843   AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
30844   SDValue Chain = N->getOperand(0);
30845   SDValue LHS = N->getOperand(1);
30846   SDValue RHS = N->getOperand(2);
30847   unsigned Opc = N->getOpcode();
30848   MVT VT = N->getSimpleValueType(0);
30849   SDLoc DL(N);
30850 
30851   // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
30852   // can only be lowered when the result is unused.  They should have already
30853   // been transformed into a cmpxchg loop in AtomicExpand.
30854   if (N->hasAnyUseOfValue(0)) {
30855     // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
30856     // select LXADD if LOCK_SUB can't be selected.
30857     if (Opc == ISD::ATOMIC_LOAD_SUB) {
30858       RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
30859       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
30860                            RHS, AN->getMemOperand());
30861     }
30862     assert(Opc == ISD::ATOMIC_LOAD_ADD &&
30863            "Used AtomicRMW ops other than Add should have been expanded!");
30864     return N;
30865   }
30866 
30867   // Specialized lowering for the canonical form of an idemptotent atomicrmw.
30868   // The core idea here is that since the memory location isn't actually
30869   // changing, all we need is a lowering for the *ordering* impacts of the
30870   // atomicrmw.  As such, we can chose a different operation and memory
30871   // location to minimize impact on other code.
30872   if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS)) {
30873     // On X86, the only ordering which actually requires an instruction is
30874     // seq_cst which isn't SingleThread, everything just needs to be preserved
30875     // during codegen and then dropped. Note that we expect (but don't assume),
30876     // that orderings other than seq_cst and acq_rel have been canonicalized to
30877     // a store or load.
30878     if (AN->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent &&
30879         AN->getSyncScopeID() == SyncScope::System) {
30880       // Prefer a locked operation against a stack location to minimize cache
30881       // traffic.  This assumes that stack locations are very likely to be
30882       // accessed only by the owning thread.
30883       SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
30884       assert(!N->hasAnyUseOfValue(0));
30885       // NOTE: The getUNDEF is needed to give something for the unused result 0.
30886       return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
30887                          DAG.getUNDEF(VT), NewChain);
30888     }
30889     // MEMBARRIER is a compiler barrier; it codegens to a no-op.
30890     SDValue NewChain = DAG.getNode(X86ISD::MEMBARRIER, DL, MVT::Other, Chain);
30891     assert(!N->hasAnyUseOfValue(0));
30892     // NOTE: The getUNDEF is needed to give something for the unused result 0.
30893     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
30894                        DAG.getUNDEF(VT), NewChain);
30895   }
30896 
30897   SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
30898   // RAUW the chain, but don't worry about the result, as it's unused.
30899   assert(!N->hasAnyUseOfValue(0));
30900   // NOTE: The getUNDEF is needed to give something for the unused result 0.
30901   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
30902                      DAG.getUNDEF(VT), LockOp.getValue(1));
30903 }
30904 
30905 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
30906                                  const X86Subtarget &Subtarget) {
30907   auto *Node = cast<AtomicSDNode>(Op.getNode());
30908   SDLoc dl(Node);
30909   EVT VT = Node->getMemoryVT();
30910 
30911   bool IsSeqCst =
30912       Node->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent;
30913   bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
30914 
30915   // If this store is not sequentially consistent and the type is legal
30916   // we can just keep it.
30917   if (!IsSeqCst && IsTypeLegal)
30918     return Op;
30919 
30920   if (VT == MVT::i64 && !IsTypeLegal) {
30921     // For illegal i64 atomic_stores, we can try to use MOVQ or MOVLPS if SSE
30922     // is enabled.
30923     bool NoImplicitFloatOps =
30924         DAG.getMachineFunction().getFunction().hasFnAttribute(
30925             Attribute::NoImplicitFloat);
30926     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
30927       SDValue Chain;
30928       if (Subtarget.hasSSE1()) {
30929         SDValue SclToVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
30930                                        Node->getOperand(2));
30931         MVT StVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
30932         SclToVec = DAG.getBitcast(StVT, SclToVec);
30933         SDVTList Tys = DAG.getVTList(MVT::Other);
30934         SDValue Ops[] = {Node->getChain(), SclToVec, Node->getBasePtr()};
30935         Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops,
30936                                         MVT::i64, Node->getMemOperand());
30937       } else if (Subtarget.hasX87()) {
30938         // First load this into an 80-bit X87 register using a stack temporary.
30939         // This will put the whole integer into the significand.
30940         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
30941         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
30942         MachinePointerInfo MPI =
30943             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
30944         Chain =
30945             DAG.getStore(Node->getChain(), dl, Node->getOperand(2), StackPtr,
30946                          MPI, MaybeAlign(), MachineMemOperand::MOStore);
30947         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
30948         SDValue LdOps[] = {Chain, StackPtr};
30949         SDValue Value =
30950             DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, LdOps, MVT::i64, MPI,
30951                                     /*Align*/ None, MachineMemOperand::MOLoad);
30952         Chain = Value.getValue(1);
30953 
30954         // Now use an FIST to do the atomic store.
30955         SDValue StoreOps[] = {Chain, Value, Node->getBasePtr()};
30956         Chain =
30957             DAG.getMemIntrinsicNode(X86ISD::FIST, dl, DAG.getVTList(MVT::Other),
30958                                     StoreOps, MVT::i64, Node->getMemOperand());
30959       }
30960 
30961       if (Chain) {
30962         // If this is a sequentially consistent store, also emit an appropriate
30963         // barrier.
30964         if (IsSeqCst)
30965           Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
30966 
30967         return Chain;
30968       }
30969     }
30970   }
30971 
30972   // Convert seq_cst store -> xchg
30973   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
30974   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
30975   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
30976                                Node->getMemoryVT(),
30977                                Node->getOperand(0),
30978                                Node->getOperand(1), Node->getOperand(2),
30979                                Node->getMemOperand());
30980   return Swap.getValue(1);
30981 }
30982 
30983 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
30984   SDNode *N = Op.getNode();
30985   MVT VT = N->getSimpleValueType(0);
30986   unsigned Opc = Op.getOpcode();
30987 
30988   // Let legalize expand this if it isn't a legal type yet.
30989   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
30990     return SDValue();
30991 
30992   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
30993   SDLoc DL(N);
30994 
30995   // Set the carry flag.
30996   SDValue Carry = Op.getOperand(2);
30997   EVT CarryVT = Carry.getValueType();
30998   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
30999                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
31000 
31001   bool IsAdd = Opc == ISD::ADDCARRY || Opc == ISD::SADDO_CARRY;
31002   SDValue Sum = DAG.getNode(IsAdd ? X86ISD::ADC : X86ISD::SBB, DL, VTs,
31003                             Op.getOperand(0), Op.getOperand(1),
31004                             Carry.getValue(1));
31005 
31006   bool IsSigned = Opc == ISD::SADDO_CARRY || Opc == ISD::SSUBO_CARRY;
31007   SDValue SetCC = getSETCC(IsSigned ? X86::COND_O : X86::COND_B,
31008                            Sum.getValue(1), DL, DAG);
31009   if (N->getValueType(1) == MVT::i1)
31010     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
31011 
31012   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
31013 }
31014 
31015 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
31016                             SelectionDAG &DAG) {
31017   assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
31018 
31019   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
31020   // which returns the values as { float, float } (in XMM0) or
31021   // { double, double } (which is returned in XMM0, XMM1).
31022   SDLoc dl(Op);
31023   SDValue Arg = Op.getOperand(0);
31024   EVT ArgVT = Arg.getValueType();
31025   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
31026 
31027   TargetLowering::ArgListTy Args;
31028   TargetLowering::ArgListEntry Entry;
31029 
31030   Entry.Node = Arg;
31031   Entry.Ty = ArgTy;
31032   Entry.IsSExt = false;
31033   Entry.IsZExt = false;
31034   Args.push_back(Entry);
31035 
31036   bool isF64 = ArgVT == MVT::f64;
31037   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
31038   // the small struct {f32, f32} is returned in (eax, edx). For f64,
31039   // the results are returned via SRet in memory.
31040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
31041   RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
31042   const char *LibcallName = TLI.getLibcallName(LC);
31043   SDValue Callee =
31044       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
31045 
31046   Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
31047                       : (Type *)FixedVectorType::get(ArgTy, 4);
31048 
31049   TargetLowering::CallLoweringInfo CLI(DAG);
31050   CLI.setDebugLoc(dl)
31051       .setChain(DAG.getEntryNode())
31052       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
31053 
31054   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
31055 
31056   if (isF64)
31057     // Returned in xmm0 and xmm1.
31058     return CallResult.first;
31059 
31060   // Returned in bits 0:31 and 32:64 xmm0.
31061   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
31062                                CallResult.first, DAG.getIntPtrConstant(0, dl));
31063   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
31064                                CallResult.first, DAG.getIntPtrConstant(1, dl));
31065   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
31066   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
31067 }
31068 
31069 /// Widen a vector input to a vector of NVT.  The
31070 /// input vector must have the same element type as NVT.
31071 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
31072                             bool FillWithZeroes = false) {
31073   // Check if InOp already has the right width.
31074   MVT InVT = InOp.getSimpleValueType();
31075   if (InVT == NVT)
31076     return InOp;
31077 
31078   if (InOp.isUndef())
31079     return DAG.getUNDEF(NVT);
31080 
31081   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
31082          "input and widen element type must match");
31083 
31084   unsigned InNumElts = InVT.getVectorNumElements();
31085   unsigned WidenNumElts = NVT.getVectorNumElements();
31086   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
31087          "Unexpected request for vector widening");
31088 
31089   SDLoc dl(InOp);
31090   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
31091       InOp.getNumOperands() == 2) {
31092     SDValue N1 = InOp.getOperand(1);
31093     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
31094         N1.isUndef()) {
31095       InOp = InOp.getOperand(0);
31096       InVT = InOp.getSimpleValueType();
31097       InNumElts = InVT.getVectorNumElements();
31098     }
31099   }
31100   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
31101       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
31102     SmallVector<SDValue, 16> Ops;
31103     for (unsigned i = 0; i < InNumElts; ++i)
31104       Ops.push_back(InOp.getOperand(i));
31105 
31106     EVT EltVT = InOp.getOperand(0).getValueType();
31107 
31108     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
31109       DAG.getUNDEF(EltVT);
31110     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
31111       Ops.push_back(FillVal);
31112     return DAG.getBuildVector(NVT, dl, Ops);
31113   }
31114   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
31115     DAG.getUNDEF(NVT);
31116   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
31117                      InOp, DAG.getIntPtrConstant(0, dl));
31118 }
31119 
31120 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
31121                              SelectionDAG &DAG) {
31122   assert(Subtarget.hasAVX512() &&
31123          "MGATHER/MSCATTER are supported on AVX-512 arch only");
31124 
31125   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
31126   SDValue Src = N->getValue();
31127   MVT VT = Src.getSimpleValueType();
31128   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
31129   SDLoc dl(Op);
31130 
31131   SDValue Scale = N->getScale();
31132   SDValue Index = N->getIndex();
31133   SDValue Mask = N->getMask();
31134   SDValue Chain = N->getChain();
31135   SDValue BasePtr = N->getBasePtr();
31136 
31137   if (VT == MVT::v2f32 || VT == MVT::v2i32) {
31138     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
31139     // If the index is v2i64 and we have VLX we can use xmm for data and index.
31140     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
31141       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
31142       EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
31143       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
31144       SDVTList VTs = DAG.getVTList(MVT::Other);
31145       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
31146       return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
31147                                      N->getMemoryVT(), N->getMemOperand());
31148     }
31149     return SDValue();
31150   }
31151 
31152   MVT IndexVT = Index.getSimpleValueType();
31153 
31154   // If the index is v2i32, we're being called by type legalization and we
31155   // should just let the default handling take care of it.
31156   if (IndexVT == MVT::v2i32)
31157     return SDValue();
31158 
31159   // If we don't have VLX and neither the passthru or index is 512-bits, we
31160   // need to widen until one is.
31161   if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
31162       !Index.getSimpleValueType().is512BitVector()) {
31163     // Determine how much we need to widen by to get a 512-bit type.
31164     unsigned Factor = std::min(512/VT.getSizeInBits(),
31165                                512/IndexVT.getSizeInBits());
31166     unsigned NumElts = VT.getVectorNumElements() * Factor;
31167 
31168     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
31169     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
31170     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
31171 
31172     Src = ExtendToType(Src, VT, DAG);
31173     Index = ExtendToType(Index, IndexVT, DAG);
31174     Mask = ExtendToType(Mask, MaskVT, DAG, true);
31175   }
31176 
31177   SDVTList VTs = DAG.getVTList(MVT::Other);
31178   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
31179   return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
31180                                  N->getMemoryVT(), N->getMemOperand());
31181 }
31182 
31183 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
31184                           SelectionDAG &DAG) {
31185 
31186   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
31187   MVT VT = Op.getSimpleValueType();
31188   MVT ScalarVT = VT.getScalarType();
31189   SDValue Mask = N->getMask();
31190   MVT MaskVT = Mask.getSimpleValueType();
31191   SDValue PassThru = N->getPassThru();
31192   SDLoc dl(Op);
31193 
31194   // Handle AVX masked loads which don't support passthru other than 0.
31195   if (MaskVT.getVectorElementType() != MVT::i1) {
31196     // We also allow undef in the isel pattern.
31197     if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
31198       return Op;
31199 
31200     SDValue NewLoad = DAG.getMaskedLoad(
31201         VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
31202         getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
31203         N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
31204         N->isExpandingLoad());
31205     // Emit a blend.
31206     SDValue Select = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
31207     return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
31208   }
31209 
31210   assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
31211          "Expanding masked load is supported on AVX-512 target only!");
31212 
31213   assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
31214          "Expanding masked load is supported for 32 and 64-bit types only!");
31215 
31216   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
31217          "Cannot lower masked load op.");
31218 
31219   assert((ScalarVT.getSizeInBits() >= 32 ||
31220           (Subtarget.hasBWI() &&
31221               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
31222          "Unsupported masked load op.");
31223 
31224   // This operation is legal for targets with VLX, but without
31225   // VLX the vector should be widened to 512 bit
31226   unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
31227   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
31228   PassThru = ExtendToType(PassThru, WideDataVT, DAG);
31229 
31230   // Mask element has to be i1.
31231   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
31232          "Unexpected mask type");
31233 
31234   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
31235 
31236   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
31237   SDValue NewLoad = DAG.getMaskedLoad(
31238       WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
31239       PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
31240       N->getExtensionType(), N->isExpandingLoad());
31241 
31242   SDValue Extract =
31243       DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, NewLoad.getValue(0),
31244                   DAG.getIntPtrConstant(0, dl));
31245   SDValue RetOps[] = {Extract, NewLoad.getValue(1)};
31246   return DAG.getMergeValues(RetOps, dl);
31247 }
31248 
31249 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
31250                            SelectionDAG &DAG) {
31251   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
31252   SDValue DataToStore = N->getValue();
31253   MVT VT = DataToStore.getSimpleValueType();
31254   MVT ScalarVT = VT.getScalarType();
31255   SDValue Mask = N->getMask();
31256   SDLoc dl(Op);
31257 
31258   assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
31259          "Expanding masked load is supported on AVX-512 target only!");
31260 
31261   assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
31262          "Expanding masked load is supported for 32 and 64-bit types only!");
31263 
31264   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
31265          "Cannot lower masked store op.");
31266 
31267   assert((ScalarVT.getSizeInBits() >= 32 ||
31268           (Subtarget.hasBWI() &&
31269               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
31270           "Unsupported masked store op.");
31271 
31272   // This operation is legal for targets with VLX, but without
31273   // VLX the vector should be widened to 512 bit
31274   unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
31275   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
31276 
31277   // Mask element has to be i1.
31278   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
31279          "Unexpected mask type");
31280 
31281   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
31282 
31283   DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
31284   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
31285   return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
31286                             N->getOffset(), Mask, N->getMemoryVT(),
31287                             N->getMemOperand(), N->getAddressingMode(),
31288                             N->isTruncatingStore(), N->isCompressingStore());
31289 }
31290 
31291 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
31292                             SelectionDAG &DAG) {
31293   assert(Subtarget.hasAVX2() &&
31294          "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
31295 
31296   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
31297   SDLoc dl(Op);
31298   MVT VT = Op.getSimpleValueType();
31299   SDValue Index = N->getIndex();
31300   SDValue Mask = N->getMask();
31301   SDValue PassThru = N->getPassThru();
31302   MVT IndexVT = Index.getSimpleValueType();
31303 
31304   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
31305 
31306   // If the index is v2i32, we're being called by type legalization.
31307   if (IndexVT == MVT::v2i32)
31308     return SDValue();
31309 
31310   // If we don't have VLX and neither the passthru or index is 512-bits, we
31311   // need to widen until one is.
31312   MVT OrigVT = VT;
31313   if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
31314       !IndexVT.is512BitVector()) {
31315     // Determine how much we need to widen by to get a 512-bit type.
31316     unsigned Factor = std::min(512/VT.getSizeInBits(),
31317                                512/IndexVT.getSizeInBits());
31318 
31319     unsigned NumElts = VT.getVectorNumElements() * Factor;
31320 
31321     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
31322     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
31323     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
31324 
31325     PassThru = ExtendToType(PassThru, VT, DAG);
31326     Index = ExtendToType(Index, IndexVT, DAG);
31327     Mask = ExtendToType(Mask, MaskVT, DAG, true);
31328   }
31329 
31330   // Break dependency on the data register.
31331   if (PassThru.isUndef())
31332     PassThru = getZeroVector(VT, Subtarget, DAG, dl);
31333 
31334   SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
31335                     N->getScale() };
31336   SDValue NewGather = DAG.getMemIntrinsicNode(
31337       X86ISD::MGATHER, dl, DAG.getVTList(VT, MVT::Other), Ops, N->getMemoryVT(),
31338       N->getMemOperand());
31339   SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
31340                                 NewGather, DAG.getIntPtrConstant(0, dl));
31341   return DAG.getMergeValues({Extract, NewGather.getValue(1)}, dl);
31342 }
31343 
31344 static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
31345   SDLoc dl(Op);
31346   SDValue Src = Op.getOperand(0);
31347   MVT DstVT = Op.getSimpleValueType();
31348 
31349   AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
31350   unsigned SrcAS = N->getSrcAddressSpace();
31351 
31352   assert(SrcAS != N->getDestAddressSpace() &&
31353          "addrspacecast must be between different address spaces");
31354 
31355   if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
31356     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
31357   } else if (DstVT == MVT::i64) {
31358     Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
31359   } else if (DstVT == MVT::i32) {
31360     Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
31361   } else {
31362     report_fatal_error("Bad address space in addrspacecast");
31363   }
31364   return Op;
31365 }
31366 
31367 SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
31368                                               SelectionDAG &DAG) const {
31369   // TODO: Eventually, the lowering of these nodes should be informed by or
31370   // deferred to the GC strategy for the function in which they appear. For
31371   // now, however, they must be lowered to something. Since they are logically
31372   // no-ops in the case of a null GC strategy (or a GC strategy which does not
31373   // require special handling for these nodes), lower them as literal NOOPs for
31374   // the time being.
31375   SmallVector<SDValue, 2> Ops;
31376 
31377   Ops.push_back(Op.getOperand(0));
31378   if (Op->getGluedNode())
31379     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
31380 
31381   SDLoc OpDL(Op);
31382   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
31383   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
31384 
31385   return NOOP;
31386 }
31387 
31388 // Custom split CVTPS2PH with wide types.
31389 static SDValue LowerCVTPS2PH(SDValue Op, SelectionDAG &DAG) {
31390   SDLoc dl(Op);
31391   EVT VT = Op.getValueType();
31392   SDValue Lo, Hi;
31393   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
31394   EVT LoVT, HiVT;
31395   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
31396   SDValue RC = Op.getOperand(1);
31397   Lo = DAG.getNode(X86ISD::CVTPS2PH, dl, LoVT, Lo, RC);
31398   Hi = DAG.getNode(X86ISD::CVTPS2PH, dl, HiVT, Hi, RC);
31399   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
31400 }
31401 
31402 /// Provide custom lowering hooks for some operations.
31403 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
31404   switch (Op.getOpcode()) {
31405   default: llvm_unreachable("Should not custom lower this!");
31406   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
31407   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
31408     return LowerCMP_SWAP(Op, Subtarget, DAG);
31409   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
31410   case ISD::ATOMIC_LOAD_ADD:
31411   case ISD::ATOMIC_LOAD_SUB:
31412   case ISD::ATOMIC_LOAD_OR:
31413   case ISD::ATOMIC_LOAD_XOR:
31414   case ISD::ATOMIC_LOAD_AND:    return lowerAtomicArith(Op, DAG, Subtarget);
31415   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG, Subtarget);
31416   case ISD::BITREVERSE:         return LowerBITREVERSE(Op, Subtarget, DAG);
31417   case ISD::PARITY:             return LowerPARITY(Op, Subtarget, DAG);
31418   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
31419   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
31420   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
31421   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
31422   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
31423   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
31424   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
31425   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
31426   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
31427   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
31428   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
31429   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
31430   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
31431   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
31432   case ISD::SHL_PARTS:
31433   case ISD::SRA_PARTS:
31434   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
31435   case ISD::FSHL:
31436   case ISD::FSHR:               return LowerFunnelShift(Op, Subtarget, DAG);
31437   case ISD::STRICT_SINT_TO_FP:
31438   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
31439   case ISD::STRICT_UINT_TO_FP:
31440   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
31441   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
31442   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
31443   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
31444   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
31445   case ISD::ZERO_EXTEND_VECTOR_INREG:
31446   case ISD::SIGN_EXTEND_VECTOR_INREG:
31447     return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
31448   case ISD::FP_TO_SINT:
31449   case ISD::STRICT_FP_TO_SINT:
31450   case ISD::FP_TO_UINT:
31451   case ISD::STRICT_FP_TO_UINT:  return LowerFP_TO_INT(Op, DAG);
31452   case ISD::FP_TO_SINT_SAT:
31453   case ISD::FP_TO_UINT_SAT:     return LowerFP_TO_INT_SAT(Op, DAG);
31454   case ISD::FP_EXTEND:
31455   case ISD::STRICT_FP_EXTEND:   return LowerFP_EXTEND(Op, DAG);
31456   case ISD::FP_ROUND:
31457   case ISD::STRICT_FP_ROUND:    return LowerFP_ROUND(Op, DAG);
31458   case ISD::FP16_TO_FP:
31459   case ISD::STRICT_FP16_TO_FP:  return LowerFP16_TO_FP(Op, DAG);
31460   case ISD::FP_TO_FP16:
31461   case ISD::STRICT_FP_TO_FP16:  return LowerFP_TO_FP16(Op, DAG);
31462   case ISD::LOAD:               return LowerLoad(Op, Subtarget, DAG);
31463   case ISD::STORE:              return LowerStore(Op, Subtarget, DAG);
31464   case ISD::FADD:
31465   case ISD::FSUB:               return lowerFaddFsub(Op, DAG);
31466   case ISD::FROUND:             return LowerFROUND(Op, DAG);
31467   case ISD::FABS:
31468   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
31469   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
31470   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
31471   case ISD::LRINT:
31472   case ISD::LLRINT:             return LowerLRINT_LLRINT(Op, DAG);
31473   case ISD::SETCC:
31474   case ISD::STRICT_FSETCC:
31475   case ISD::STRICT_FSETCCS:     return LowerSETCC(Op, DAG);
31476   case ISD::SETCCCARRY:         return LowerSETCCCARRY(Op, DAG);
31477   case ISD::SELECT:             return LowerSELECT(Op, DAG);
31478   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
31479   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
31480   case ISD::VASTART:            return LowerVASTART(Op, DAG);
31481   case ISD::VAARG:              return LowerVAARG(Op, DAG);
31482   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
31483   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
31484   case ISD::INTRINSIC_VOID:
31485   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
31486   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
31487   case ISD::ADDROFRETURNADDR:   return LowerADDROFRETURNADDR(Op, DAG);
31488   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
31489   case ISD::FRAME_TO_ARGS_OFFSET:
31490                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
31491   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
31492   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
31493   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
31494   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
31495   case ISD::EH_SJLJ_SETUP_DISPATCH:
31496     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
31497   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
31498   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
31499   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
31500   case ISD::SET_ROUNDING:       return LowerSET_ROUNDING(Op, DAG);
31501   case ISD::CTLZ:
31502   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ(Op, Subtarget, DAG);
31503   case ISD::CTTZ:
31504   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, Subtarget, DAG);
31505   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
31506   case ISD::MULHS:
31507   case ISD::MULHU:              return LowerMULH(Op, Subtarget, DAG);
31508   case ISD::ROTL:
31509   case ISD::ROTR:               return LowerRotate(Op, Subtarget, DAG);
31510   case ISD::SRA:
31511   case ISD::SRL:
31512   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
31513   case ISD::SADDO:
31514   case ISD::UADDO:
31515   case ISD::SSUBO:
31516   case ISD::USUBO:              return LowerXALUO(Op, DAG);
31517   case ISD::SMULO:
31518   case ISD::UMULO:              return LowerMULO(Op, Subtarget, DAG);
31519   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
31520   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
31521   case ISD::SADDO_CARRY:
31522   case ISD::SSUBO_CARRY:
31523   case ISD::ADDCARRY:
31524   case ISD::SUBCARRY:           return LowerADDSUBCARRY(Op, DAG);
31525   case ISD::ADD:
31526   case ISD::SUB:                return lowerAddSub(Op, DAG, Subtarget);
31527   case ISD::UADDSAT:
31528   case ISD::SADDSAT:
31529   case ISD::USUBSAT:
31530   case ISD::SSUBSAT:            return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
31531   case ISD::SMAX:
31532   case ISD::SMIN:
31533   case ISD::UMAX:
31534   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
31535   case ISD::ABS:                return LowerABS(Op, Subtarget, DAG);
31536   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
31537   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
31538   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
31539   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
31540   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
31541   case ISD::GC_TRANSITION_START:
31542   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION(Op, DAG);
31543   case ISD::ADDRSPACECAST:      return LowerADDRSPACECAST(Op, DAG);
31544   case X86ISD::CVTPS2PH:        return LowerCVTPS2PH(Op, DAG);
31545   }
31546 }
31547 
31548 /// Replace a node with an illegal result type with a new node built out of
31549 /// custom code.
31550 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
31551                                            SmallVectorImpl<SDValue>&Results,
31552                                            SelectionDAG &DAG) const {
31553   SDLoc dl(N);
31554   switch (N->getOpcode()) {
31555   default:
31556 #ifndef NDEBUG
31557     dbgs() << "ReplaceNodeResults: ";
31558     N->dump(&DAG);
31559 #endif
31560     llvm_unreachable("Do not know how to custom type legalize this operation!");
31561   case X86ISD::CVTPH2PS: {
31562     EVT VT = N->getValueType(0);
31563     SDValue Lo, Hi;
31564     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
31565     EVT LoVT, HiVT;
31566     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
31567     Lo = DAG.getNode(X86ISD::CVTPH2PS, dl, LoVT, Lo);
31568     Hi = DAG.getNode(X86ISD::CVTPH2PS, dl, HiVT, Hi);
31569     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
31570     Results.push_back(Res);
31571     return;
31572   }
31573   case X86ISD::STRICT_CVTPH2PS: {
31574     EVT VT = N->getValueType(0);
31575     SDValue Lo, Hi;
31576     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 1);
31577     EVT LoVT, HiVT;
31578     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
31579     Lo = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {LoVT, MVT::Other},
31580                      {N->getOperand(0), Lo});
31581     Hi = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {HiVT, MVT::Other},
31582                      {N->getOperand(0), Hi});
31583     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
31584                                 Lo.getValue(1), Hi.getValue(1));
31585     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
31586     Results.push_back(Res);
31587     Results.push_back(Chain);
31588     return;
31589   }
31590   case X86ISD::CVTPS2PH:
31591     Results.push_back(LowerCVTPS2PH(SDValue(N, 0), DAG));
31592     return;
31593   case ISD::CTPOP: {
31594     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
31595     // Use a v2i64 if possible.
31596     bool NoImplicitFloatOps =
31597         DAG.getMachineFunction().getFunction().hasFnAttribute(
31598             Attribute::NoImplicitFloat);
31599     if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
31600       SDValue Wide =
31601           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
31602       Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
31603       // Bit count should fit in 32-bits, extract it as that and then zero
31604       // extend to i64. Otherwise we end up extracting bits 63:32 separately.
31605       Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
31606       Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
31607                          DAG.getIntPtrConstant(0, dl));
31608       Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
31609       Results.push_back(Wide);
31610     }
31611     return;
31612   }
31613   case ISD::MUL: {
31614     EVT VT = N->getValueType(0);
31615     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
31616            VT.getVectorElementType() == MVT::i8 && "Unexpected VT!");
31617     // Pre-promote these to vXi16 to avoid op legalization thinking all 16
31618     // elements are needed.
31619     MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
31620     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
31621     SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
31622     SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
31623     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
31624     unsigned NumConcats = 16 / VT.getVectorNumElements();
31625     SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
31626     ConcatOps[0] = Res;
31627     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
31628     Results.push_back(Res);
31629     return;
31630   }
31631   case X86ISD::VPMADDWD:
31632   case X86ISD::AVG: {
31633     // Legalize types for X86ISD::AVG/VPMADDWD by widening.
31634     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
31635 
31636     EVT VT = N->getValueType(0);
31637     EVT InVT = N->getOperand(0).getValueType();
31638     assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
31639            "Expected a VT that divides into 128 bits.");
31640     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
31641            "Unexpected type action!");
31642     unsigned NumConcat = 128 / InVT.getSizeInBits();
31643 
31644     EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
31645                                     InVT.getVectorElementType(),
31646                                     NumConcat * InVT.getVectorNumElements());
31647     EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
31648                                   VT.getVectorElementType(),
31649                                   NumConcat * VT.getVectorNumElements());
31650 
31651     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
31652     Ops[0] = N->getOperand(0);
31653     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
31654     Ops[0] = N->getOperand(1);
31655     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
31656 
31657     SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
31658     Results.push_back(Res);
31659     return;
31660   }
31661   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
31662   case X86ISD::FMINC:
31663   case X86ISD::FMIN:
31664   case X86ISD::FMAXC:
31665   case X86ISD::FMAX: {
31666     EVT VT = N->getValueType(0);
31667     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
31668     SDValue UNDEF = DAG.getUNDEF(VT);
31669     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
31670                               N->getOperand(0), UNDEF);
31671     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
31672                               N->getOperand(1), UNDEF);
31673     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
31674     return;
31675   }
31676   case ISD::SDIV:
31677   case ISD::UDIV:
31678   case ISD::SREM:
31679   case ISD::UREM: {
31680     EVT VT = N->getValueType(0);
31681     if (VT.isVector()) {
31682       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
31683              "Unexpected type action!");
31684       // If this RHS is a constant splat vector we can widen this and let
31685       // division/remainder by constant optimize it.
31686       // TODO: Can we do something for non-splat?
31687       APInt SplatVal;
31688       if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
31689         unsigned NumConcats = 128 / VT.getSizeInBits();
31690         SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
31691         Ops0[0] = N->getOperand(0);
31692         EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
31693         SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
31694         SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
31695         SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
31696         Results.push_back(Res);
31697       }
31698       return;
31699     }
31700 
31701     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
31702     Results.push_back(V);
31703     return;
31704   }
31705   case ISD::TRUNCATE: {
31706     MVT VT = N->getSimpleValueType(0);
31707     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
31708       return;
31709 
31710     // The generic legalizer will try to widen the input type to the same
31711     // number of elements as the widened result type. But this isn't always
31712     // the best thing so do some custom legalization to avoid some cases.
31713     MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
31714     SDValue In = N->getOperand(0);
31715     EVT InVT = In.getValueType();
31716 
31717     unsigned InBits = InVT.getSizeInBits();
31718     if (128 % InBits == 0) {
31719       // 128 bit and smaller inputs should avoid truncate all together and
31720       // just use a build_vector that will become a shuffle.
31721       // TODO: Widen and use a shuffle directly?
31722       MVT InEltVT = InVT.getSimpleVT().getVectorElementType();
31723       EVT EltVT = VT.getVectorElementType();
31724       unsigned WidenNumElts = WidenVT.getVectorNumElements();
31725       SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
31726       // Use the original element count so we don't do more scalar opts than
31727       // necessary.
31728       unsigned MinElts = VT.getVectorNumElements();
31729       for (unsigned i=0; i < MinElts; ++i) {
31730         SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
31731                                   DAG.getIntPtrConstant(i, dl));
31732         Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
31733       }
31734       Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
31735       return;
31736     }
31737     // With AVX512 there are some cases that can use a target specific
31738     // truncate node to go from 256/512 to less than 128 with zeros in the
31739     // upper elements of the 128 bit result.
31740     if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
31741       // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
31742       if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
31743         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
31744         return;
31745       }
31746       // There's one case we can widen to 512 bits and use VTRUNC.
31747       if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
31748         In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
31749                          DAG.getUNDEF(MVT::v4i64));
31750         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
31751         return;
31752       }
31753     }
31754     if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
31755         getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
31756         isTypeLegal(MVT::v4i64)) {
31757       // Input needs to be split and output needs to widened. Let's use two
31758       // VTRUNCs, and shuffle their results together into the wider type.
31759       SDValue Lo, Hi;
31760       std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
31761 
31762       Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
31763       Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
31764       SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
31765                                          { 0,  1,  2,  3, 16, 17, 18, 19,
31766                                           -1, -1, -1, -1, -1, -1, -1, -1 });
31767       Results.push_back(Res);
31768       return;
31769     }
31770 
31771     return;
31772   }
31773   case ISD::ANY_EXTEND:
31774     // Right now, only MVT::v8i8 has Custom action for an illegal type.
31775     // It's intended to custom handle the input type.
31776     assert(N->getValueType(0) == MVT::v8i8 &&
31777            "Do not know how to legalize this Node");
31778     return;
31779   case ISD::SIGN_EXTEND:
31780   case ISD::ZERO_EXTEND: {
31781     EVT VT = N->getValueType(0);
31782     SDValue In = N->getOperand(0);
31783     EVT InVT = In.getValueType();
31784     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
31785         (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
31786       assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&
31787              "Unexpected type action!");
31788       assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode");
31789       // Custom split this so we can extend i8/i16->i32 invec. This is better
31790       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
31791       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
31792       // we allow the sra from the extend to i32 to be shared by the split.
31793       In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
31794 
31795       // Fill a vector with sign bits for each element.
31796       SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
31797       SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
31798 
31799       // Create an unpackl and unpackh to interleave the sign bits then bitcast
31800       // to v2i64.
31801       SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
31802                                         {0, 4, 1, 5});
31803       Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
31804       SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
31805                                         {2, 6, 3, 7});
31806       Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
31807 
31808       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
31809       Results.push_back(Res);
31810       return;
31811     }
31812 
31813     if (VT == MVT::v16i32 || VT == MVT::v8i64) {
31814       if (!InVT.is128BitVector()) {
31815         // Not a 128 bit vector, but maybe type legalization will promote
31816         // it to 128 bits.
31817         if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
31818           return;
31819         InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
31820         if (!InVT.is128BitVector())
31821           return;
31822 
31823         // Promote the input to 128 bits. Type legalization will turn this into
31824         // zext_inreg/sext_inreg.
31825         In = DAG.getNode(N->getOpcode(), dl, InVT, In);
31826       }
31827 
31828       // Perform custom splitting instead of the two stage extend we would get
31829       // by default.
31830       EVT LoVT, HiVT;
31831       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
31832       assert(isTypeLegal(LoVT) && "Split VT not legal?");
31833 
31834       SDValue Lo = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, LoVT, In, DAG);
31835 
31836       // We need to shift the input over by half the number of elements.
31837       unsigned NumElts = InVT.getVectorNumElements();
31838       unsigned HalfNumElts = NumElts / 2;
31839       SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
31840       for (unsigned i = 0; i != HalfNumElts; ++i)
31841         ShufMask[i] = i + HalfNumElts;
31842 
31843       SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
31844       Hi = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, HiVT, Hi, DAG);
31845 
31846       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
31847       Results.push_back(Res);
31848     }
31849     return;
31850   }
31851   case ISD::FP_TO_SINT:
31852   case ISD::STRICT_FP_TO_SINT:
31853   case ISD::FP_TO_UINT:
31854   case ISD::STRICT_FP_TO_UINT: {
31855     bool IsStrict = N->isStrictFPOpcode();
31856     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
31857                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
31858     EVT VT = N->getValueType(0);
31859     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
31860     EVT SrcVT = Src.getValueType();
31861 
31862     if (VT.isVector() && Subtarget.hasFP16() &&
31863         SrcVT.getVectorElementType() == MVT::f16) {
31864       EVT EleVT = VT.getVectorElementType();
31865       EVT ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
31866 
31867       if (SrcVT != MVT::v8f16) {
31868         SDValue Tmp =
31869             IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
31870         SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
31871         Ops[0] = Src;
31872         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
31873       }
31874 
31875       SDValue Res, Chain;
31876       if (IsStrict) {
31877         unsigned Opc =
31878             IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
31879         Res =
31880             DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {N->getOperand(0), Src});
31881         Chain = Res.getValue(1);
31882       } else {
31883         unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
31884         Res = DAG.getNode(Opc, dl, ResVT, Src);
31885       }
31886 
31887       // TODO: Need to add exception check code for strict FP.
31888       if (EleVT.getSizeInBits() < 16) {
31889         MVT TmpVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8);
31890         Res = DAG.getNode(ISD::TRUNCATE, dl, TmpVT, Res);
31891 
31892         // Now widen to 128 bits.
31893         unsigned NumConcats = 128 / TmpVT.getSizeInBits();
31894         MVT ConcatVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8 * NumConcats);
31895         SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(TmpVT));
31896         ConcatOps[0] = Res;
31897         Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
31898       }
31899 
31900       Results.push_back(Res);
31901       if (IsStrict)
31902         Results.push_back(Chain);
31903 
31904       return;
31905     }
31906 
31907     if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
31908       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
31909              "Unexpected type action!");
31910 
31911       // Try to create a 128 bit vector, but don't exceed a 32 bit element.
31912       unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
31913       MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
31914                                        VT.getVectorNumElements());
31915       SDValue Res;
31916       SDValue Chain;
31917       if (IsStrict) {
31918         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
31919                           {N->getOperand(0), Src});
31920         Chain = Res.getValue(1);
31921       } else
31922         Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
31923 
31924       // Preserve what we know about the size of the original result. If the
31925       // result is v2i32, we have to manually widen the assert.
31926       if (PromoteVT == MVT::v2i32)
31927         Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
31928                           DAG.getUNDEF(MVT::v2i32));
31929 
31930       Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext, dl,
31931                         Res.getValueType(), Res,
31932                         DAG.getValueType(VT.getVectorElementType()));
31933 
31934       if (PromoteVT == MVT::v2i32)
31935         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
31936                           DAG.getIntPtrConstant(0, dl));
31937 
31938       // Truncate back to the original width.
31939       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
31940 
31941       // Now widen to 128 bits.
31942       unsigned NumConcats = 128 / VT.getSizeInBits();
31943       MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
31944                                       VT.getVectorNumElements() * NumConcats);
31945       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
31946       ConcatOps[0] = Res;
31947       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
31948       Results.push_back(Res);
31949       if (IsStrict)
31950         Results.push_back(Chain);
31951       return;
31952     }
31953 
31954 
31955     if (VT == MVT::v2i32) {
31956       assert((!IsStrict || IsSigned || Subtarget.hasAVX512()) &&
31957              "Strict unsigned conversion requires AVX512");
31958       assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
31959       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
31960              "Unexpected type action!");
31961       if (Src.getValueType() == MVT::v2f64) {
31962         if (!IsSigned && !Subtarget.hasAVX512()) {
31963           SDValue Res =
31964               expandFP_TO_UINT_SSE(MVT::v4i32, Src, dl, DAG, Subtarget);
31965           Results.push_back(Res);
31966           return;
31967         }
31968 
31969         unsigned Opc;
31970         if (IsStrict)
31971           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
31972         else
31973           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
31974 
31975         // If we have VLX we can emit a target specific FP_TO_UINT node,.
31976         if (!IsSigned && !Subtarget.hasVLX()) {
31977           // Otherwise we can defer to the generic legalizer which will widen
31978           // the input as well. This will be further widened during op
31979           // legalization to v8i32<-v8f64.
31980           // For strict nodes we'll need to widen ourselves.
31981           // FIXME: Fix the type legalizer to safely widen strict nodes?
31982           if (!IsStrict)
31983             return;
31984           Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
31985                             DAG.getConstantFP(0.0, dl, MVT::v2f64));
31986           Opc = N->getOpcode();
31987         }
31988         SDValue Res;
31989         SDValue Chain;
31990         if (IsStrict) {
31991           Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
31992                             {N->getOperand(0), Src});
31993           Chain = Res.getValue(1);
31994         } else {
31995           Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
31996         }
31997         Results.push_back(Res);
31998         if (IsStrict)
31999           Results.push_back(Chain);
32000         return;
32001       }
32002 
32003       // Custom widen strict v2f32->v2i32 by padding with zeros.
32004       // FIXME: Should generic type legalizer do this?
32005       if (Src.getValueType() == MVT::v2f32 && IsStrict) {
32006         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
32007                           DAG.getConstantFP(0.0, dl, MVT::v2f32));
32008         SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
32009                                   {N->getOperand(0), Src});
32010         Results.push_back(Res);
32011         Results.push_back(Res.getValue(1));
32012         return;
32013       }
32014 
32015       // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
32016       // so early out here.
32017       return;
32018     }
32019 
32020     assert(!VT.isVector() && "Vectors should have been handled above!");
32021 
32022     if ((Subtarget.hasDQI() && VT == MVT::i64 &&
32023          (SrcVT == MVT::f32 || SrcVT == MVT::f64)) ||
32024         (Subtarget.hasFP16() && SrcVT == MVT::f16)) {
32025       assert(!Subtarget.is64Bit() && "i64 should be legal");
32026       unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
32027       // If we use a 128-bit result we might need to use a target specific node.
32028       unsigned SrcElts =
32029           std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
32030       MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
32031       MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
32032       unsigned Opc = N->getOpcode();
32033       if (NumElts != SrcElts) {
32034         if (IsStrict)
32035           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
32036         else
32037           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
32038       }
32039 
32040       SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
32041       SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
32042                                 DAG.getConstantFP(0.0, dl, VecInVT), Src,
32043                                 ZeroIdx);
32044       SDValue Chain;
32045       if (IsStrict) {
32046         SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
32047         Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
32048         Chain = Res.getValue(1);
32049       } else
32050         Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
32051       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
32052       Results.push_back(Res);
32053       if (IsStrict)
32054         Results.push_back(Chain);
32055       return;
32056     }
32057 
32058     if (VT == MVT::i128 && Subtarget.isTargetWin64()) {
32059       SDValue Chain;
32060       SDValue V = LowerWin64_FP_TO_INT128(SDValue(N, 0), DAG, Chain);
32061       Results.push_back(V);
32062       if (IsStrict)
32063         Results.push_back(Chain);
32064       return;
32065     }
32066 
32067     SDValue Chain;
32068     if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
32069       Results.push_back(V);
32070       if (IsStrict)
32071         Results.push_back(Chain);
32072     }
32073     return;
32074   }
32075   case ISD::LRINT:
32076   case ISD::LLRINT: {
32077     if (SDValue V = LRINT_LLRINTHelper(N, DAG))
32078       Results.push_back(V);
32079     return;
32080   }
32081 
32082   case ISD::SINT_TO_FP:
32083   case ISD::STRICT_SINT_TO_FP:
32084   case ISD::UINT_TO_FP:
32085   case ISD::STRICT_UINT_TO_FP: {
32086     bool IsStrict = N->isStrictFPOpcode();
32087     bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
32088                     N->getOpcode() == ISD::STRICT_SINT_TO_FP;
32089     EVT VT = N->getValueType(0);
32090     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32091     if (VT.getVectorElementType() == MVT::f16 && Subtarget.hasFP16() &&
32092         Subtarget.hasVLX()) {
32093       if (Src.getValueType().getVectorElementType() == MVT::i16)
32094         return;
32095 
32096       if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2i32)
32097         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
32098                           IsStrict ? DAG.getConstant(0, dl, MVT::v2i32)
32099                                    : DAG.getUNDEF(MVT::v2i32));
32100       if (IsStrict) {
32101         unsigned Opc =
32102             IsSigned ? X86ISD::STRICT_CVTSI2P : X86ISD::STRICT_CVTUI2P;
32103         SDValue Res = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
32104                                   {N->getOperand(0), Src});
32105         Results.push_back(Res);
32106         Results.push_back(Res.getValue(1));
32107       } else {
32108         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
32109         Results.push_back(DAG.getNode(Opc, dl, MVT::v8f16, Src));
32110       }
32111       return;
32112     }
32113     if (VT != MVT::v2f32)
32114       return;
32115     EVT SrcVT = Src.getValueType();
32116     if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
32117       if (IsStrict) {
32118         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
32119                                 : X86ISD::STRICT_CVTUI2P;
32120         SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
32121                                   {N->getOperand(0), Src});
32122         Results.push_back(Res);
32123         Results.push_back(Res.getValue(1));
32124       } else {
32125         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
32126         Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
32127       }
32128       return;
32129     }
32130     if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
32131         Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
32132       SDValue Zero = DAG.getConstant(0, dl, SrcVT);
32133       SDValue One  = DAG.getConstant(1, dl, SrcVT);
32134       SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
32135                                  DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
32136                                  DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
32137       SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
32138       SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
32139       SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
32140       for (int i = 0; i != 2; ++i) {
32141         SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
32142                                   SignSrc, DAG.getIntPtrConstant(i, dl));
32143         if (IsStrict)
32144           SignCvts[i] =
32145               DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
32146                           {N->getOperand(0), Elt});
32147         else
32148           SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Elt);
32149       };
32150       SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
32151       SDValue Slow, Chain;
32152       if (IsStrict) {
32153         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
32154                             SignCvts[0].getValue(1), SignCvts[1].getValue(1));
32155         Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
32156                            {Chain, SignCvt, SignCvt});
32157         Chain = Slow.getValue(1);
32158       } else {
32159         Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
32160       }
32161       IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
32162       IsNeg =
32163           DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
32164       SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
32165       Results.push_back(Cvt);
32166       if (IsStrict)
32167         Results.push_back(Chain);
32168       return;
32169     }
32170 
32171     if (SrcVT != MVT::v2i32)
32172       return;
32173 
32174     if (IsSigned || Subtarget.hasAVX512()) {
32175       if (!IsStrict)
32176         return;
32177 
32178       // Custom widen strict v2i32->v2f32 to avoid scalarization.
32179       // FIXME: Should generic type legalizer do this?
32180       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
32181                         DAG.getConstant(0, dl, MVT::v2i32));
32182       SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
32183                                 {N->getOperand(0), Src});
32184       Results.push_back(Res);
32185       Results.push_back(Res.getValue(1));
32186       return;
32187     }
32188 
32189     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
32190     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
32191     SDValue VBias =
32192         DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
32193     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
32194                              DAG.getBitcast(MVT::v2i64, VBias));
32195     Or = DAG.getBitcast(MVT::v2f64, Or);
32196     if (IsStrict) {
32197       SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
32198                                 {N->getOperand(0), Or, VBias});
32199       SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
32200                                 {MVT::v4f32, MVT::Other},
32201                                 {Sub.getValue(1), Sub});
32202       Results.push_back(Res);
32203       Results.push_back(Res.getValue(1));
32204     } else {
32205       // TODO: Are there any fast-math-flags to propagate here?
32206       SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
32207       Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
32208     }
32209     return;
32210   }
32211   case ISD::STRICT_FP_ROUND:
32212   case ISD::FP_ROUND: {
32213     bool IsStrict = N->isStrictFPOpcode();
32214     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32215     EVT VT = N->getValueType(0);
32216     EVT NewVT = VT.getVectorElementType() == MVT::f16 ? MVT::v8f16 : MVT::v4f32;
32217     if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2f32) {
32218       SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f32)
32219                              : DAG.getUNDEF(MVT::v2f32);
32220       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src, Ext);
32221     }
32222     if (!isTypeLegal(Src.getValueType()))
32223       return;
32224     SDValue V;
32225     if (IsStrict)
32226       V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {NewVT, MVT::Other},
32227                       {N->getOperand(0), Src});
32228     else
32229       V = DAG.getNode(X86ISD::VFPROUND, dl, NewVT, Src);
32230     Results.push_back(V);
32231     if (IsStrict)
32232       Results.push_back(V.getValue(1));
32233     return;
32234   }
32235   case ISD::FP_EXTEND:
32236   case ISD::STRICT_FP_EXTEND: {
32237     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
32238     // No other ValueType for FP_EXTEND should reach this point.
32239     assert(N->getValueType(0) == MVT::v2f32 &&
32240            "Do not know how to legalize this Node");
32241     if (!Subtarget.hasFP16() || !Subtarget.hasVLX())
32242       return;
32243     bool IsStrict = N->isStrictFPOpcode();
32244     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32245     SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f16)
32246                            : DAG.getUNDEF(MVT::v2f16);
32247     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f16, Src, Ext);
32248     if (IsStrict)
32249       V = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::v4f32, MVT::Other},
32250                       {N->getOperand(0), V});
32251     else
32252       V = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, V);
32253     Results.push_back(V);
32254     if (IsStrict)
32255       Results.push_back(V.getValue(1));
32256     return;
32257   }
32258   case ISD::INTRINSIC_W_CHAIN: {
32259     unsigned IntNo = N->getConstantOperandVal(1);
32260     switch (IntNo) {
32261     default : llvm_unreachable("Do not know how to custom type "
32262                                "legalize this intrinsic operation!");
32263     case Intrinsic::x86_rdtsc:
32264       return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
32265                                      Results);
32266     case Intrinsic::x86_rdtscp:
32267       return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
32268                                      Results);
32269     case Intrinsic::x86_rdpmc:
32270       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
32271                                   Results);
32272       return;
32273     case Intrinsic::x86_xgetbv:
32274       expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
32275                                   Results);
32276       return;
32277     }
32278   }
32279   case ISD::READCYCLECOUNTER: {
32280     return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
32281   }
32282   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
32283     EVT T = N->getValueType(0);
32284     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
32285     bool Regs64bit = T == MVT::i128;
32286     assert((!Regs64bit || Subtarget.hasCmpxchg16b()) &&
32287            "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B");
32288     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
32289     SDValue cpInL, cpInH;
32290     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
32291                         DAG.getConstant(0, dl, HalfT));
32292     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
32293                         DAG.getConstant(1, dl, HalfT));
32294     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
32295                              Regs64bit ? X86::RAX : X86::EAX,
32296                              cpInL, SDValue());
32297     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
32298                              Regs64bit ? X86::RDX : X86::EDX,
32299                              cpInH, cpInL.getValue(1));
32300     SDValue swapInL, swapInH;
32301     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
32302                           DAG.getConstant(0, dl, HalfT));
32303     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
32304                           DAG.getConstant(1, dl, HalfT));
32305     swapInH =
32306         DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
32307                          swapInH, cpInH.getValue(1));
32308 
32309     // In 64-bit mode we might need the base pointer in RBX, but we can't know
32310     // until later. So we keep the RBX input in a vreg and use a custom
32311     // inserter.
32312     // Since RBX will be a reserved register the register allocator will not
32313     // make sure its value will be properly saved and restored around this
32314     // live-range.
32315     SDValue Result;
32316     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
32317     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
32318     if (Regs64bit) {
32319       SDValue Ops[] = {swapInH.getValue(0), N->getOperand(1), swapInL,
32320                        swapInH.getValue(1)};
32321       Result =
32322           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG16_DAG, dl, Tys, Ops, T, MMO);
32323     } else {
32324       swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl, X86::EBX, swapInL,
32325                                  swapInH.getValue(1));
32326       SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
32327                        swapInL.getValue(1)};
32328       Result =
32329           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, T, MMO);
32330     }
32331 
32332     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
32333                                         Regs64bit ? X86::RAX : X86::EAX,
32334                                         HalfT, Result.getValue(1));
32335     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
32336                                         Regs64bit ? X86::RDX : X86::EDX,
32337                                         HalfT, cpOutL.getValue(2));
32338     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
32339 
32340     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
32341                                         MVT::i32, cpOutH.getValue(2));
32342     SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
32343     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
32344 
32345     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
32346     Results.push_back(Success);
32347     Results.push_back(EFLAGS.getValue(1));
32348     return;
32349   }
32350   case ISD::ATOMIC_LOAD: {
32351     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
32352     bool NoImplicitFloatOps =
32353         DAG.getMachineFunction().getFunction().hasFnAttribute(
32354             Attribute::NoImplicitFloat);
32355     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
32356       auto *Node = cast<AtomicSDNode>(N);
32357       if (Subtarget.hasSSE1()) {
32358         // Use a VZEXT_LOAD which will be selected as MOVQ or XORPS+MOVLPS.
32359         // Then extract the lower 64-bits.
32360         MVT LdVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
32361         SDVTList Tys = DAG.getVTList(LdVT, MVT::Other);
32362         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
32363         SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
32364                                              MVT::i64, Node->getMemOperand());
32365         if (Subtarget.hasSSE2()) {
32366           SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
32367                                     DAG.getIntPtrConstant(0, dl));
32368           Results.push_back(Res);
32369           Results.push_back(Ld.getValue(1));
32370           return;
32371         }
32372         // We use an alternative sequence for SSE1 that extracts as v2f32 and
32373         // then casts to i64. This avoids a 128-bit stack temporary being
32374         // created by type legalization if we were to cast v4f32->v2i64.
32375         SDValue Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Ld,
32376                                   DAG.getIntPtrConstant(0, dl));
32377         Res = DAG.getBitcast(MVT::i64, Res);
32378         Results.push_back(Res);
32379         Results.push_back(Ld.getValue(1));
32380         return;
32381       }
32382       if (Subtarget.hasX87()) {
32383         // First load this into an 80-bit X87 register. This will put the whole
32384         // integer into the significand.
32385         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
32386         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
32387         SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD,
32388                                                  dl, Tys, Ops, MVT::i64,
32389                                                  Node->getMemOperand());
32390         SDValue Chain = Result.getValue(1);
32391 
32392         // Now store the X87 register to a stack temporary and convert to i64.
32393         // This store is not atomic and doesn't need to be.
32394         // FIXME: We don't need a stack temporary if the result of the load
32395         // is already being stored. We could just directly store there.
32396         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
32397         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
32398         MachinePointerInfo MPI =
32399             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
32400         SDValue StoreOps[] = { Chain, Result, StackPtr };
32401         Chain = DAG.getMemIntrinsicNode(
32402             X86ISD::FIST, dl, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
32403             MPI, None /*Align*/, MachineMemOperand::MOStore);
32404 
32405         // Finally load the value back from the stack temporary and return it.
32406         // This load is not atomic and doesn't need to be.
32407         // This load will be further type legalized.
32408         Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
32409         Results.push_back(Result);
32410         Results.push_back(Result.getValue(1));
32411         return;
32412       }
32413     }
32414     // TODO: Use MOVLPS when SSE1 is available?
32415     // Delegate to generic TypeLegalization. Situations we can really handle
32416     // should have already been dealt with by AtomicExpandPass.cpp.
32417     break;
32418   }
32419   case ISD::ATOMIC_SWAP:
32420   case ISD::ATOMIC_LOAD_ADD:
32421   case ISD::ATOMIC_LOAD_SUB:
32422   case ISD::ATOMIC_LOAD_AND:
32423   case ISD::ATOMIC_LOAD_OR:
32424   case ISD::ATOMIC_LOAD_XOR:
32425   case ISD::ATOMIC_LOAD_NAND:
32426   case ISD::ATOMIC_LOAD_MIN:
32427   case ISD::ATOMIC_LOAD_MAX:
32428   case ISD::ATOMIC_LOAD_UMIN:
32429   case ISD::ATOMIC_LOAD_UMAX:
32430     // Delegate to generic TypeLegalization. Situations we can really handle
32431     // should have already been dealt with by AtomicExpandPass.cpp.
32432     break;
32433 
32434   case ISD::BITCAST: {
32435     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
32436     EVT DstVT = N->getValueType(0);
32437     EVT SrcVT = N->getOperand(0).getValueType();
32438 
32439     // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
32440     // we can split using the k-register rather than memory.
32441     if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
32442       assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
32443       SDValue Lo, Hi;
32444       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
32445       Lo = DAG.getBitcast(MVT::i32, Lo);
32446       Hi = DAG.getBitcast(MVT::i32, Hi);
32447       SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
32448       Results.push_back(Res);
32449       return;
32450     }
32451 
32452     if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
32453       // FIXME: Use v4f32 for SSE1?
32454       assert(Subtarget.hasSSE2() && "Requires SSE2");
32455       assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&
32456              "Unexpected type action!");
32457       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
32458       SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64,
32459                                 N->getOperand(0));
32460       Res = DAG.getBitcast(WideVT, Res);
32461       Results.push_back(Res);
32462       return;
32463     }
32464 
32465     return;
32466   }
32467   case ISD::MGATHER: {
32468     EVT VT = N->getValueType(0);
32469     if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
32470         (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
32471       auto *Gather = cast<MaskedGatherSDNode>(N);
32472       SDValue Index = Gather->getIndex();
32473       if (Index.getValueType() != MVT::v2i64)
32474         return;
32475       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32476              "Unexpected type action!");
32477       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
32478       SDValue Mask = Gather->getMask();
32479       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
32480       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
32481                                      Gather->getPassThru(),
32482                                      DAG.getUNDEF(VT));
32483       if (!Subtarget.hasVLX()) {
32484         // We need to widen the mask, but the instruction will only use 2
32485         // of its elements. So we can use undef.
32486         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
32487                            DAG.getUNDEF(MVT::v2i1));
32488         Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
32489       }
32490       SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
32491                         Gather->getBasePtr(), Index, Gather->getScale() };
32492       SDValue Res = DAG.getMemIntrinsicNode(
32493           X86ISD::MGATHER, dl, DAG.getVTList(WideVT, MVT::Other), Ops,
32494           Gather->getMemoryVT(), Gather->getMemOperand());
32495       Results.push_back(Res);
32496       Results.push_back(Res.getValue(1));
32497       return;
32498     }
32499     return;
32500   }
32501   case ISD::LOAD: {
32502     // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
32503     // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
32504     // cast since type legalization will try to use an i64 load.
32505     MVT VT = N->getSimpleValueType(0);
32506     assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
32507     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32508            "Unexpected type action!");
32509     if (!ISD::isNON_EXTLoad(N))
32510       return;
32511     auto *Ld = cast<LoadSDNode>(N);
32512     if (Subtarget.hasSSE2()) {
32513       MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
32514       SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
32515                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
32516                                 Ld->getMemOperand()->getFlags());
32517       SDValue Chain = Res.getValue(1);
32518       MVT VecVT = MVT::getVectorVT(LdVT, 2);
32519       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
32520       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
32521       Res = DAG.getBitcast(WideVT, Res);
32522       Results.push_back(Res);
32523       Results.push_back(Chain);
32524       return;
32525     }
32526     assert(Subtarget.hasSSE1() && "Expected SSE");
32527     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
32528     SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
32529     SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
32530                                           MVT::i64, Ld->getMemOperand());
32531     Results.push_back(Res);
32532     Results.push_back(Res.getValue(1));
32533     return;
32534   }
32535   case ISD::ADDRSPACECAST: {
32536     SDValue V = LowerADDRSPACECAST(SDValue(N,0), DAG);
32537     Results.push_back(V);
32538     return;
32539   }
32540   case ISD::BITREVERSE:
32541     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
32542     assert(Subtarget.hasXOP() && "Expected XOP");
32543     // We can use VPPERM by copying to a vector register and back. We'll need
32544     // to move the scalar in two i32 pieces.
32545     Results.push_back(LowerBITREVERSE(SDValue(N, 0), Subtarget, DAG));
32546     return;
32547   }
32548 }
32549 
32550 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
32551   switch ((X86ISD::NodeType)Opcode) {
32552   case X86ISD::FIRST_NUMBER:       break;
32553 #define NODE_NAME_CASE(NODE) case X86ISD::NODE: return "X86ISD::" #NODE;
32554   NODE_NAME_CASE(BSF)
32555   NODE_NAME_CASE(BSR)
32556   NODE_NAME_CASE(FSHL)
32557   NODE_NAME_CASE(FSHR)
32558   NODE_NAME_CASE(FAND)
32559   NODE_NAME_CASE(FANDN)
32560   NODE_NAME_CASE(FOR)
32561   NODE_NAME_CASE(FXOR)
32562   NODE_NAME_CASE(FILD)
32563   NODE_NAME_CASE(FIST)
32564   NODE_NAME_CASE(FP_TO_INT_IN_MEM)
32565   NODE_NAME_CASE(FLD)
32566   NODE_NAME_CASE(FST)
32567   NODE_NAME_CASE(CALL)
32568   NODE_NAME_CASE(CALL_RVMARKER)
32569   NODE_NAME_CASE(BT)
32570   NODE_NAME_CASE(CMP)
32571   NODE_NAME_CASE(FCMP)
32572   NODE_NAME_CASE(STRICT_FCMP)
32573   NODE_NAME_CASE(STRICT_FCMPS)
32574   NODE_NAME_CASE(COMI)
32575   NODE_NAME_CASE(UCOMI)
32576   NODE_NAME_CASE(CMPM)
32577   NODE_NAME_CASE(CMPMM)
32578   NODE_NAME_CASE(STRICT_CMPM)
32579   NODE_NAME_CASE(CMPMM_SAE)
32580   NODE_NAME_CASE(SETCC)
32581   NODE_NAME_CASE(SETCC_CARRY)
32582   NODE_NAME_CASE(FSETCC)
32583   NODE_NAME_CASE(FSETCCM)
32584   NODE_NAME_CASE(FSETCCM_SAE)
32585   NODE_NAME_CASE(CMOV)
32586   NODE_NAME_CASE(BRCOND)
32587   NODE_NAME_CASE(RET_FLAG)
32588   NODE_NAME_CASE(IRET)
32589   NODE_NAME_CASE(REP_STOS)
32590   NODE_NAME_CASE(REP_MOVS)
32591   NODE_NAME_CASE(GlobalBaseReg)
32592   NODE_NAME_CASE(Wrapper)
32593   NODE_NAME_CASE(WrapperRIP)
32594   NODE_NAME_CASE(MOVQ2DQ)
32595   NODE_NAME_CASE(MOVDQ2Q)
32596   NODE_NAME_CASE(MMX_MOVD2W)
32597   NODE_NAME_CASE(MMX_MOVW2D)
32598   NODE_NAME_CASE(PEXTRB)
32599   NODE_NAME_CASE(PEXTRW)
32600   NODE_NAME_CASE(INSERTPS)
32601   NODE_NAME_CASE(PINSRB)
32602   NODE_NAME_CASE(PINSRW)
32603   NODE_NAME_CASE(PSHUFB)
32604   NODE_NAME_CASE(ANDNP)
32605   NODE_NAME_CASE(BLENDI)
32606   NODE_NAME_CASE(BLENDV)
32607   NODE_NAME_CASE(HADD)
32608   NODE_NAME_CASE(HSUB)
32609   NODE_NAME_CASE(FHADD)
32610   NODE_NAME_CASE(FHSUB)
32611   NODE_NAME_CASE(CONFLICT)
32612   NODE_NAME_CASE(FMAX)
32613   NODE_NAME_CASE(FMAXS)
32614   NODE_NAME_CASE(FMAX_SAE)
32615   NODE_NAME_CASE(FMAXS_SAE)
32616   NODE_NAME_CASE(FMIN)
32617   NODE_NAME_CASE(FMINS)
32618   NODE_NAME_CASE(FMIN_SAE)
32619   NODE_NAME_CASE(FMINS_SAE)
32620   NODE_NAME_CASE(FMAXC)
32621   NODE_NAME_CASE(FMINC)
32622   NODE_NAME_CASE(FRSQRT)
32623   NODE_NAME_CASE(FRCP)
32624   NODE_NAME_CASE(EXTRQI)
32625   NODE_NAME_CASE(INSERTQI)
32626   NODE_NAME_CASE(TLSADDR)
32627   NODE_NAME_CASE(TLSBASEADDR)
32628   NODE_NAME_CASE(TLSCALL)
32629   NODE_NAME_CASE(EH_SJLJ_SETJMP)
32630   NODE_NAME_CASE(EH_SJLJ_LONGJMP)
32631   NODE_NAME_CASE(EH_SJLJ_SETUP_DISPATCH)
32632   NODE_NAME_CASE(EH_RETURN)
32633   NODE_NAME_CASE(TC_RETURN)
32634   NODE_NAME_CASE(FNSTCW16m)
32635   NODE_NAME_CASE(FLDCW16m)
32636   NODE_NAME_CASE(LCMPXCHG_DAG)
32637   NODE_NAME_CASE(LCMPXCHG8_DAG)
32638   NODE_NAME_CASE(LCMPXCHG16_DAG)
32639   NODE_NAME_CASE(LCMPXCHG16_SAVE_RBX_DAG)
32640   NODE_NAME_CASE(LADD)
32641   NODE_NAME_CASE(LSUB)
32642   NODE_NAME_CASE(LOR)
32643   NODE_NAME_CASE(LXOR)
32644   NODE_NAME_CASE(LAND)
32645   NODE_NAME_CASE(VZEXT_MOVL)
32646   NODE_NAME_CASE(VZEXT_LOAD)
32647   NODE_NAME_CASE(VEXTRACT_STORE)
32648   NODE_NAME_CASE(VTRUNC)
32649   NODE_NAME_CASE(VTRUNCS)
32650   NODE_NAME_CASE(VTRUNCUS)
32651   NODE_NAME_CASE(VMTRUNC)
32652   NODE_NAME_CASE(VMTRUNCS)
32653   NODE_NAME_CASE(VMTRUNCUS)
32654   NODE_NAME_CASE(VTRUNCSTORES)
32655   NODE_NAME_CASE(VTRUNCSTOREUS)
32656   NODE_NAME_CASE(VMTRUNCSTORES)
32657   NODE_NAME_CASE(VMTRUNCSTOREUS)
32658   NODE_NAME_CASE(VFPEXT)
32659   NODE_NAME_CASE(STRICT_VFPEXT)
32660   NODE_NAME_CASE(VFPEXT_SAE)
32661   NODE_NAME_CASE(VFPEXTS)
32662   NODE_NAME_CASE(VFPEXTS_SAE)
32663   NODE_NAME_CASE(VFPROUND)
32664   NODE_NAME_CASE(STRICT_VFPROUND)
32665   NODE_NAME_CASE(VMFPROUND)
32666   NODE_NAME_CASE(VFPROUND_RND)
32667   NODE_NAME_CASE(VFPROUNDS)
32668   NODE_NAME_CASE(VFPROUNDS_RND)
32669   NODE_NAME_CASE(VSHLDQ)
32670   NODE_NAME_CASE(VSRLDQ)
32671   NODE_NAME_CASE(VSHL)
32672   NODE_NAME_CASE(VSRL)
32673   NODE_NAME_CASE(VSRA)
32674   NODE_NAME_CASE(VSHLI)
32675   NODE_NAME_CASE(VSRLI)
32676   NODE_NAME_CASE(VSRAI)
32677   NODE_NAME_CASE(VSHLV)
32678   NODE_NAME_CASE(VSRLV)
32679   NODE_NAME_CASE(VSRAV)
32680   NODE_NAME_CASE(VROTLI)
32681   NODE_NAME_CASE(VROTRI)
32682   NODE_NAME_CASE(VPPERM)
32683   NODE_NAME_CASE(CMPP)
32684   NODE_NAME_CASE(STRICT_CMPP)
32685   NODE_NAME_CASE(PCMPEQ)
32686   NODE_NAME_CASE(PCMPGT)
32687   NODE_NAME_CASE(PHMINPOS)
32688   NODE_NAME_CASE(ADD)
32689   NODE_NAME_CASE(SUB)
32690   NODE_NAME_CASE(ADC)
32691   NODE_NAME_CASE(SBB)
32692   NODE_NAME_CASE(SMUL)
32693   NODE_NAME_CASE(UMUL)
32694   NODE_NAME_CASE(OR)
32695   NODE_NAME_CASE(XOR)
32696   NODE_NAME_CASE(AND)
32697   NODE_NAME_CASE(BEXTR)
32698   NODE_NAME_CASE(BEXTRI)
32699   NODE_NAME_CASE(BZHI)
32700   NODE_NAME_CASE(PDEP)
32701   NODE_NAME_CASE(PEXT)
32702   NODE_NAME_CASE(MUL_IMM)
32703   NODE_NAME_CASE(MOVMSK)
32704   NODE_NAME_CASE(PTEST)
32705   NODE_NAME_CASE(TESTP)
32706   NODE_NAME_CASE(KORTEST)
32707   NODE_NAME_CASE(KTEST)
32708   NODE_NAME_CASE(KADD)
32709   NODE_NAME_CASE(KSHIFTL)
32710   NODE_NAME_CASE(KSHIFTR)
32711   NODE_NAME_CASE(PACKSS)
32712   NODE_NAME_CASE(PACKUS)
32713   NODE_NAME_CASE(PALIGNR)
32714   NODE_NAME_CASE(VALIGN)
32715   NODE_NAME_CASE(VSHLD)
32716   NODE_NAME_CASE(VSHRD)
32717   NODE_NAME_CASE(VSHLDV)
32718   NODE_NAME_CASE(VSHRDV)
32719   NODE_NAME_CASE(PSHUFD)
32720   NODE_NAME_CASE(PSHUFHW)
32721   NODE_NAME_CASE(PSHUFLW)
32722   NODE_NAME_CASE(SHUFP)
32723   NODE_NAME_CASE(SHUF128)
32724   NODE_NAME_CASE(MOVLHPS)
32725   NODE_NAME_CASE(MOVHLPS)
32726   NODE_NAME_CASE(MOVDDUP)
32727   NODE_NAME_CASE(MOVSHDUP)
32728   NODE_NAME_CASE(MOVSLDUP)
32729   NODE_NAME_CASE(MOVSD)
32730   NODE_NAME_CASE(MOVSS)
32731   NODE_NAME_CASE(MOVSH)
32732   NODE_NAME_CASE(UNPCKL)
32733   NODE_NAME_CASE(UNPCKH)
32734   NODE_NAME_CASE(VBROADCAST)
32735   NODE_NAME_CASE(VBROADCAST_LOAD)
32736   NODE_NAME_CASE(VBROADCASTM)
32737   NODE_NAME_CASE(SUBV_BROADCAST_LOAD)
32738   NODE_NAME_CASE(VPERMILPV)
32739   NODE_NAME_CASE(VPERMILPI)
32740   NODE_NAME_CASE(VPERM2X128)
32741   NODE_NAME_CASE(VPERMV)
32742   NODE_NAME_CASE(VPERMV3)
32743   NODE_NAME_CASE(VPERMI)
32744   NODE_NAME_CASE(VPTERNLOG)
32745   NODE_NAME_CASE(VFIXUPIMM)
32746   NODE_NAME_CASE(VFIXUPIMM_SAE)
32747   NODE_NAME_CASE(VFIXUPIMMS)
32748   NODE_NAME_CASE(VFIXUPIMMS_SAE)
32749   NODE_NAME_CASE(VRANGE)
32750   NODE_NAME_CASE(VRANGE_SAE)
32751   NODE_NAME_CASE(VRANGES)
32752   NODE_NAME_CASE(VRANGES_SAE)
32753   NODE_NAME_CASE(PMULUDQ)
32754   NODE_NAME_CASE(PMULDQ)
32755   NODE_NAME_CASE(PSADBW)
32756   NODE_NAME_CASE(DBPSADBW)
32757   NODE_NAME_CASE(VASTART_SAVE_XMM_REGS)
32758   NODE_NAME_CASE(VAARG_64)
32759   NODE_NAME_CASE(VAARG_X32)
32760   NODE_NAME_CASE(DYN_ALLOCA)
32761   NODE_NAME_CASE(MEMBARRIER)
32762   NODE_NAME_CASE(MFENCE)
32763   NODE_NAME_CASE(SEG_ALLOCA)
32764   NODE_NAME_CASE(PROBED_ALLOCA)
32765   NODE_NAME_CASE(RDRAND)
32766   NODE_NAME_CASE(RDSEED)
32767   NODE_NAME_CASE(RDPKRU)
32768   NODE_NAME_CASE(WRPKRU)
32769   NODE_NAME_CASE(VPMADDUBSW)
32770   NODE_NAME_CASE(VPMADDWD)
32771   NODE_NAME_CASE(VPSHA)
32772   NODE_NAME_CASE(VPSHL)
32773   NODE_NAME_CASE(VPCOM)
32774   NODE_NAME_CASE(VPCOMU)
32775   NODE_NAME_CASE(VPERMIL2)
32776   NODE_NAME_CASE(FMSUB)
32777   NODE_NAME_CASE(STRICT_FMSUB)
32778   NODE_NAME_CASE(FNMADD)
32779   NODE_NAME_CASE(STRICT_FNMADD)
32780   NODE_NAME_CASE(FNMSUB)
32781   NODE_NAME_CASE(STRICT_FNMSUB)
32782   NODE_NAME_CASE(FMADDSUB)
32783   NODE_NAME_CASE(FMSUBADD)
32784   NODE_NAME_CASE(FMADD_RND)
32785   NODE_NAME_CASE(FNMADD_RND)
32786   NODE_NAME_CASE(FMSUB_RND)
32787   NODE_NAME_CASE(FNMSUB_RND)
32788   NODE_NAME_CASE(FMADDSUB_RND)
32789   NODE_NAME_CASE(FMSUBADD_RND)
32790   NODE_NAME_CASE(VFMADDC)
32791   NODE_NAME_CASE(VFMADDC_RND)
32792   NODE_NAME_CASE(VFCMADDC)
32793   NODE_NAME_CASE(VFCMADDC_RND)
32794   NODE_NAME_CASE(VFMULC)
32795   NODE_NAME_CASE(VFMULC_RND)
32796   NODE_NAME_CASE(VFCMULC)
32797   NODE_NAME_CASE(VFCMULC_RND)
32798   NODE_NAME_CASE(VFMULCSH)
32799   NODE_NAME_CASE(VFMULCSH_RND)
32800   NODE_NAME_CASE(VFCMULCSH)
32801   NODE_NAME_CASE(VFCMULCSH_RND)
32802   NODE_NAME_CASE(VFMADDCSH)
32803   NODE_NAME_CASE(VFMADDCSH_RND)
32804   NODE_NAME_CASE(VFCMADDCSH)
32805   NODE_NAME_CASE(VFCMADDCSH_RND)
32806   NODE_NAME_CASE(VPMADD52H)
32807   NODE_NAME_CASE(VPMADD52L)
32808   NODE_NAME_CASE(VRNDSCALE)
32809   NODE_NAME_CASE(STRICT_VRNDSCALE)
32810   NODE_NAME_CASE(VRNDSCALE_SAE)
32811   NODE_NAME_CASE(VRNDSCALES)
32812   NODE_NAME_CASE(VRNDSCALES_SAE)
32813   NODE_NAME_CASE(VREDUCE)
32814   NODE_NAME_CASE(VREDUCE_SAE)
32815   NODE_NAME_CASE(VREDUCES)
32816   NODE_NAME_CASE(VREDUCES_SAE)
32817   NODE_NAME_CASE(VGETMANT)
32818   NODE_NAME_CASE(VGETMANT_SAE)
32819   NODE_NAME_CASE(VGETMANTS)
32820   NODE_NAME_CASE(VGETMANTS_SAE)
32821   NODE_NAME_CASE(PCMPESTR)
32822   NODE_NAME_CASE(PCMPISTR)
32823   NODE_NAME_CASE(XTEST)
32824   NODE_NAME_CASE(COMPRESS)
32825   NODE_NAME_CASE(EXPAND)
32826   NODE_NAME_CASE(SELECTS)
32827   NODE_NAME_CASE(ADDSUB)
32828   NODE_NAME_CASE(RCP14)
32829   NODE_NAME_CASE(RCP14S)
32830   NODE_NAME_CASE(RCP28)
32831   NODE_NAME_CASE(RCP28_SAE)
32832   NODE_NAME_CASE(RCP28S)
32833   NODE_NAME_CASE(RCP28S_SAE)
32834   NODE_NAME_CASE(EXP2)
32835   NODE_NAME_CASE(EXP2_SAE)
32836   NODE_NAME_CASE(RSQRT14)
32837   NODE_NAME_CASE(RSQRT14S)
32838   NODE_NAME_CASE(RSQRT28)
32839   NODE_NAME_CASE(RSQRT28_SAE)
32840   NODE_NAME_CASE(RSQRT28S)
32841   NODE_NAME_CASE(RSQRT28S_SAE)
32842   NODE_NAME_CASE(FADD_RND)
32843   NODE_NAME_CASE(FADDS)
32844   NODE_NAME_CASE(FADDS_RND)
32845   NODE_NAME_CASE(FSUB_RND)
32846   NODE_NAME_CASE(FSUBS)
32847   NODE_NAME_CASE(FSUBS_RND)
32848   NODE_NAME_CASE(FMUL_RND)
32849   NODE_NAME_CASE(FMULS)
32850   NODE_NAME_CASE(FMULS_RND)
32851   NODE_NAME_CASE(FDIV_RND)
32852   NODE_NAME_CASE(FDIVS)
32853   NODE_NAME_CASE(FDIVS_RND)
32854   NODE_NAME_CASE(FSQRT_RND)
32855   NODE_NAME_CASE(FSQRTS)
32856   NODE_NAME_CASE(FSQRTS_RND)
32857   NODE_NAME_CASE(FGETEXP)
32858   NODE_NAME_CASE(FGETEXP_SAE)
32859   NODE_NAME_CASE(FGETEXPS)
32860   NODE_NAME_CASE(FGETEXPS_SAE)
32861   NODE_NAME_CASE(SCALEF)
32862   NODE_NAME_CASE(SCALEF_RND)
32863   NODE_NAME_CASE(SCALEFS)
32864   NODE_NAME_CASE(SCALEFS_RND)
32865   NODE_NAME_CASE(AVG)
32866   NODE_NAME_CASE(MULHRS)
32867   NODE_NAME_CASE(SINT_TO_FP_RND)
32868   NODE_NAME_CASE(UINT_TO_FP_RND)
32869   NODE_NAME_CASE(CVTTP2SI)
32870   NODE_NAME_CASE(CVTTP2UI)
32871   NODE_NAME_CASE(STRICT_CVTTP2SI)
32872   NODE_NAME_CASE(STRICT_CVTTP2UI)
32873   NODE_NAME_CASE(MCVTTP2SI)
32874   NODE_NAME_CASE(MCVTTP2UI)
32875   NODE_NAME_CASE(CVTTP2SI_SAE)
32876   NODE_NAME_CASE(CVTTP2UI_SAE)
32877   NODE_NAME_CASE(CVTTS2SI)
32878   NODE_NAME_CASE(CVTTS2UI)
32879   NODE_NAME_CASE(CVTTS2SI_SAE)
32880   NODE_NAME_CASE(CVTTS2UI_SAE)
32881   NODE_NAME_CASE(CVTSI2P)
32882   NODE_NAME_CASE(CVTUI2P)
32883   NODE_NAME_CASE(STRICT_CVTSI2P)
32884   NODE_NAME_CASE(STRICT_CVTUI2P)
32885   NODE_NAME_CASE(MCVTSI2P)
32886   NODE_NAME_CASE(MCVTUI2P)
32887   NODE_NAME_CASE(VFPCLASS)
32888   NODE_NAME_CASE(VFPCLASSS)
32889   NODE_NAME_CASE(MULTISHIFT)
32890   NODE_NAME_CASE(SCALAR_SINT_TO_FP)
32891   NODE_NAME_CASE(SCALAR_SINT_TO_FP_RND)
32892   NODE_NAME_CASE(SCALAR_UINT_TO_FP)
32893   NODE_NAME_CASE(SCALAR_UINT_TO_FP_RND)
32894   NODE_NAME_CASE(CVTPS2PH)
32895   NODE_NAME_CASE(STRICT_CVTPS2PH)
32896   NODE_NAME_CASE(MCVTPS2PH)
32897   NODE_NAME_CASE(CVTPH2PS)
32898   NODE_NAME_CASE(STRICT_CVTPH2PS)
32899   NODE_NAME_CASE(CVTPH2PS_SAE)
32900   NODE_NAME_CASE(CVTP2SI)
32901   NODE_NAME_CASE(CVTP2UI)
32902   NODE_NAME_CASE(MCVTP2SI)
32903   NODE_NAME_CASE(MCVTP2UI)
32904   NODE_NAME_CASE(CVTP2SI_RND)
32905   NODE_NAME_CASE(CVTP2UI_RND)
32906   NODE_NAME_CASE(CVTS2SI)
32907   NODE_NAME_CASE(CVTS2UI)
32908   NODE_NAME_CASE(CVTS2SI_RND)
32909   NODE_NAME_CASE(CVTS2UI_RND)
32910   NODE_NAME_CASE(CVTNE2PS2BF16)
32911   NODE_NAME_CASE(CVTNEPS2BF16)
32912   NODE_NAME_CASE(MCVTNEPS2BF16)
32913   NODE_NAME_CASE(DPBF16PS)
32914   NODE_NAME_CASE(LWPINS)
32915   NODE_NAME_CASE(MGATHER)
32916   NODE_NAME_CASE(MSCATTER)
32917   NODE_NAME_CASE(VPDPBUSD)
32918   NODE_NAME_CASE(VPDPBUSDS)
32919   NODE_NAME_CASE(VPDPWSSD)
32920   NODE_NAME_CASE(VPDPWSSDS)
32921   NODE_NAME_CASE(VPSHUFBITQMB)
32922   NODE_NAME_CASE(GF2P8MULB)
32923   NODE_NAME_CASE(GF2P8AFFINEQB)
32924   NODE_NAME_CASE(GF2P8AFFINEINVQB)
32925   NODE_NAME_CASE(NT_CALL)
32926   NODE_NAME_CASE(NT_BRIND)
32927   NODE_NAME_CASE(UMWAIT)
32928   NODE_NAME_CASE(TPAUSE)
32929   NODE_NAME_CASE(ENQCMD)
32930   NODE_NAME_CASE(ENQCMDS)
32931   NODE_NAME_CASE(VP2INTERSECT)
32932   NODE_NAME_CASE(AESENC128KL)
32933   NODE_NAME_CASE(AESDEC128KL)
32934   NODE_NAME_CASE(AESENC256KL)
32935   NODE_NAME_CASE(AESDEC256KL)
32936   NODE_NAME_CASE(AESENCWIDE128KL)
32937   NODE_NAME_CASE(AESDECWIDE128KL)
32938   NODE_NAME_CASE(AESENCWIDE256KL)
32939   NODE_NAME_CASE(AESDECWIDE256KL)
32940   NODE_NAME_CASE(TESTUI)
32941   }
32942   return nullptr;
32943 #undef NODE_NAME_CASE
32944 }
32945 
32946 /// Return true if the addressing mode represented by AM is legal for this
32947 /// target, for a load/store of the specified type.
32948 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
32949                                               const AddrMode &AM, Type *Ty,
32950                                               unsigned AS,
32951                                               Instruction *I) const {
32952   // X86 supports extremely general addressing modes.
32953   CodeModel::Model M = getTargetMachine().getCodeModel();
32954 
32955   // X86 allows a sign-extended 32-bit immediate field as a displacement.
32956   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
32957     return false;
32958 
32959   if (AM.BaseGV) {
32960     unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
32961 
32962     // If a reference to this global requires an extra load, we can't fold it.
32963     if (isGlobalStubReference(GVFlags))
32964       return false;
32965 
32966     // If BaseGV requires a register for the PIC base, we cannot also have a
32967     // BaseReg specified.
32968     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
32969       return false;
32970 
32971     // If lower 4G is not available, then we must use rip-relative addressing.
32972     if ((M != CodeModel::Small || isPositionIndependent()) &&
32973         Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
32974       return false;
32975   }
32976 
32977   switch (AM.Scale) {
32978   case 0:
32979   case 1:
32980   case 2:
32981   case 4:
32982   case 8:
32983     // These scales always work.
32984     break;
32985   case 3:
32986   case 5:
32987   case 9:
32988     // These scales are formed with basereg+scalereg.  Only accept if there is
32989     // no basereg yet.
32990     if (AM.HasBaseReg)
32991       return false;
32992     break;
32993   default:  // Other stuff never works.
32994     return false;
32995   }
32996 
32997   return true;
32998 }
32999 
33000 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
33001   unsigned Bits = Ty->getScalarSizeInBits();
33002 
33003   // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
33004   // Splitting for v32i8/v16i16 on XOP+AVX2 targets is still preferred.
33005   if (Subtarget.hasXOP() &&
33006       (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
33007     return false;
33008 
33009   // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
33010   // shifts just as cheap as scalar ones.
33011   if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
33012     return false;
33013 
33014   // AVX512BW has shifts such as vpsllvw.
33015   if (Subtarget.hasBWI() && Bits == 16)
33016       return false;
33017 
33018   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
33019   // fully general vector.
33020   return true;
33021 }
33022 
33023 bool X86TargetLowering::isBinOp(unsigned Opcode) const {
33024   switch (Opcode) {
33025   // These are non-commutative binops.
33026   // TODO: Add more X86ISD opcodes once we have test coverage.
33027   case X86ISD::ANDNP:
33028   case X86ISD::PCMPGT:
33029   case X86ISD::FMAX:
33030   case X86ISD::FMIN:
33031   case X86ISD::FANDN:
33032     return true;
33033   }
33034 
33035   return TargetLoweringBase::isBinOp(Opcode);
33036 }
33037 
33038 bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
33039   switch (Opcode) {
33040   // TODO: Add more X86ISD opcodes once we have test coverage.
33041   case X86ISD::AVG:
33042   case X86ISD::PCMPEQ:
33043   case X86ISD::PMULDQ:
33044   case X86ISD::PMULUDQ:
33045   case X86ISD::FMAXC:
33046   case X86ISD::FMINC:
33047   case X86ISD::FAND:
33048   case X86ISD::FOR:
33049   case X86ISD::FXOR:
33050     return true;
33051   }
33052 
33053   return TargetLoweringBase::isCommutativeBinOp(Opcode);
33054 }
33055 
33056 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
33057   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
33058     return false;
33059   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
33060   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
33061   return NumBits1 > NumBits2;
33062 }
33063 
33064 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
33065   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
33066     return false;
33067 
33068   if (!isTypeLegal(EVT::getEVT(Ty1)))
33069     return false;
33070 
33071   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
33072 
33073   // Assuming the caller doesn't have a zeroext or signext return parameter,
33074   // truncation all the way down to i1 is valid.
33075   return true;
33076 }
33077 
33078 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
33079   return isInt<32>(Imm);
33080 }
33081 
33082 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
33083   // Can also use sub to handle negated immediates.
33084   return isInt<32>(Imm);
33085 }
33086 
33087 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
33088   return isInt<32>(Imm);
33089 }
33090 
33091 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
33092   if (!VT1.isScalarInteger() || !VT2.isScalarInteger())
33093     return false;
33094   unsigned NumBits1 = VT1.getSizeInBits();
33095   unsigned NumBits2 = VT2.getSizeInBits();
33096   return NumBits1 > NumBits2;
33097 }
33098 
33099 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
33100   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
33101   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
33102 }
33103 
33104 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
33105   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
33106   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
33107 }
33108 
33109 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
33110   EVT VT1 = Val.getValueType();
33111   if (isZExtFree(VT1, VT2))
33112     return true;
33113 
33114   if (Val.getOpcode() != ISD::LOAD)
33115     return false;
33116 
33117   if (!VT1.isSimple() || !VT1.isInteger() ||
33118       !VT2.isSimple() || !VT2.isInteger())
33119     return false;
33120 
33121   switch (VT1.getSimpleVT().SimpleTy) {
33122   default: break;
33123   case MVT::i8:
33124   case MVT::i16:
33125   case MVT::i32:
33126     // X86 has 8, 16, and 32-bit zero-extending loads.
33127     return true;
33128   }
33129 
33130   return false;
33131 }
33132 
33133 bool X86TargetLowering::shouldSinkOperands(Instruction *I,
33134                                            SmallVectorImpl<Use *> &Ops) const {
33135   using namespace llvm::PatternMatch;
33136 
33137   FixedVectorType *VTy = dyn_cast<FixedVectorType>(I->getType());
33138   if (!VTy)
33139     return false;
33140 
33141   if (I->getOpcode() == Instruction::Mul &&
33142       VTy->getElementType()->isIntegerTy(64)) {
33143     for (auto &Op : I->operands()) {
33144       // Make sure we are not already sinking this operand
33145       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
33146         continue;
33147 
33148       // Look for PMULDQ pattern where the input is a sext_inreg from vXi32 or
33149       // the PMULUDQ pattern where the input is a zext_inreg from vXi32.
33150       if (Subtarget.hasSSE41() &&
33151           match(Op.get(), m_AShr(m_Shl(m_Value(), m_SpecificInt(32)),
33152                                  m_SpecificInt(32)))) {
33153         Ops.push_back(&cast<Instruction>(Op)->getOperandUse(0));
33154         Ops.push_back(&Op);
33155       } else if (Subtarget.hasSSE2() &&
33156                  match(Op.get(),
33157                        m_And(m_Value(), m_SpecificInt(UINT64_C(0xffffffff))))) {
33158         Ops.push_back(&Op);
33159       }
33160     }
33161 
33162     return !Ops.empty();
33163   }
33164 
33165   // A uniform shift amount in a vector shift or funnel shift may be much
33166   // cheaper than a generic variable vector shift, so make that pattern visible
33167   // to SDAG by sinking the shuffle instruction next to the shift.
33168   int ShiftAmountOpNum = -1;
33169   if (I->isShift())
33170     ShiftAmountOpNum = 1;
33171   else if (auto *II = dyn_cast<IntrinsicInst>(I)) {
33172     if (II->getIntrinsicID() == Intrinsic::fshl ||
33173         II->getIntrinsicID() == Intrinsic::fshr)
33174       ShiftAmountOpNum = 2;
33175   }
33176 
33177   if (ShiftAmountOpNum == -1)
33178     return false;
33179 
33180   auto *Shuf = dyn_cast<ShuffleVectorInst>(I->getOperand(ShiftAmountOpNum));
33181   if (Shuf && getSplatIndex(Shuf->getShuffleMask()) >= 0 &&
33182       isVectorShiftByScalarCheap(I->getType())) {
33183     Ops.push_back(&I->getOperandUse(ShiftAmountOpNum));
33184     return true;
33185   }
33186 
33187   return false;
33188 }
33189 
33190 bool X86TargetLowering::shouldConvertPhiType(Type *From, Type *To) const {
33191   if (!Subtarget.is64Bit())
33192     return false;
33193   return TargetLowering::shouldConvertPhiType(From, To);
33194 }
33195 
33196 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
33197   if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
33198     return false;
33199 
33200   EVT SrcVT = ExtVal.getOperand(0).getValueType();
33201 
33202   // There is no extending load for vXi1.
33203   if (SrcVT.getScalarType() == MVT::i1)
33204     return false;
33205 
33206   return true;
33207 }
33208 
33209 bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
33210                                                    EVT VT) const {
33211   if (!Subtarget.hasAnyFMA())
33212     return false;
33213 
33214   VT = VT.getScalarType();
33215 
33216   if (!VT.isSimple())
33217     return false;
33218 
33219   switch (VT.getSimpleVT().SimpleTy) {
33220   case MVT::f16:
33221     return Subtarget.hasFP16();
33222   case MVT::f32:
33223   case MVT::f64:
33224     return true;
33225   default:
33226     break;
33227   }
33228 
33229   return false;
33230 }
33231 
33232 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
33233   // i16 instructions are longer (0x66 prefix) and potentially slower.
33234   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
33235 }
33236 
33237 /// Targets can use this to indicate that they only support *some*
33238 /// VECTOR_SHUFFLE operations, those with specific masks.
33239 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
33240 /// are assumed to be legal.
33241 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
33242   if (!VT.isSimple())
33243     return false;
33244 
33245   // Not for i1 vectors
33246   if (VT.getSimpleVT().getScalarType() == MVT::i1)
33247     return false;
33248 
33249   // Very little shuffling can be done for 64-bit vectors right now.
33250   if (VT.getSimpleVT().getSizeInBits() == 64)
33251     return false;
33252 
33253   // We only care that the types being shuffled are legal. The lowering can
33254   // handle any possible shuffle mask that results.
33255   return isTypeLegal(VT.getSimpleVT());
33256 }
33257 
33258 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
33259                                                EVT VT) const {
33260   // Don't convert an 'and' into a shuffle that we don't directly support.
33261   // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
33262   if (!Subtarget.hasAVX2())
33263     if (VT == MVT::v32i8 || VT == MVT::v16i16)
33264       return false;
33265 
33266   // Just delegate to the generic legality, clear masks aren't special.
33267   return isShuffleMaskLegal(Mask, VT);
33268 }
33269 
33270 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
33271   // If the subtarget is using thunks, we need to not generate jump tables.
33272   if (Subtarget.useIndirectThunkBranches())
33273     return false;
33274 
33275   // Otherwise, fallback on the generic logic.
33276   return TargetLowering::areJTsAllowed(Fn);
33277 }
33278 
33279 //===----------------------------------------------------------------------===//
33280 //                           X86 Scheduler Hooks
33281 //===----------------------------------------------------------------------===//
33282 
33283 // Returns true if EFLAG is consumed after this iterator in the rest of the
33284 // basic block or any successors of the basic block.
33285 static bool isEFLAGSLiveAfter(MachineBasicBlock::iterator Itr,
33286                               MachineBasicBlock *BB) {
33287   // Scan forward through BB for a use/def of EFLAGS.
33288   for (MachineBasicBlock::iterator miI = std::next(Itr), miE = BB->end();
33289          miI != miE; ++miI) {
33290     const MachineInstr& mi = *miI;
33291     if (mi.readsRegister(X86::EFLAGS))
33292       return true;
33293     // If we found a def, we can stop searching.
33294     if (mi.definesRegister(X86::EFLAGS))
33295       return false;
33296   }
33297 
33298   // If we hit the end of the block, check whether EFLAGS is live into a
33299   // successor.
33300   for (MachineBasicBlock *Succ : BB->successors())
33301     if (Succ->isLiveIn(X86::EFLAGS))
33302       return true;
33303 
33304   return false;
33305 }
33306 
33307 /// Utility function to emit xbegin specifying the start of an RTM region.
33308 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
33309                                      const TargetInstrInfo *TII) {
33310   const DebugLoc &DL = MI.getDebugLoc();
33311 
33312   const BasicBlock *BB = MBB->getBasicBlock();
33313   MachineFunction::iterator I = ++MBB->getIterator();
33314 
33315   // For the v = xbegin(), we generate
33316   //
33317   // thisMBB:
33318   //  xbegin sinkMBB
33319   //
33320   // mainMBB:
33321   //  s0 = -1
33322   //
33323   // fallBB:
33324   //  eax = # XABORT_DEF
33325   //  s1 = eax
33326   //
33327   // sinkMBB:
33328   //  v = phi(s0/mainBB, s1/fallBB)
33329 
33330   MachineBasicBlock *thisMBB = MBB;
33331   MachineFunction *MF = MBB->getParent();
33332   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
33333   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
33334   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
33335   MF->insert(I, mainMBB);
33336   MF->insert(I, fallMBB);
33337   MF->insert(I, sinkMBB);
33338 
33339   if (isEFLAGSLiveAfter(MI, MBB)) {
33340     mainMBB->addLiveIn(X86::EFLAGS);
33341     fallMBB->addLiveIn(X86::EFLAGS);
33342     sinkMBB->addLiveIn(X86::EFLAGS);
33343   }
33344 
33345   // Transfer the remainder of BB and its successor edges to sinkMBB.
33346   sinkMBB->splice(sinkMBB->begin(), MBB,
33347                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
33348   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
33349 
33350   MachineRegisterInfo &MRI = MF->getRegInfo();
33351   Register DstReg = MI.getOperand(0).getReg();
33352   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
33353   Register mainDstReg = MRI.createVirtualRegister(RC);
33354   Register fallDstReg = MRI.createVirtualRegister(RC);
33355 
33356   // thisMBB:
33357   //  xbegin fallMBB
33358   //  # fallthrough to mainMBB
33359   //  # abortion to fallMBB
33360   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
33361   thisMBB->addSuccessor(mainMBB);
33362   thisMBB->addSuccessor(fallMBB);
33363 
33364   // mainMBB:
33365   //  mainDstReg := -1
33366   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
33367   BuildMI(mainMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
33368   mainMBB->addSuccessor(sinkMBB);
33369 
33370   // fallMBB:
33371   //  ; pseudo instruction to model hardware's definition from XABORT
33372   //  EAX := XABORT_DEF
33373   //  fallDstReg := EAX
33374   BuildMI(fallMBB, DL, TII->get(X86::XABORT_DEF));
33375   BuildMI(fallMBB, DL, TII->get(TargetOpcode::COPY), fallDstReg)
33376       .addReg(X86::EAX);
33377   fallMBB->addSuccessor(sinkMBB);
33378 
33379   // sinkMBB:
33380   //  DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
33381   BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI), DstReg)
33382       .addReg(mainDstReg).addMBB(mainMBB)
33383       .addReg(fallDstReg).addMBB(fallMBB);
33384 
33385   MI.eraseFromParent();
33386   return sinkMBB;
33387 }
33388 
33389 MachineBasicBlock *
33390 X86TargetLowering::EmitVAARGWithCustomInserter(MachineInstr &MI,
33391                                                MachineBasicBlock *MBB) const {
33392   // Emit va_arg instruction on X86-64.
33393 
33394   // Operands to this pseudo-instruction:
33395   // 0  ) Output        : destination address (reg)
33396   // 1-5) Input         : va_list address (addr, i64mem)
33397   // 6  ) ArgSize       : Size (in bytes) of vararg type
33398   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
33399   // 8  ) Align         : Alignment of type
33400   // 9  ) EFLAGS (implicit-def)
33401 
33402   assert(MI.getNumOperands() == 10 && "VAARG should have 10 operands!");
33403   static_assert(X86::AddrNumOperands == 5, "VAARG assumes 5 address operands");
33404 
33405   Register DestReg = MI.getOperand(0).getReg();
33406   MachineOperand &Base = MI.getOperand(1);
33407   MachineOperand &Scale = MI.getOperand(2);
33408   MachineOperand &Index = MI.getOperand(3);
33409   MachineOperand &Disp = MI.getOperand(4);
33410   MachineOperand &Segment = MI.getOperand(5);
33411   unsigned ArgSize = MI.getOperand(6).getImm();
33412   unsigned ArgMode = MI.getOperand(7).getImm();
33413   Align Alignment = Align(MI.getOperand(8).getImm());
33414 
33415   MachineFunction *MF = MBB->getParent();
33416 
33417   // Memory Reference
33418   assert(MI.hasOneMemOperand() && "Expected VAARG to have one memoperand");
33419 
33420   MachineMemOperand *OldMMO = MI.memoperands().front();
33421 
33422   // Clone the MMO into two separate MMOs for loading and storing
33423   MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
33424       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
33425   MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
33426       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
33427 
33428   // Machine Information
33429   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33430   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
33431   const TargetRegisterClass *AddrRegClass =
33432       getRegClassFor(getPointerTy(MBB->getParent()->getDataLayout()));
33433   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
33434   const DebugLoc &DL = MI.getDebugLoc();
33435 
33436   // struct va_list {
33437   //   i32   gp_offset
33438   //   i32   fp_offset
33439   //   i64   overflow_area (address)
33440   //   i64   reg_save_area (address)
33441   // }
33442   // sizeof(va_list) = 24
33443   // alignment(va_list) = 8
33444 
33445   unsigned TotalNumIntRegs = 6;
33446   unsigned TotalNumXMMRegs = 8;
33447   bool UseGPOffset = (ArgMode == 1);
33448   bool UseFPOffset = (ArgMode == 2);
33449   unsigned MaxOffset = TotalNumIntRegs * 8 +
33450                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
33451 
33452   /* Align ArgSize to a multiple of 8 */
33453   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
33454   bool NeedsAlign = (Alignment > 8);
33455 
33456   MachineBasicBlock *thisMBB = MBB;
33457   MachineBasicBlock *overflowMBB;
33458   MachineBasicBlock *offsetMBB;
33459   MachineBasicBlock *endMBB;
33460 
33461   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
33462   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
33463   unsigned OffsetReg = 0;
33464 
33465   if (!UseGPOffset && !UseFPOffset) {
33466     // If we only pull from the overflow region, we don't create a branch.
33467     // We don't need to alter control flow.
33468     OffsetDestReg = 0; // unused
33469     OverflowDestReg = DestReg;
33470 
33471     offsetMBB = nullptr;
33472     overflowMBB = thisMBB;
33473     endMBB = thisMBB;
33474   } else {
33475     // First emit code to check if gp_offset (or fp_offset) is below the bound.
33476     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
33477     // If not, pull from overflow_area. (branch to overflowMBB)
33478     //
33479     //       thisMBB
33480     //         |     .
33481     //         |        .
33482     //     offsetMBB   overflowMBB
33483     //         |        .
33484     //         |     .
33485     //        endMBB
33486 
33487     // Registers for the PHI in endMBB
33488     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
33489     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
33490 
33491     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
33492     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
33493     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
33494     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
33495 
33496     MachineFunction::iterator MBBIter = ++MBB->getIterator();
33497 
33498     // Insert the new basic blocks
33499     MF->insert(MBBIter, offsetMBB);
33500     MF->insert(MBBIter, overflowMBB);
33501     MF->insert(MBBIter, endMBB);
33502 
33503     // Transfer the remainder of MBB and its successor edges to endMBB.
33504     endMBB->splice(endMBB->begin(), thisMBB,
33505                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
33506     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
33507 
33508     // Make offsetMBB and overflowMBB successors of thisMBB
33509     thisMBB->addSuccessor(offsetMBB);
33510     thisMBB->addSuccessor(overflowMBB);
33511 
33512     // endMBB is a successor of both offsetMBB and overflowMBB
33513     offsetMBB->addSuccessor(endMBB);
33514     overflowMBB->addSuccessor(endMBB);
33515 
33516     // Load the offset value into a register
33517     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
33518     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
33519         .add(Base)
33520         .add(Scale)
33521         .add(Index)
33522         .addDisp(Disp, UseFPOffset ? 4 : 0)
33523         .add(Segment)
33524         .setMemRefs(LoadOnlyMMO);
33525 
33526     // Check if there is enough room left to pull this argument.
33527     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
33528       .addReg(OffsetReg)
33529       .addImm(MaxOffset + 8 - ArgSizeA8);
33530 
33531     // Branch to "overflowMBB" if offset >= max
33532     // Fall through to "offsetMBB" otherwise
33533     BuildMI(thisMBB, DL, TII->get(X86::JCC_1))
33534       .addMBB(overflowMBB).addImm(X86::COND_AE);
33535   }
33536 
33537   // In offsetMBB, emit code to use the reg_save_area.
33538   if (offsetMBB) {
33539     assert(OffsetReg != 0);
33540 
33541     // Read the reg_save_area address.
33542     Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
33543     BuildMI(
33544         offsetMBB, DL,
33545         TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
33546         RegSaveReg)
33547         .add(Base)
33548         .add(Scale)
33549         .add(Index)
33550         .addDisp(Disp, Subtarget.isTarget64BitLP64() ? 16 : 12)
33551         .add(Segment)
33552         .setMemRefs(LoadOnlyMMO);
33553 
33554     if (Subtarget.isTarget64BitLP64()) {
33555       // Zero-extend the offset
33556       Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
33557       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
33558           .addImm(0)
33559           .addReg(OffsetReg)
33560           .addImm(X86::sub_32bit);
33561 
33562       // Add the offset to the reg_save_area to get the final address.
33563       BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
33564           .addReg(OffsetReg64)
33565           .addReg(RegSaveReg);
33566     } else {
33567       // Add the offset to the reg_save_area to get the final address.
33568       BuildMI(offsetMBB, DL, TII->get(X86::ADD32rr), OffsetDestReg)
33569           .addReg(OffsetReg)
33570           .addReg(RegSaveReg);
33571     }
33572 
33573     // Compute the offset for the next argument
33574     Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
33575     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
33576       .addReg(OffsetReg)
33577       .addImm(UseFPOffset ? 16 : 8);
33578 
33579     // Store it back into the va_list.
33580     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
33581         .add(Base)
33582         .add(Scale)
33583         .add(Index)
33584         .addDisp(Disp, UseFPOffset ? 4 : 0)
33585         .add(Segment)
33586         .addReg(NextOffsetReg)
33587         .setMemRefs(StoreOnlyMMO);
33588 
33589     // Jump to endMBB
33590     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
33591       .addMBB(endMBB);
33592   }
33593 
33594   //
33595   // Emit code to use overflow area
33596   //
33597 
33598   // Load the overflow_area address into a register.
33599   Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
33600   BuildMI(overflowMBB, DL,
33601           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
33602           OverflowAddrReg)
33603       .add(Base)
33604       .add(Scale)
33605       .add(Index)
33606       .addDisp(Disp, 8)
33607       .add(Segment)
33608       .setMemRefs(LoadOnlyMMO);
33609 
33610   // If we need to align it, do so. Otherwise, just copy the address
33611   // to OverflowDestReg.
33612   if (NeedsAlign) {
33613     // Align the overflow address
33614     Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
33615 
33616     // aligned_addr = (addr + (align-1)) & ~(align-1)
33617     BuildMI(
33618         overflowMBB, DL,
33619         TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
33620         TmpReg)
33621         .addReg(OverflowAddrReg)
33622         .addImm(Alignment.value() - 1);
33623 
33624     BuildMI(
33625         overflowMBB, DL,
33626         TII->get(Subtarget.isTarget64BitLP64() ? X86::AND64ri32 : X86::AND32ri),
33627         OverflowDestReg)
33628         .addReg(TmpReg)
33629         .addImm(~(uint64_t)(Alignment.value() - 1));
33630   } else {
33631     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
33632       .addReg(OverflowAddrReg);
33633   }
33634 
33635   // Compute the next overflow address after this argument.
33636   // (the overflow address should be kept 8-byte aligned)
33637   Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
33638   BuildMI(
33639       overflowMBB, DL,
33640       TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
33641       NextAddrReg)
33642       .addReg(OverflowDestReg)
33643       .addImm(ArgSizeA8);
33644 
33645   // Store the new overflow address.
33646   BuildMI(overflowMBB, DL,
33647           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64mr : X86::MOV32mr))
33648       .add(Base)
33649       .add(Scale)
33650       .add(Index)
33651       .addDisp(Disp, 8)
33652       .add(Segment)
33653       .addReg(NextAddrReg)
33654       .setMemRefs(StoreOnlyMMO);
33655 
33656   // If we branched, emit the PHI to the front of endMBB.
33657   if (offsetMBB) {
33658     BuildMI(*endMBB, endMBB->begin(), DL,
33659             TII->get(X86::PHI), DestReg)
33660       .addReg(OffsetDestReg).addMBB(offsetMBB)
33661       .addReg(OverflowDestReg).addMBB(overflowMBB);
33662   }
33663 
33664   // Erase the pseudo instruction
33665   MI.eraseFromParent();
33666 
33667   return endMBB;
33668 }
33669 
33670 // The EFLAGS operand of SelectItr might be missing a kill marker
33671 // because there were multiple uses of EFLAGS, and ISel didn't know
33672 // which to mark. Figure out whether SelectItr should have had a
33673 // kill marker, and set it if it should. Returns the correct kill
33674 // marker value.
33675 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
33676                                      MachineBasicBlock* BB,
33677                                      const TargetRegisterInfo* TRI) {
33678   if (isEFLAGSLiveAfter(SelectItr, BB))
33679     return false;
33680 
33681   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
33682   // out. SelectMI should have a kill flag on EFLAGS.
33683   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
33684   return true;
33685 }
33686 
33687 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
33688 // together with other CMOV pseudo-opcodes into a single basic-block with
33689 // conditional jump around it.
33690 static bool isCMOVPseudo(MachineInstr &MI) {
33691   switch (MI.getOpcode()) {
33692   case X86::CMOV_FR16X:
33693   case X86::CMOV_FR32:
33694   case X86::CMOV_FR32X:
33695   case X86::CMOV_FR64:
33696   case X86::CMOV_FR64X:
33697   case X86::CMOV_GR8:
33698   case X86::CMOV_GR16:
33699   case X86::CMOV_GR32:
33700   case X86::CMOV_RFP32:
33701   case X86::CMOV_RFP64:
33702   case X86::CMOV_RFP80:
33703   case X86::CMOV_VR64:
33704   case X86::CMOV_VR128:
33705   case X86::CMOV_VR128X:
33706   case X86::CMOV_VR256:
33707   case X86::CMOV_VR256X:
33708   case X86::CMOV_VR512:
33709   case X86::CMOV_VK1:
33710   case X86::CMOV_VK2:
33711   case X86::CMOV_VK4:
33712   case X86::CMOV_VK8:
33713   case X86::CMOV_VK16:
33714   case X86::CMOV_VK32:
33715   case X86::CMOV_VK64:
33716     return true;
33717 
33718   default:
33719     return false;
33720   }
33721 }
33722 
33723 // Helper function, which inserts PHI functions into SinkMBB:
33724 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
33725 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
33726 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
33727 // the last PHI function inserted.
33728 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
33729     MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
33730     MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
33731     MachineBasicBlock *SinkMBB) {
33732   MachineFunction *MF = TrueMBB->getParent();
33733   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
33734   const DebugLoc &DL = MIItBegin->getDebugLoc();
33735 
33736   X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
33737   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
33738 
33739   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
33740 
33741   // As we are creating the PHIs, we have to be careful if there is more than
33742   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
33743   // PHIs have to reference the individual true/false inputs from earlier PHIs.
33744   // That also means that PHI construction must work forward from earlier to
33745   // later, and that the code must maintain a mapping from earlier PHI's
33746   // destination registers, and the registers that went into the PHI.
33747   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
33748   MachineInstrBuilder MIB;
33749 
33750   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
33751     Register DestReg = MIIt->getOperand(0).getReg();
33752     Register Op1Reg = MIIt->getOperand(1).getReg();
33753     Register Op2Reg = MIIt->getOperand(2).getReg();
33754 
33755     // If this CMOV we are generating is the opposite condition from
33756     // the jump we generated, then we have to swap the operands for the
33757     // PHI that is going to be generated.
33758     if (MIIt->getOperand(3).getImm() == OppCC)
33759       std::swap(Op1Reg, Op2Reg);
33760 
33761     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
33762       Op1Reg = RegRewriteTable[Op1Reg].first;
33763 
33764     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
33765       Op2Reg = RegRewriteTable[Op2Reg].second;
33766 
33767     MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
33768               .addReg(Op1Reg)
33769               .addMBB(FalseMBB)
33770               .addReg(Op2Reg)
33771               .addMBB(TrueMBB);
33772 
33773     // Add this PHI to the rewrite table.
33774     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
33775   }
33776 
33777   return MIB;
33778 }
33779 
33780 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
33781 MachineBasicBlock *
33782 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
33783                                              MachineInstr &SecondCascadedCMOV,
33784                                              MachineBasicBlock *ThisMBB) const {
33785   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33786   const DebugLoc &DL = FirstCMOV.getDebugLoc();
33787 
33788   // We lower cascaded CMOVs such as
33789   //
33790   //   (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
33791   //
33792   // to two successive branches.
33793   //
33794   // Without this, we would add a PHI between the two jumps, which ends up
33795   // creating a few copies all around. For instance, for
33796   //
33797   //    (sitofp (zext (fcmp une)))
33798   //
33799   // we would generate:
33800   //
33801   //         ucomiss %xmm1, %xmm0
33802   //         movss  <1.0f>, %xmm0
33803   //         movaps  %xmm0, %xmm1
33804   //         jne     .LBB5_2
33805   //         xorps   %xmm1, %xmm1
33806   // .LBB5_2:
33807   //         jp      .LBB5_4
33808   //         movaps  %xmm1, %xmm0
33809   // .LBB5_4:
33810   //         retq
33811   //
33812   // because this custom-inserter would have generated:
33813   //
33814   //   A
33815   //   | \
33816   //   |  B
33817   //   | /
33818   //   C
33819   //   | \
33820   //   |  D
33821   //   | /
33822   //   E
33823   //
33824   // A: X = ...; Y = ...
33825   // B: empty
33826   // C: Z = PHI [X, A], [Y, B]
33827   // D: empty
33828   // E: PHI [X, C], [Z, D]
33829   //
33830   // If we lower both CMOVs in a single step, we can instead generate:
33831   //
33832   //   A
33833   //   | \
33834   //   |  C
33835   //   | /|
33836   //   |/ |
33837   //   |  |
33838   //   |  D
33839   //   | /
33840   //   E
33841   //
33842   // A: X = ...; Y = ...
33843   // D: empty
33844   // E: PHI [X, A], [X, C], [Y, D]
33845   //
33846   // Which, in our sitofp/fcmp example, gives us something like:
33847   //
33848   //         ucomiss %xmm1, %xmm0
33849   //         movss  <1.0f>, %xmm0
33850   //         jne     .LBB5_4
33851   //         jp      .LBB5_4
33852   //         xorps   %xmm0, %xmm0
33853   // .LBB5_4:
33854   //         retq
33855   //
33856 
33857   // We lower cascaded CMOV into two successive branches to the same block.
33858   // EFLAGS is used by both, so mark it as live in the second.
33859   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
33860   MachineFunction *F = ThisMBB->getParent();
33861   MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
33862   MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
33863   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
33864 
33865   MachineFunction::iterator It = ++ThisMBB->getIterator();
33866   F->insert(It, FirstInsertedMBB);
33867   F->insert(It, SecondInsertedMBB);
33868   F->insert(It, SinkMBB);
33869 
33870   // For a cascaded CMOV, we lower it to two successive branches to
33871   // the same block (SinkMBB).  EFLAGS is used by both, so mark it as live in
33872   // the FirstInsertedMBB.
33873   FirstInsertedMBB->addLiveIn(X86::EFLAGS);
33874 
33875   // If the EFLAGS register isn't dead in the terminator, then claim that it's
33876   // live into the sink and copy blocks.
33877   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
33878   if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
33879       !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
33880     SecondInsertedMBB->addLiveIn(X86::EFLAGS);
33881     SinkMBB->addLiveIn(X86::EFLAGS);
33882   }
33883 
33884   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
33885   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
33886                   std::next(MachineBasicBlock::iterator(FirstCMOV)),
33887                   ThisMBB->end());
33888   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
33889 
33890   // Fallthrough block for ThisMBB.
33891   ThisMBB->addSuccessor(FirstInsertedMBB);
33892   // The true block target of the first branch is always SinkMBB.
33893   ThisMBB->addSuccessor(SinkMBB);
33894   // Fallthrough block for FirstInsertedMBB.
33895   FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
33896   // The true block for the branch of FirstInsertedMBB.
33897   FirstInsertedMBB->addSuccessor(SinkMBB);
33898   // This is fallthrough.
33899   SecondInsertedMBB->addSuccessor(SinkMBB);
33900 
33901   // Create the conditional branch instructions.
33902   X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
33903   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
33904 
33905   X86::CondCode SecondCC =
33906       X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
33907   BuildMI(FirstInsertedMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(SecondCC);
33908 
33909   //  SinkMBB:
33910   //   %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
33911   Register DestReg = FirstCMOV.getOperand(0).getReg();
33912   Register Op1Reg = FirstCMOV.getOperand(1).getReg();
33913   Register Op2Reg = FirstCMOV.getOperand(2).getReg();
33914   MachineInstrBuilder MIB =
33915       BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(X86::PHI), DestReg)
33916           .addReg(Op1Reg)
33917           .addMBB(SecondInsertedMBB)
33918           .addReg(Op2Reg)
33919           .addMBB(ThisMBB);
33920 
33921   // The second SecondInsertedMBB provides the same incoming value as the
33922   // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
33923   MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
33924   // Copy the PHI result to the register defined by the second CMOV.
33925   BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())), DL,
33926           TII->get(TargetOpcode::COPY),
33927           SecondCascadedCMOV.getOperand(0).getReg())
33928       .addReg(FirstCMOV.getOperand(0).getReg());
33929 
33930   // Now remove the CMOVs.
33931   FirstCMOV.eraseFromParent();
33932   SecondCascadedCMOV.eraseFromParent();
33933 
33934   return SinkMBB;
33935 }
33936 
33937 MachineBasicBlock *
33938 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
33939                                      MachineBasicBlock *ThisMBB) const {
33940   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33941   const DebugLoc &DL = MI.getDebugLoc();
33942 
33943   // To "insert" a SELECT_CC instruction, we actually have to insert the
33944   // diamond control-flow pattern.  The incoming instruction knows the
33945   // destination vreg to set, the condition code register to branch on, the
33946   // true/false values to select between and a branch opcode to use.
33947 
33948   //  ThisMBB:
33949   //  ...
33950   //   TrueVal = ...
33951   //   cmpTY ccX, r1, r2
33952   //   bCC copy1MBB
33953   //   fallthrough --> FalseMBB
33954 
33955   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
33956   // as described above, by inserting a BB, and then making a PHI at the join
33957   // point to select the true and false operands of the CMOV in the PHI.
33958   //
33959   // The code also handles two different cases of multiple CMOV opcodes
33960   // in a row.
33961   //
33962   // Case 1:
33963   // In this case, there are multiple CMOVs in a row, all which are based on
33964   // the same condition setting (or the exact opposite condition setting).
33965   // In this case we can lower all the CMOVs using a single inserted BB, and
33966   // then make a number of PHIs at the join point to model the CMOVs. The only
33967   // trickiness here, is that in a case like:
33968   //
33969   // t2 = CMOV cond1 t1, f1
33970   // t3 = CMOV cond1 t2, f2
33971   //
33972   // when rewriting this into PHIs, we have to perform some renaming on the
33973   // temps since you cannot have a PHI operand refer to a PHI result earlier
33974   // in the same block.  The "simple" but wrong lowering would be:
33975   //
33976   // t2 = PHI t1(BB1), f1(BB2)
33977   // t3 = PHI t2(BB1), f2(BB2)
33978   //
33979   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
33980   // renaming is to note that on the path through BB1, t2 is really just a
33981   // copy of t1, and do that renaming, properly generating:
33982   //
33983   // t2 = PHI t1(BB1), f1(BB2)
33984   // t3 = PHI t1(BB1), f2(BB2)
33985   //
33986   // Case 2:
33987   // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
33988   // function - EmitLoweredCascadedSelect.
33989 
33990   X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
33991   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
33992   MachineInstr *LastCMOV = &MI;
33993   MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
33994 
33995   // Check for case 1, where there are multiple CMOVs with the same condition
33996   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
33997   // number of jumps the most.
33998 
33999   if (isCMOVPseudo(MI)) {
34000     // See if we have a string of CMOVS with the same condition. Skip over
34001     // intervening debug insts.
34002     while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
34003            (NextMIIt->getOperand(3).getImm() == CC ||
34004             NextMIIt->getOperand(3).getImm() == OppCC)) {
34005       LastCMOV = &*NextMIIt;
34006       NextMIIt = next_nodbg(NextMIIt, ThisMBB->end());
34007     }
34008   }
34009 
34010   // This checks for case 2, but only do this if we didn't already find
34011   // case 1, as indicated by LastCMOV == MI.
34012   if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
34013       NextMIIt->getOpcode() == MI.getOpcode() &&
34014       NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
34015       NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
34016       NextMIIt->getOperand(1).isKill()) {
34017     return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
34018   }
34019 
34020   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
34021   MachineFunction *F = ThisMBB->getParent();
34022   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
34023   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
34024 
34025   MachineFunction::iterator It = ++ThisMBB->getIterator();
34026   F->insert(It, FalseMBB);
34027   F->insert(It, SinkMBB);
34028 
34029   // If the EFLAGS register isn't dead in the terminator, then claim that it's
34030   // live into the sink and copy blocks.
34031   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
34032   if (!LastCMOV->killsRegister(X86::EFLAGS) &&
34033       !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
34034     FalseMBB->addLiveIn(X86::EFLAGS);
34035     SinkMBB->addLiveIn(X86::EFLAGS);
34036   }
34037 
34038   // Transfer any debug instructions inside the CMOV sequence to the sunk block.
34039   auto DbgRange = llvm::make_range(MachineBasicBlock::iterator(MI),
34040                                    MachineBasicBlock::iterator(LastCMOV));
34041   for (MachineInstr &MI : llvm::make_early_inc_range(DbgRange))
34042     if (MI.isDebugInstr())
34043       SinkMBB->push_back(MI.removeFromParent());
34044 
34045   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
34046   SinkMBB->splice(SinkMBB->end(), ThisMBB,
34047                   std::next(MachineBasicBlock::iterator(LastCMOV)),
34048                   ThisMBB->end());
34049   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
34050 
34051   // Fallthrough block for ThisMBB.
34052   ThisMBB->addSuccessor(FalseMBB);
34053   // The true block target of the first (or only) branch is always a SinkMBB.
34054   ThisMBB->addSuccessor(SinkMBB);
34055   // Fallthrough block for FalseMBB.
34056   FalseMBB->addSuccessor(SinkMBB);
34057 
34058   // Create the conditional branch instruction.
34059   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
34060 
34061   //  SinkMBB:
34062   //   %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
34063   //  ...
34064   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
34065   MachineBasicBlock::iterator MIItEnd =
34066       std::next(MachineBasicBlock::iterator(LastCMOV));
34067   createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
34068 
34069   // Now remove the CMOV(s).
34070   ThisMBB->erase(MIItBegin, MIItEnd);
34071 
34072   return SinkMBB;
34073 }
34074 
34075 static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
34076   if (IsLP64) {
34077     if (isInt<8>(Imm))
34078       return X86::SUB64ri8;
34079     return X86::SUB64ri32;
34080   } else {
34081     if (isInt<8>(Imm))
34082       return X86::SUB32ri8;
34083     return X86::SUB32ri;
34084   }
34085 }
34086 
34087 MachineBasicBlock *
34088 X86TargetLowering::EmitLoweredProbedAlloca(MachineInstr &MI,
34089                                            MachineBasicBlock *MBB) const {
34090   MachineFunction *MF = MBB->getParent();
34091   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34092   const X86FrameLowering &TFI = *Subtarget.getFrameLowering();
34093   const DebugLoc &DL = MI.getDebugLoc();
34094   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
34095 
34096   const unsigned ProbeSize = getStackProbeSize(*MF);
34097 
34098   MachineRegisterInfo &MRI = MF->getRegInfo();
34099   MachineBasicBlock *testMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34100   MachineBasicBlock *tailMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34101   MachineBasicBlock *blockMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34102 
34103   MachineFunction::iterator MBBIter = ++MBB->getIterator();
34104   MF->insert(MBBIter, testMBB);
34105   MF->insert(MBBIter, blockMBB);
34106   MF->insert(MBBIter, tailMBB);
34107 
34108   Register sizeVReg = MI.getOperand(1).getReg();
34109 
34110   Register physSPReg = TFI.Uses64BitFramePtr ? X86::RSP : X86::ESP;
34111 
34112   Register TmpStackPtr = MRI.createVirtualRegister(
34113       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
34114   Register FinalStackPtr = MRI.createVirtualRegister(
34115       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
34116 
34117   BuildMI(*MBB, {MI}, DL, TII->get(TargetOpcode::COPY), TmpStackPtr)
34118       .addReg(physSPReg);
34119   {
34120     const unsigned Opc = TFI.Uses64BitFramePtr ? X86::SUB64rr : X86::SUB32rr;
34121     BuildMI(*MBB, {MI}, DL, TII->get(Opc), FinalStackPtr)
34122         .addReg(TmpStackPtr)
34123         .addReg(sizeVReg);
34124   }
34125 
34126   // test rsp size
34127 
34128   BuildMI(testMBB, DL,
34129           TII->get(TFI.Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
34130       .addReg(FinalStackPtr)
34131       .addReg(physSPReg);
34132 
34133   BuildMI(testMBB, DL, TII->get(X86::JCC_1))
34134       .addMBB(tailMBB)
34135       .addImm(X86::COND_GE);
34136   testMBB->addSuccessor(blockMBB);
34137   testMBB->addSuccessor(tailMBB);
34138 
34139   // Touch the block then extend it. This is done on the opposite side of
34140   // static probe where we allocate then touch, to avoid the need of probing the
34141   // tail of the static alloca. Possible scenarios are:
34142   //
34143   //       + ---- <- ------------ <- ------------- <- ------------ +
34144   //       |                                                       |
34145   // [free probe] -> [page alloc] -> [alloc probe] -> [tail alloc] + -> [dyn probe] -> [page alloc] -> [dyn probe] -> [tail alloc] +
34146   //                                                               |                                                               |
34147   //                                                               + <- ----------- <- ------------ <- ----------- <- ------------ +
34148   //
34149   // The property we want to enforce is to never have more than [page alloc] between two probes.
34150 
34151   const unsigned XORMIOpc =
34152       TFI.Uses64BitFramePtr ? X86::XOR64mi8 : X86::XOR32mi8;
34153   addRegOffset(BuildMI(blockMBB, DL, TII->get(XORMIOpc)), physSPReg, false, 0)
34154       .addImm(0);
34155 
34156   BuildMI(blockMBB, DL,
34157           TII->get(getSUBriOpcode(TFI.Uses64BitFramePtr, ProbeSize)), physSPReg)
34158       .addReg(physSPReg)
34159       .addImm(ProbeSize);
34160 
34161 
34162   BuildMI(blockMBB, DL, TII->get(X86::JMP_1)).addMBB(testMBB);
34163   blockMBB->addSuccessor(testMBB);
34164 
34165   // Replace original instruction by the expected stack ptr
34166   BuildMI(tailMBB, DL, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
34167       .addReg(FinalStackPtr);
34168 
34169   tailMBB->splice(tailMBB->end(), MBB,
34170                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
34171   tailMBB->transferSuccessorsAndUpdatePHIs(MBB);
34172   MBB->addSuccessor(testMBB);
34173 
34174   // Delete the original pseudo instruction.
34175   MI.eraseFromParent();
34176 
34177   // And we're done.
34178   return tailMBB;
34179 }
34180 
34181 MachineBasicBlock *
34182 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
34183                                         MachineBasicBlock *BB) const {
34184   MachineFunction *MF = BB->getParent();
34185   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34186   const DebugLoc &DL = MI.getDebugLoc();
34187   const BasicBlock *LLVM_BB = BB->getBasicBlock();
34188 
34189   assert(MF->shouldSplitStack());
34190 
34191   const bool Is64Bit = Subtarget.is64Bit();
34192   const bool IsLP64 = Subtarget.isTarget64BitLP64();
34193 
34194   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
34195   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
34196 
34197   // BB:
34198   //  ... [Till the alloca]
34199   // If stacklet is not large enough, jump to mallocMBB
34200   //
34201   // bumpMBB:
34202   //  Allocate by subtracting from RSP
34203   //  Jump to continueMBB
34204   //
34205   // mallocMBB:
34206   //  Allocate by call to runtime
34207   //
34208   // continueMBB:
34209   //  ...
34210   //  [rest of original BB]
34211   //
34212 
34213   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34214   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34215   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34216 
34217   MachineRegisterInfo &MRI = MF->getRegInfo();
34218   const TargetRegisterClass *AddrRegClass =
34219       getRegClassFor(getPointerTy(MF->getDataLayout()));
34220 
34221   Register mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
34222            bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
34223            tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
34224            SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
34225            sizeVReg = MI.getOperand(1).getReg(),
34226            physSPReg =
34227                IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
34228 
34229   MachineFunction::iterator MBBIter = ++BB->getIterator();
34230 
34231   MF->insert(MBBIter, bumpMBB);
34232   MF->insert(MBBIter, mallocMBB);
34233   MF->insert(MBBIter, continueMBB);
34234 
34235   continueMBB->splice(continueMBB->begin(), BB,
34236                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
34237   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
34238 
34239   // Add code to the main basic block to check if the stack limit has been hit,
34240   // and if so, jump to mallocMBB otherwise to bumpMBB.
34241   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
34242   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
34243     .addReg(tmpSPVReg).addReg(sizeVReg);
34244   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
34245     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
34246     .addReg(SPLimitVReg);
34247   BuildMI(BB, DL, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
34248 
34249   // bumpMBB simply decreases the stack pointer, since we know the current
34250   // stacklet has enough space.
34251   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
34252     .addReg(SPLimitVReg);
34253   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
34254     .addReg(SPLimitVReg);
34255   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
34256 
34257   // Calls into a routine in libgcc to allocate more space from the heap.
34258   const uint32_t *RegMask =
34259       Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
34260   if (IsLP64) {
34261     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
34262       .addReg(sizeVReg);
34263     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
34264       .addExternalSymbol("__morestack_allocate_stack_space")
34265       .addRegMask(RegMask)
34266       .addReg(X86::RDI, RegState::Implicit)
34267       .addReg(X86::RAX, RegState::ImplicitDefine);
34268   } else if (Is64Bit) {
34269     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
34270       .addReg(sizeVReg);
34271     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
34272       .addExternalSymbol("__morestack_allocate_stack_space")
34273       .addRegMask(RegMask)
34274       .addReg(X86::EDI, RegState::Implicit)
34275       .addReg(X86::EAX, RegState::ImplicitDefine);
34276   } else {
34277     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
34278       .addImm(12);
34279     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
34280     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
34281       .addExternalSymbol("__morestack_allocate_stack_space")
34282       .addRegMask(RegMask)
34283       .addReg(X86::EAX, RegState::ImplicitDefine);
34284   }
34285 
34286   if (!Is64Bit)
34287     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
34288       .addImm(16);
34289 
34290   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
34291     .addReg(IsLP64 ? X86::RAX : X86::EAX);
34292   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
34293 
34294   // Set up the CFG correctly.
34295   BB->addSuccessor(bumpMBB);
34296   BB->addSuccessor(mallocMBB);
34297   mallocMBB->addSuccessor(continueMBB);
34298   bumpMBB->addSuccessor(continueMBB);
34299 
34300   // Take care of the PHI nodes.
34301   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
34302           MI.getOperand(0).getReg())
34303       .addReg(mallocPtrVReg)
34304       .addMBB(mallocMBB)
34305       .addReg(bumpSPPtrVReg)
34306       .addMBB(bumpMBB);
34307 
34308   // Delete the original pseudo instruction.
34309   MI.eraseFromParent();
34310 
34311   // And we're done.
34312   return continueMBB;
34313 }
34314 
34315 MachineBasicBlock *
34316 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
34317                                        MachineBasicBlock *BB) const {
34318   MachineFunction *MF = BB->getParent();
34319   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
34320   MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
34321   const DebugLoc &DL = MI.getDebugLoc();
34322 
34323   assert(!isAsynchronousEHPersonality(
34324              classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
34325          "SEH does not use catchret!");
34326 
34327   // Only 32-bit EH needs to worry about manually restoring stack pointers.
34328   if (!Subtarget.is32Bit())
34329     return BB;
34330 
34331   // C++ EH creates a new target block to hold the restore code, and wires up
34332   // the new block to the return destination with a normal JMP_4.
34333   MachineBasicBlock *RestoreMBB =
34334       MF->CreateMachineBasicBlock(BB->getBasicBlock());
34335   assert(BB->succ_size() == 1);
34336   MF->insert(std::next(BB->getIterator()), RestoreMBB);
34337   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
34338   BB->addSuccessor(RestoreMBB);
34339   MI.getOperand(0).setMBB(RestoreMBB);
34340 
34341   // Marking this as an EH pad but not a funclet entry block causes PEI to
34342   // restore stack pointers in the block.
34343   RestoreMBB->setIsEHPad(true);
34344 
34345   auto RestoreMBBI = RestoreMBB->begin();
34346   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
34347   return BB;
34348 }
34349 
34350 MachineBasicBlock *
34351 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
34352                                       MachineBasicBlock *BB) const {
34353   // So, here we replace TLSADDR with the sequence:
34354   // adjust_stackdown -> TLSADDR -> adjust_stackup.
34355   // We need this because TLSADDR is lowered into calls
34356   // inside MC, therefore without the two markers shrink-wrapping
34357   // may push the prologue/epilogue pass them.
34358   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
34359   const DebugLoc &DL = MI.getDebugLoc();
34360   MachineFunction &MF = *BB->getParent();
34361 
34362   // Emit CALLSEQ_START right before the instruction.
34363   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
34364   MachineInstrBuilder CallseqStart =
34365     BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
34366   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
34367 
34368   // Emit CALLSEQ_END right after the instruction.
34369   // We don't call erase from parent because we want to keep the
34370   // original instruction around.
34371   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
34372   MachineInstrBuilder CallseqEnd =
34373     BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
34374   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
34375 
34376   return BB;
34377 }
34378 
34379 MachineBasicBlock *
34380 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
34381                                       MachineBasicBlock *BB) const {
34382   // This is pretty easy.  We're taking the value that we received from
34383   // our load from the relocation, sticking it in either RDI (x86-64)
34384   // or EAX and doing an indirect call.  The return value will then
34385   // be in the normal return register.
34386   MachineFunction *F = BB->getParent();
34387   const X86InstrInfo *TII = Subtarget.getInstrInfo();
34388   const DebugLoc &DL = MI.getDebugLoc();
34389 
34390   assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
34391   assert(MI.getOperand(3).isGlobal() && "This should be a global");
34392 
34393   // Get a register mask for the lowered call.
34394   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
34395   // proper register mask.
34396   const uint32_t *RegMask =
34397       Subtarget.is64Bit() ?
34398       Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
34399       Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
34400   if (Subtarget.is64Bit()) {
34401     MachineInstrBuilder MIB =
34402         BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
34403             .addReg(X86::RIP)
34404             .addImm(0)
34405             .addReg(0)
34406             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
34407                               MI.getOperand(3).getTargetFlags())
34408             .addReg(0);
34409     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
34410     addDirectMem(MIB, X86::RDI);
34411     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
34412   } else if (!isPositionIndependent()) {
34413     MachineInstrBuilder MIB =
34414         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
34415             .addReg(0)
34416             .addImm(0)
34417             .addReg(0)
34418             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
34419                               MI.getOperand(3).getTargetFlags())
34420             .addReg(0);
34421     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
34422     addDirectMem(MIB, X86::EAX);
34423     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
34424   } else {
34425     MachineInstrBuilder MIB =
34426         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
34427             .addReg(TII->getGlobalBaseReg(F))
34428             .addImm(0)
34429             .addReg(0)
34430             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
34431                               MI.getOperand(3).getTargetFlags())
34432             .addReg(0);
34433     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
34434     addDirectMem(MIB, X86::EAX);
34435     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
34436   }
34437 
34438   MI.eraseFromParent(); // The pseudo instruction is gone now.
34439   return BB;
34440 }
34441 
34442 static unsigned getOpcodeForIndirectThunk(unsigned RPOpc) {
34443   switch (RPOpc) {
34444   case X86::INDIRECT_THUNK_CALL32:
34445     return X86::CALLpcrel32;
34446   case X86::INDIRECT_THUNK_CALL64:
34447     return X86::CALL64pcrel32;
34448   case X86::INDIRECT_THUNK_TCRETURN32:
34449     return X86::TCRETURNdi;
34450   case X86::INDIRECT_THUNK_TCRETURN64:
34451     return X86::TCRETURNdi64;
34452   }
34453   llvm_unreachable("not indirect thunk opcode");
34454 }
34455 
34456 static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
34457                                           unsigned Reg) {
34458   if (Subtarget.useRetpolineExternalThunk()) {
34459     // When using an external thunk for retpolines, we pick names that match the
34460     // names GCC happens to use as well. This helps simplify the implementation
34461     // of the thunks for kernels where they have no easy ability to create
34462     // aliases and are doing non-trivial configuration of the thunk's body. For
34463     // example, the Linux kernel will do boot-time hot patching of the thunk
34464     // bodies and cannot easily export aliases of these to loaded modules.
34465     //
34466     // Note that at any point in the future, we may need to change the semantics
34467     // of how we implement retpolines and at that time will likely change the
34468     // name of the called thunk. Essentially, there is no hard guarantee that
34469     // LLVM will generate calls to specific thunks, we merely make a best-effort
34470     // attempt to help out kernels and other systems where duplicating the
34471     // thunks is costly.
34472     switch (Reg) {
34473     case X86::EAX:
34474       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
34475       return "__x86_indirect_thunk_eax";
34476     case X86::ECX:
34477       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
34478       return "__x86_indirect_thunk_ecx";
34479     case X86::EDX:
34480       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
34481       return "__x86_indirect_thunk_edx";
34482     case X86::EDI:
34483       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
34484       return "__x86_indirect_thunk_edi";
34485     case X86::R11:
34486       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
34487       return "__x86_indirect_thunk_r11";
34488     }
34489     llvm_unreachable("unexpected reg for external indirect thunk");
34490   }
34491 
34492   if (Subtarget.useRetpolineIndirectCalls() ||
34493       Subtarget.useRetpolineIndirectBranches()) {
34494     // When targeting an internal COMDAT thunk use an LLVM-specific name.
34495     switch (Reg) {
34496     case X86::EAX:
34497       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
34498       return "__llvm_retpoline_eax";
34499     case X86::ECX:
34500       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
34501       return "__llvm_retpoline_ecx";
34502     case X86::EDX:
34503       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
34504       return "__llvm_retpoline_edx";
34505     case X86::EDI:
34506       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
34507       return "__llvm_retpoline_edi";
34508     case X86::R11:
34509       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
34510       return "__llvm_retpoline_r11";
34511     }
34512     llvm_unreachable("unexpected reg for retpoline");
34513   }
34514 
34515   if (Subtarget.useLVIControlFlowIntegrity()) {
34516     assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
34517     return "__llvm_lvi_thunk_r11";
34518   }
34519   llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature");
34520 }
34521 
34522 MachineBasicBlock *
34523 X86TargetLowering::EmitLoweredIndirectThunk(MachineInstr &MI,
34524                                             MachineBasicBlock *BB) const {
34525   // Copy the virtual register into the R11 physical register and
34526   // call the retpoline thunk.
34527   const DebugLoc &DL = MI.getDebugLoc();
34528   const X86InstrInfo *TII = Subtarget.getInstrInfo();
34529   Register CalleeVReg = MI.getOperand(0).getReg();
34530   unsigned Opc = getOpcodeForIndirectThunk(MI.getOpcode());
34531 
34532   // Find an available scratch register to hold the callee. On 64-bit, we can
34533   // just use R11, but we scan for uses anyway to ensure we don't generate
34534   // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
34535   // already a register use operand to the call to hold the callee. If none
34536   // are available, use EDI instead. EDI is chosen because EBX is the PIC base
34537   // register and ESI is the base pointer to realigned stack frames with VLAs.
34538   SmallVector<unsigned, 3> AvailableRegs;
34539   if (Subtarget.is64Bit())
34540     AvailableRegs.push_back(X86::R11);
34541   else
34542     AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
34543 
34544   // Zero out any registers that are already used.
34545   for (const auto &MO : MI.operands()) {
34546     if (MO.isReg() && MO.isUse())
34547       for (unsigned &Reg : AvailableRegs)
34548         if (Reg == MO.getReg())
34549           Reg = 0;
34550   }
34551 
34552   // Choose the first remaining non-zero available register.
34553   unsigned AvailableReg = 0;
34554   for (unsigned MaybeReg : AvailableRegs) {
34555     if (MaybeReg) {
34556       AvailableReg = MaybeReg;
34557       break;
34558     }
34559   }
34560   if (!AvailableReg)
34561     report_fatal_error("calling convention incompatible with retpoline, no "
34562                        "available registers");
34563 
34564   const char *Symbol = getIndirectThunkSymbol(Subtarget, AvailableReg);
34565 
34566   BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
34567       .addReg(CalleeVReg);
34568   MI.getOperand(0).ChangeToES(Symbol);
34569   MI.setDesc(TII->get(Opc));
34570   MachineInstrBuilder(*BB->getParent(), &MI)
34571       .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
34572   return BB;
34573 }
34574 
34575 /// SetJmp implies future control flow change upon calling the corresponding
34576 /// LongJmp.
34577 /// Instead of using the 'return' instruction, the long jump fixes the stack and
34578 /// performs an indirect branch. To do so it uses the registers that were stored
34579 /// in the jump buffer (when calling SetJmp).
34580 /// In case the shadow stack is enabled we need to fix it as well, because some
34581 /// return addresses will be skipped.
34582 /// The function will save the SSP for future fixing in the function
34583 /// emitLongJmpShadowStackFix.
34584 /// \sa emitLongJmpShadowStackFix
34585 /// \param [in] MI The temporary Machine Instruction for the builtin.
34586 /// \param [in] MBB The Machine Basic Block that will be modified.
34587 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
34588                                                  MachineBasicBlock *MBB) const {
34589   const DebugLoc &DL = MI.getDebugLoc();
34590   MachineFunction *MF = MBB->getParent();
34591   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34592   MachineRegisterInfo &MRI = MF->getRegInfo();
34593   MachineInstrBuilder MIB;
34594 
34595   // Memory Reference.
34596   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
34597                                            MI.memoperands_end());
34598 
34599   // Initialize a register with zero.
34600   MVT PVT = getPointerTy(MF->getDataLayout());
34601   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
34602   Register ZReg = MRI.createVirtualRegister(PtrRC);
34603   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
34604   BuildMI(*MBB, MI, DL, TII->get(XorRROpc))
34605       .addDef(ZReg)
34606       .addReg(ZReg, RegState::Undef)
34607       .addReg(ZReg, RegState::Undef);
34608 
34609   // Read the current SSP Register value to the zeroed register.
34610   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
34611   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
34612   BuildMI(*MBB, MI, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
34613 
34614   // Write the SSP register value to offset 3 in input memory buffer.
34615   unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
34616   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrStoreOpc));
34617   const int64_t SSPOffset = 3 * PVT.getStoreSize();
34618   const unsigned MemOpndSlot = 1;
34619   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
34620     if (i == X86::AddrDisp)
34621       MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
34622     else
34623       MIB.add(MI.getOperand(MemOpndSlot + i));
34624   }
34625   MIB.addReg(SSPCopyReg);
34626   MIB.setMemRefs(MMOs);
34627 }
34628 
34629 MachineBasicBlock *
34630 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
34631                                     MachineBasicBlock *MBB) const {
34632   const DebugLoc &DL = MI.getDebugLoc();
34633   MachineFunction *MF = MBB->getParent();
34634   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34635   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
34636   MachineRegisterInfo &MRI = MF->getRegInfo();
34637 
34638   const BasicBlock *BB = MBB->getBasicBlock();
34639   MachineFunction::iterator I = ++MBB->getIterator();
34640 
34641   // Memory Reference
34642   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
34643                                            MI.memoperands_end());
34644 
34645   unsigned DstReg;
34646   unsigned MemOpndSlot = 0;
34647 
34648   unsigned CurOp = 0;
34649 
34650   DstReg = MI.getOperand(CurOp++).getReg();
34651   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
34652   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
34653   (void)TRI;
34654   Register mainDstReg = MRI.createVirtualRegister(RC);
34655   Register restoreDstReg = MRI.createVirtualRegister(RC);
34656 
34657   MemOpndSlot = CurOp;
34658 
34659   MVT PVT = getPointerTy(MF->getDataLayout());
34660   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
34661          "Invalid Pointer Size!");
34662 
34663   // For v = setjmp(buf), we generate
34664   //
34665   // thisMBB:
34666   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
34667   //  SjLjSetup restoreMBB
34668   //
34669   // mainMBB:
34670   //  v_main = 0
34671   //
34672   // sinkMBB:
34673   //  v = phi(main, restore)
34674   //
34675   // restoreMBB:
34676   //  if base pointer being used, load it from frame
34677   //  v_restore = 1
34678 
34679   MachineBasicBlock *thisMBB = MBB;
34680   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
34681   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
34682   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
34683   MF->insert(I, mainMBB);
34684   MF->insert(I, sinkMBB);
34685   MF->push_back(restoreMBB);
34686   restoreMBB->setHasAddressTaken();
34687 
34688   MachineInstrBuilder MIB;
34689 
34690   // Transfer the remainder of BB and its successor edges to sinkMBB.
34691   sinkMBB->splice(sinkMBB->begin(), MBB,
34692                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
34693   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
34694 
34695   // thisMBB:
34696   unsigned PtrStoreOpc = 0;
34697   unsigned LabelReg = 0;
34698   const int64_t LabelOffset = 1 * PVT.getStoreSize();
34699   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
34700                      !isPositionIndependent();
34701 
34702   // Prepare IP either in reg or imm.
34703   if (!UseImmLabel) {
34704     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
34705     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
34706     LabelReg = MRI.createVirtualRegister(PtrRC);
34707     if (Subtarget.is64Bit()) {
34708       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
34709               .addReg(X86::RIP)
34710               .addImm(0)
34711               .addReg(0)
34712               .addMBB(restoreMBB)
34713               .addReg(0);
34714     } else {
34715       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
34716       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
34717               .addReg(XII->getGlobalBaseReg(MF))
34718               .addImm(0)
34719               .addReg(0)
34720               .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
34721               .addReg(0);
34722     }
34723   } else
34724     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
34725   // Store IP
34726   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
34727   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
34728     if (i == X86::AddrDisp)
34729       MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
34730     else
34731       MIB.add(MI.getOperand(MemOpndSlot + i));
34732   }
34733   if (!UseImmLabel)
34734     MIB.addReg(LabelReg);
34735   else
34736     MIB.addMBB(restoreMBB);
34737   MIB.setMemRefs(MMOs);
34738 
34739   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
34740     emitSetJmpShadowStackFix(MI, thisMBB);
34741   }
34742 
34743   // Setup
34744   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
34745           .addMBB(restoreMBB);
34746 
34747   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
34748   MIB.addRegMask(RegInfo->getNoPreservedMask());
34749   thisMBB->addSuccessor(mainMBB);
34750   thisMBB->addSuccessor(restoreMBB);
34751 
34752   // mainMBB:
34753   //  EAX = 0
34754   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
34755   mainMBB->addSuccessor(sinkMBB);
34756 
34757   // sinkMBB:
34758   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
34759           TII->get(X86::PHI), DstReg)
34760     .addReg(mainDstReg).addMBB(mainMBB)
34761     .addReg(restoreDstReg).addMBB(restoreMBB);
34762 
34763   // restoreMBB:
34764   if (RegInfo->hasBasePointer(*MF)) {
34765     const bool Uses64BitFramePtr =
34766         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
34767     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
34768     X86FI->setRestoreBasePointer(MF);
34769     Register FramePtr = RegInfo->getFrameRegister(*MF);
34770     Register BasePtr = RegInfo->getBaseRegister();
34771     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
34772     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
34773                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
34774       .setMIFlag(MachineInstr::FrameSetup);
34775   }
34776   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
34777   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
34778   restoreMBB->addSuccessor(sinkMBB);
34779 
34780   MI.eraseFromParent();
34781   return sinkMBB;
34782 }
34783 
34784 /// Fix the shadow stack using the previously saved SSP pointer.
34785 /// \sa emitSetJmpShadowStackFix
34786 /// \param [in] MI The temporary Machine Instruction for the builtin.
34787 /// \param [in] MBB The Machine Basic Block that will be modified.
34788 /// \return The sink MBB that will perform the future indirect branch.
34789 MachineBasicBlock *
34790 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
34791                                              MachineBasicBlock *MBB) const {
34792   const DebugLoc &DL = MI.getDebugLoc();
34793   MachineFunction *MF = MBB->getParent();
34794   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34795   MachineRegisterInfo &MRI = MF->getRegInfo();
34796 
34797   // Memory Reference
34798   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
34799                                            MI.memoperands_end());
34800 
34801   MVT PVT = getPointerTy(MF->getDataLayout());
34802   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
34803 
34804   // checkSspMBB:
34805   //         xor vreg1, vreg1
34806   //         rdssp vreg1
34807   //         test vreg1, vreg1
34808   //         je sinkMBB   # Jump if Shadow Stack is not supported
34809   // fallMBB:
34810   //         mov buf+24/12(%rip), vreg2
34811   //         sub vreg1, vreg2
34812   //         jbe sinkMBB  # No need to fix the Shadow Stack
34813   // fixShadowMBB:
34814   //         shr 3/2, vreg2
34815   //         incssp vreg2  # fix the SSP according to the lower 8 bits
34816   //         shr 8, vreg2
34817   //         je sinkMBB
34818   // fixShadowLoopPrepareMBB:
34819   //         shl vreg2
34820   //         mov 128, vreg3
34821   // fixShadowLoopMBB:
34822   //         incssp vreg3
34823   //         dec vreg2
34824   //         jne fixShadowLoopMBB # Iterate until you finish fixing
34825   //                              # the Shadow Stack
34826   // sinkMBB:
34827 
34828   MachineFunction::iterator I = ++MBB->getIterator();
34829   const BasicBlock *BB = MBB->getBasicBlock();
34830 
34831   MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
34832   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
34833   MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
34834   MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
34835   MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
34836   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
34837   MF->insert(I, checkSspMBB);
34838   MF->insert(I, fallMBB);
34839   MF->insert(I, fixShadowMBB);
34840   MF->insert(I, fixShadowLoopPrepareMBB);
34841   MF->insert(I, fixShadowLoopMBB);
34842   MF->insert(I, sinkMBB);
34843 
34844   // Transfer the remainder of BB and its successor edges to sinkMBB.
34845   sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
34846                   MBB->end());
34847   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
34848 
34849   MBB->addSuccessor(checkSspMBB);
34850 
34851   // Initialize a register with zero.
34852   Register ZReg = MRI.createVirtualRegister(&X86::GR32RegClass);
34853   BuildMI(checkSspMBB, DL, TII->get(X86::MOV32r0), ZReg);
34854 
34855   if (PVT == MVT::i64) {
34856     Register TmpZReg = MRI.createVirtualRegister(PtrRC);
34857     BuildMI(checkSspMBB, DL, TII->get(X86::SUBREG_TO_REG), TmpZReg)
34858       .addImm(0)
34859       .addReg(ZReg)
34860       .addImm(X86::sub_32bit);
34861     ZReg = TmpZReg;
34862   }
34863 
34864   // Read the current SSP Register value to the zeroed register.
34865   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
34866   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
34867   BuildMI(checkSspMBB, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
34868 
34869   // Check whether the result of the SSP register is zero and jump directly
34870   // to the sink.
34871   unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
34872   BuildMI(checkSspMBB, DL, TII->get(TestRROpc))
34873       .addReg(SSPCopyReg)
34874       .addReg(SSPCopyReg);
34875   BuildMI(checkSspMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
34876   checkSspMBB->addSuccessor(sinkMBB);
34877   checkSspMBB->addSuccessor(fallMBB);
34878 
34879   // Reload the previously saved SSP register value.
34880   Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
34881   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
34882   const int64_t SPPOffset = 3 * PVT.getStoreSize();
34883   MachineInstrBuilder MIB =
34884       BuildMI(fallMBB, DL, TII->get(PtrLoadOpc), PrevSSPReg);
34885   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
34886     const MachineOperand &MO = MI.getOperand(i);
34887     if (i == X86::AddrDisp)
34888       MIB.addDisp(MO, SPPOffset);
34889     else if (MO.isReg()) // Don't add the whole operand, we don't want to
34890                          // preserve kill flags.
34891       MIB.addReg(MO.getReg());
34892     else
34893       MIB.add(MO);
34894   }
34895   MIB.setMemRefs(MMOs);
34896 
34897   // Subtract the current SSP from the previous SSP.
34898   Register SspSubReg = MRI.createVirtualRegister(PtrRC);
34899   unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
34900   BuildMI(fallMBB, DL, TII->get(SubRROpc), SspSubReg)
34901       .addReg(PrevSSPReg)
34902       .addReg(SSPCopyReg);
34903 
34904   // Jump to sink in case PrevSSPReg <= SSPCopyReg.
34905   BuildMI(fallMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_BE);
34906   fallMBB->addSuccessor(sinkMBB);
34907   fallMBB->addSuccessor(fixShadowMBB);
34908 
34909   // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
34910   unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
34911   unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
34912   Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
34913   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspFirstShrReg)
34914       .addReg(SspSubReg)
34915       .addImm(Offset);
34916 
34917   // Increase SSP when looking only on the lower 8 bits of the delta.
34918   unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
34919   BuildMI(fixShadowMBB, DL, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
34920 
34921   // Reset the lower 8 bits.
34922   Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
34923   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspSecondShrReg)
34924       .addReg(SspFirstShrReg)
34925       .addImm(8);
34926 
34927   // Jump if the result of the shift is zero.
34928   BuildMI(fixShadowMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
34929   fixShadowMBB->addSuccessor(sinkMBB);
34930   fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
34931 
34932   // Do a single shift left.
34933   unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64r1 : X86::SHL32r1;
34934   Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
34935   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(ShlR1Opc), SspAfterShlReg)
34936       .addReg(SspSecondShrReg);
34937 
34938   // Save the value 128 to a register (will be used next with incssp).
34939   Register Value128InReg = MRI.createVirtualRegister(PtrRC);
34940   unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
34941   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(MovRIOpc), Value128InReg)
34942       .addImm(128);
34943   fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
34944 
34945   // Since incssp only looks at the lower 8 bits, we might need to do several
34946   // iterations of incssp until we finish fixing the shadow stack.
34947   Register DecReg = MRI.createVirtualRegister(PtrRC);
34948   Register CounterReg = MRI.createVirtualRegister(PtrRC);
34949   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::PHI), CounterReg)
34950       .addReg(SspAfterShlReg)
34951       .addMBB(fixShadowLoopPrepareMBB)
34952       .addReg(DecReg)
34953       .addMBB(fixShadowLoopMBB);
34954 
34955   // Every iteration we increase the SSP by 128.
34956   BuildMI(fixShadowLoopMBB, DL, TII->get(IncsspOpc)).addReg(Value128InReg);
34957 
34958   // Every iteration we decrement the counter by 1.
34959   unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
34960   BuildMI(fixShadowLoopMBB, DL, TII->get(DecROpc), DecReg).addReg(CounterReg);
34961 
34962   // Jump if the counter is not zero yet.
34963   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::JCC_1)).addMBB(fixShadowLoopMBB).addImm(X86::COND_NE);
34964   fixShadowLoopMBB->addSuccessor(sinkMBB);
34965   fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
34966 
34967   return sinkMBB;
34968 }
34969 
34970 MachineBasicBlock *
34971 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
34972                                      MachineBasicBlock *MBB) const {
34973   const DebugLoc &DL = MI.getDebugLoc();
34974   MachineFunction *MF = MBB->getParent();
34975   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34976   MachineRegisterInfo &MRI = MF->getRegInfo();
34977 
34978   // Memory Reference
34979   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
34980                                            MI.memoperands_end());
34981 
34982   MVT PVT = getPointerTy(MF->getDataLayout());
34983   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
34984          "Invalid Pointer Size!");
34985 
34986   const TargetRegisterClass *RC =
34987     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
34988   Register Tmp = MRI.createVirtualRegister(RC);
34989   // Since FP is only updated here but NOT referenced, it's treated as GPR.
34990   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
34991   Register FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
34992   Register SP = RegInfo->getStackRegister();
34993 
34994   MachineInstrBuilder MIB;
34995 
34996   const int64_t LabelOffset = 1 * PVT.getStoreSize();
34997   const int64_t SPOffset = 2 * PVT.getStoreSize();
34998 
34999   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
35000   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
35001 
35002   MachineBasicBlock *thisMBB = MBB;
35003 
35004   // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
35005   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
35006     thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
35007   }
35008 
35009   // Reload FP
35010   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), FP);
35011   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35012     const MachineOperand &MO = MI.getOperand(i);
35013     if (MO.isReg()) // Don't add the whole operand, we don't want to
35014                     // preserve kill flags.
35015       MIB.addReg(MO.getReg());
35016     else
35017       MIB.add(MO);
35018   }
35019   MIB.setMemRefs(MMOs);
35020 
35021   // Reload IP
35022   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
35023   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35024     const MachineOperand &MO = MI.getOperand(i);
35025     if (i == X86::AddrDisp)
35026       MIB.addDisp(MO, LabelOffset);
35027     else if (MO.isReg()) // Don't add the whole operand, we don't want to
35028                          // preserve kill flags.
35029       MIB.addReg(MO.getReg());
35030     else
35031       MIB.add(MO);
35032   }
35033   MIB.setMemRefs(MMOs);
35034 
35035   // Reload SP
35036   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), SP);
35037   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35038     if (i == X86::AddrDisp)
35039       MIB.addDisp(MI.getOperand(i), SPOffset);
35040     else
35041       MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
35042                                  // the last instruction of the expansion.
35043   }
35044   MIB.setMemRefs(MMOs);
35045 
35046   // Jump
35047   BuildMI(*thisMBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
35048 
35049   MI.eraseFromParent();
35050   return thisMBB;
35051 }
35052 
35053 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
35054                                                MachineBasicBlock *MBB,
35055                                                MachineBasicBlock *DispatchBB,
35056                                                int FI) const {
35057   const DebugLoc &DL = MI.getDebugLoc();
35058   MachineFunction *MF = MBB->getParent();
35059   MachineRegisterInfo *MRI = &MF->getRegInfo();
35060   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35061 
35062   MVT PVT = getPointerTy(MF->getDataLayout());
35063   assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
35064 
35065   unsigned Op = 0;
35066   unsigned VR = 0;
35067 
35068   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
35069                      !isPositionIndependent();
35070 
35071   if (UseImmLabel) {
35072     Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
35073   } else {
35074     const TargetRegisterClass *TRC =
35075         (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
35076     VR = MRI->createVirtualRegister(TRC);
35077     Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
35078 
35079     if (Subtarget.is64Bit())
35080       BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
35081           .addReg(X86::RIP)
35082           .addImm(1)
35083           .addReg(0)
35084           .addMBB(DispatchBB)
35085           .addReg(0);
35086     else
35087       BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
35088           .addReg(0) /* TII->getGlobalBaseReg(MF) */
35089           .addImm(1)
35090           .addReg(0)
35091           .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
35092           .addReg(0);
35093   }
35094 
35095   MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
35096   addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
35097   if (UseImmLabel)
35098     MIB.addMBB(DispatchBB);
35099   else
35100     MIB.addReg(VR);
35101 }
35102 
35103 MachineBasicBlock *
35104 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
35105                                          MachineBasicBlock *BB) const {
35106   const DebugLoc &DL = MI.getDebugLoc();
35107   MachineFunction *MF = BB->getParent();
35108   MachineRegisterInfo *MRI = &MF->getRegInfo();
35109   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35110   int FI = MF->getFrameInfo().getFunctionContextIndex();
35111 
35112   // Get a mapping of the call site numbers to all of the landing pads they're
35113   // associated with.
35114   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
35115   unsigned MaxCSNum = 0;
35116   for (auto &MBB : *MF) {
35117     if (!MBB.isEHPad())
35118       continue;
35119 
35120     MCSymbol *Sym = nullptr;
35121     for (const auto &MI : MBB) {
35122       if (MI.isDebugInstr())
35123         continue;
35124 
35125       assert(MI.isEHLabel() && "expected EH_LABEL");
35126       Sym = MI.getOperand(0).getMCSymbol();
35127       break;
35128     }
35129 
35130     if (!MF->hasCallSiteLandingPad(Sym))
35131       continue;
35132 
35133     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
35134       CallSiteNumToLPad[CSI].push_back(&MBB);
35135       MaxCSNum = std::max(MaxCSNum, CSI);
35136     }
35137   }
35138 
35139   // Get an ordered list of the machine basic blocks for the jump table.
35140   std::vector<MachineBasicBlock *> LPadList;
35141   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
35142   LPadList.reserve(CallSiteNumToLPad.size());
35143 
35144   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
35145     for (auto &LP : CallSiteNumToLPad[CSI]) {
35146       LPadList.push_back(LP);
35147       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
35148     }
35149   }
35150 
35151   assert(!LPadList.empty() &&
35152          "No landing pad destinations for the dispatch jump table!");
35153 
35154   // Create the MBBs for the dispatch code.
35155 
35156   // Shove the dispatch's address into the return slot in the function context.
35157   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
35158   DispatchBB->setIsEHPad(true);
35159 
35160   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
35161   BuildMI(TrapBB, DL, TII->get(X86::TRAP));
35162   DispatchBB->addSuccessor(TrapBB);
35163 
35164   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
35165   DispatchBB->addSuccessor(DispContBB);
35166 
35167   // Insert MBBs.
35168   MF->push_back(DispatchBB);
35169   MF->push_back(DispContBB);
35170   MF->push_back(TrapBB);
35171 
35172   // Insert code into the entry block that creates and registers the function
35173   // context.
35174   SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
35175 
35176   // Create the jump table and associated information
35177   unsigned JTE = getJumpTableEncoding();
35178   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
35179   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
35180 
35181   const X86RegisterInfo &RI = TII->getRegisterInfo();
35182   // Add a register mask with no preserved registers.  This results in all
35183   // registers being marked as clobbered.
35184   if (RI.hasBasePointer(*MF)) {
35185     const bool FPIs64Bit =
35186         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
35187     X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
35188     MFI->setRestoreBasePointer(MF);
35189 
35190     Register FP = RI.getFrameRegister(*MF);
35191     Register BP = RI.getBaseRegister();
35192     unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
35193     addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
35194                  MFI->getRestoreBasePointerOffset())
35195         .addRegMask(RI.getNoPreservedMask());
35196   } else {
35197     BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
35198         .addRegMask(RI.getNoPreservedMask());
35199   }
35200 
35201   // IReg is used as an index in a memory operand and therefore can't be SP
35202   Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
35203   addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
35204                     Subtarget.is64Bit() ? 8 : 4);
35205   BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
35206       .addReg(IReg)
35207       .addImm(LPadList.size());
35208   BuildMI(DispatchBB, DL, TII->get(X86::JCC_1)).addMBB(TrapBB).addImm(X86::COND_AE);
35209 
35210   if (Subtarget.is64Bit()) {
35211     Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
35212     Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
35213 
35214     // leaq .LJTI0_0(%rip), BReg
35215     BuildMI(DispContBB, DL, TII->get(X86::LEA64r), BReg)
35216         .addReg(X86::RIP)
35217         .addImm(1)
35218         .addReg(0)
35219         .addJumpTableIndex(MJTI)
35220         .addReg(0);
35221     // movzx IReg64, IReg
35222     BuildMI(DispContBB, DL, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
35223         .addImm(0)
35224         .addReg(IReg)
35225         .addImm(X86::sub_32bit);
35226 
35227     switch (JTE) {
35228     case MachineJumpTableInfo::EK_BlockAddress:
35229       // jmpq *(BReg,IReg64,8)
35230       BuildMI(DispContBB, DL, TII->get(X86::JMP64m))
35231           .addReg(BReg)
35232           .addImm(8)
35233           .addReg(IReg64)
35234           .addImm(0)
35235           .addReg(0);
35236       break;
35237     case MachineJumpTableInfo::EK_LabelDifference32: {
35238       Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
35239       Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
35240       Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
35241 
35242       // movl (BReg,IReg64,4), OReg
35243       BuildMI(DispContBB, DL, TII->get(X86::MOV32rm), OReg)
35244           .addReg(BReg)
35245           .addImm(4)
35246           .addReg(IReg64)
35247           .addImm(0)
35248           .addReg(0);
35249       // movsx OReg64, OReg
35250       BuildMI(DispContBB, DL, TII->get(X86::MOVSX64rr32), OReg64).addReg(OReg);
35251       // addq BReg, OReg64, TReg
35252       BuildMI(DispContBB, DL, TII->get(X86::ADD64rr), TReg)
35253           .addReg(OReg64)
35254           .addReg(BReg);
35255       // jmpq *TReg
35256       BuildMI(DispContBB, DL, TII->get(X86::JMP64r)).addReg(TReg);
35257       break;
35258     }
35259     default:
35260       llvm_unreachable("Unexpected jump table encoding");
35261     }
35262   } else {
35263     // jmpl *.LJTI0_0(,IReg,4)
35264     BuildMI(DispContBB, DL, TII->get(X86::JMP32m))
35265         .addReg(0)
35266         .addImm(4)
35267         .addReg(IReg)
35268         .addJumpTableIndex(MJTI)
35269         .addReg(0);
35270   }
35271 
35272   // Add the jump table entries as successors to the MBB.
35273   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
35274   for (auto &LP : LPadList)
35275     if (SeenMBBs.insert(LP).second)
35276       DispContBB->addSuccessor(LP);
35277 
35278   // N.B. the order the invoke BBs are processed in doesn't matter here.
35279   SmallVector<MachineBasicBlock *, 64> MBBLPads;
35280   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
35281   for (MachineBasicBlock *MBB : InvokeBBs) {
35282     // Remove the landing pad successor from the invoke block and replace it
35283     // with the new dispatch block.
35284     // Keep a copy of Successors since it's modified inside the loop.
35285     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
35286                                                    MBB->succ_rend());
35287     // FIXME: Avoid quadratic complexity.
35288     for (auto MBBS : Successors) {
35289       if (MBBS->isEHPad()) {
35290         MBB->removeSuccessor(MBBS);
35291         MBBLPads.push_back(MBBS);
35292       }
35293     }
35294 
35295     MBB->addSuccessor(DispatchBB);
35296 
35297     // Find the invoke call and mark all of the callee-saved registers as
35298     // 'implicit defined' so that they're spilled.  This prevents code from
35299     // moving instructions to before the EH block, where they will never be
35300     // executed.
35301     for (auto &II : reverse(*MBB)) {
35302       if (!II.isCall())
35303         continue;
35304 
35305       DenseMap<unsigned, bool> DefRegs;
35306       for (auto &MOp : II.operands())
35307         if (MOp.isReg())
35308           DefRegs[MOp.getReg()] = true;
35309 
35310       MachineInstrBuilder MIB(*MF, &II);
35311       for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
35312         unsigned Reg = SavedRegs[RegIdx];
35313         if (!DefRegs[Reg])
35314           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
35315       }
35316 
35317       break;
35318     }
35319   }
35320 
35321   // Mark all former landing pads as non-landing pads.  The dispatch is the only
35322   // landing pad now.
35323   for (auto &LP : MBBLPads)
35324     LP->setIsEHPad(false);
35325 
35326   // The instruction is gone now.
35327   MI.eraseFromParent();
35328   return BB;
35329 }
35330 
35331 MachineBasicBlock *
35332 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
35333                                                MachineBasicBlock *BB) const {
35334   MachineFunction *MF = BB->getParent();
35335   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35336   const DebugLoc &DL = MI.getDebugLoc();
35337 
35338   auto TMMImmToTMMReg = [](unsigned Imm) {
35339     assert (Imm < 8 && "Illegal tmm index");
35340     return X86::TMM0 + Imm;
35341   };
35342   switch (MI.getOpcode()) {
35343   default: llvm_unreachable("Unexpected instr type to insert");
35344   case X86::TLS_addr32:
35345   case X86::TLS_addr64:
35346   case X86::TLS_addrX32:
35347   case X86::TLS_base_addr32:
35348   case X86::TLS_base_addr64:
35349   case X86::TLS_base_addrX32:
35350     return EmitLoweredTLSAddr(MI, BB);
35351   case X86::INDIRECT_THUNK_CALL32:
35352   case X86::INDIRECT_THUNK_CALL64:
35353   case X86::INDIRECT_THUNK_TCRETURN32:
35354   case X86::INDIRECT_THUNK_TCRETURN64:
35355     return EmitLoweredIndirectThunk(MI, BB);
35356   case X86::CATCHRET:
35357     return EmitLoweredCatchRet(MI, BB);
35358   case X86::SEG_ALLOCA_32:
35359   case X86::SEG_ALLOCA_64:
35360     return EmitLoweredSegAlloca(MI, BB);
35361   case X86::PROBED_ALLOCA_32:
35362   case X86::PROBED_ALLOCA_64:
35363     return EmitLoweredProbedAlloca(MI, BB);
35364   case X86::TLSCall_32:
35365   case X86::TLSCall_64:
35366     return EmitLoweredTLSCall(MI, BB);
35367   case X86::CMOV_FR32:
35368   case X86::CMOV_FR32X:
35369   case X86::CMOV_FR64:
35370   case X86::CMOV_FR64X:
35371   case X86::CMOV_GR8:
35372   case X86::CMOV_GR16:
35373   case X86::CMOV_GR32:
35374   case X86::CMOV_RFP32:
35375   case X86::CMOV_RFP64:
35376   case X86::CMOV_RFP80:
35377   case X86::CMOV_VR64:
35378   case X86::CMOV_VR128:
35379   case X86::CMOV_VR128X:
35380   case X86::CMOV_VR256:
35381   case X86::CMOV_VR256X:
35382   case X86::CMOV_VR512:
35383   case X86::CMOV_VK1:
35384   case X86::CMOV_VK2:
35385   case X86::CMOV_VK4:
35386   case X86::CMOV_VK8:
35387   case X86::CMOV_VK16:
35388   case X86::CMOV_VK32:
35389   case X86::CMOV_VK64:
35390     return EmitLoweredSelect(MI, BB);
35391 
35392   case X86::RDFLAGS32:
35393   case X86::RDFLAGS64: {
35394     unsigned PushF =
35395         MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
35396     unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
35397     MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
35398     // Permit reads of the EFLAGS and DF registers without them being defined.
35399     // This intrinsic exists to read external processor state in flags, such as
35400     // the trap flag, interrupt flag, and direction flag, none of which are
35401     // modeled by the backend.
35402     assert(Push->getOperand(2).getReg() == X86::EFLAGS &&
35403            "Unexpected register in operand!");
35404     Push->getOperand(2).setIsUndef();
35405     assert(Push->getOperand(3).getReg() == X86::DF &&
35406            "Unexpected register in operand!");
35407     Push->getOperand(3).setIsUndef();
35408     BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
35409 
35410     MI.eraseFromParent(); // The pseudo is gone now.
35411     return BB;
35412   }
35413 
35414   case X86::WRFLAGS32:
35415   case X86::WRFLAGS64: {
35416     unsigned Push =
35417         MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
35418     unsigned PopF =
35419         MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
35420     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
35421     BuildMI(*BB, MI, DL, TII->get(PopF));
35422 
35423     MI.eraseFromParent(); // The pseudo is gone now.
35424     return BB;
35425   }
35426 
35427   case X86::FP32_TO_INT16_IN_MEM:
35428   case X86::FP32_TO_INT32_IN_MEM:
35429   case X86::FP32_TO_INT64_IN_MEM:
35430   case X86::FP64_TO_INT16_IN_MEM:
35431   case X86::FP64_TO_INT32_IN_MEM:
35432   case X86::FP64_TO_INT64_IN_MEM:
35433   case X86::FP80_TO_INT16_IN_MEM:
35434   case X86::FP80_TO_INT32_IN_MEM:
35435   case X86::FP80_TO_INT64_IN_MEM: {
35436     // Change the floating point control register to use "round towards zero"
35437     // mode when truncating to an integer value.
35438     int OrigCWFrameIdx =
35439         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
35440     addFrameReference(BuildMI(*BB, MI, DL,
35441                               TII->get(X86::FNSTCW16m)), OrigCWFrameIdx);
35442 
35443     // Load the old value of the control word...
35444     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
35445     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOVZX32rm16), OldCW),
35446                       OrigCWFrameIdx);
35447 
35448     // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
35449     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
35450     BuildMI(*BB, MI, DL, TII->get(X86::OR32ri), NewCW)
35451       .addReg(OldCW, RegState::Kill).addImm(0xC00);
35452 
35453     // Extract to 16 bits.
35454     Register NewCW16 =
35455         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
35456     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), NewCW16)
35457       .addReg(NewCW, RegState::Kill, X86::sub_16bit);
35458 
35459     // Prepare memory for FLDCW.
35460     int NewCWFrameIdx =
35461         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
35462     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)),
35463                       NewCWFrameIdx)
35464       .addReg(NewCW16, RegState::Kill);
35465 
35466     // Reload the modified control word now...
35467     addFrameReference(BuildMI(*BB, MI, DL,
35468                               TII->get(X86::FLDCW16m)), NewCWFrameIdx);
35469 
35470     // Get the X86 opcode to use.
35471     unsigned Opc;
35472     switch (MI.getOpcode()) {
35473     default: llvm_unreachable("illegal opcode!");
35474     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
35475     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
35476     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
35477     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
35478     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
35479     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
35480     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
35481     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
35482     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
35483     }
35484 
35485     X86AddressMode AM = getAddressFromInstr(&MI, 0);
35486     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
35487         .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
35488 
35489     // Reload the original control word now.
35490     addFrameReference(BuildMI(*BB, MI, DL,
35491                               TII->get(X86::FLDCW16m)), OrigCWFrameIdx);
35492 
35493     MI.eraseFromParent(); // The pseudo instruction is gone now.
35494     return BB;
35495   }
35496 
35497   // xbegin
35498   case X86::XBEGIN:
35499     return emitXBegin(MI, BB, Subtarget.getInstrInfo());
35500 
35501   case X86::VAARG_64:
35502   case X86::VAARG_X32:
35503     return EmitVAARGWithCustomInserter(MI, BB);
35504 
35505   case X86::EH_SjLj_SetJmp32:
35506   case X86::EH_SjLj_SetJmp64:
35507     return emitEHSjLjSetJmp(MI, BB);
35508 
35509   case X86::EH_SjLj_LongJmp32:
35510   case X86::EH_SjLj_LongJmp64:
35511     return emitEHSjLjLongJmp(MI, BB);
35512 
35513   case X86::Int_eh_sjlj_setup_dispatch:
35514     return EmitSjLjDispatchBlock(MI, BB);
35515 
35516   case TargetOpcode::STATEPOINT:
35517     // As an implementation detail, STATEPOINT shares the STACKMAP format at
35518     // this point in the process.  We diverge later.
35519     return emitPatchPoint(MI, BB);
35520 
35521   case TargetOpcode::STACKMAP:
35522   case TargetOpcode::PATCHPOINT:
35523     return emitPatchPoint(MI, BB);
35524 
35525   case TargetOpcode::PATCHABLE_EVENT_CALL:
35526   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
35527     return BB;
35528 
35529   case X86::LCMPXCHG8B: {
35530     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
35531     // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
35532     // requires a memory operand. If it happens that current architecture is
35533     // i686 and for current function we need a base pointer
35534     // - which is ESI for i686 - register allocator would not be able to
35535     // allocate registers for an address in form of X(%reg, %reg, Y)
35536     // - there never would be enough unreserved registers during regalloc
35537     // (without the need for base ptr the only option would be X(%edi, %esi, Y).
35538     // We are giving a hand to register allocator by precomputing the address in
35539     // a new vreg using LEA.
35540 
35541     // If it is not i686 or there is no base pointer - nothing to do here.
35542     if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
35543       return BB;
35544 
35545     // Even though this code does not necessarily needs the base pointer to
35546     // be ESI, we check for that. The reason: if this assert fails, there are
35547     // some changes happened in the compiler base pointer handling, which most
35548     // probably have to be addressed somehow here.
35549     assert(TRI->getBaseRegister() == X86::ESI &&
35550            "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
35551            "base pointer in mind");
35552 
35553     MachineRegisterInfo &MRI = MF->getRegInfo();
35554     MVT SPTy = getPointerTy(MF->getDataLayout());
35555     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
35556     Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
35557 
35558     X86AddressMode AM = getAddressFromInstr(&MI, 0);
35559     // Regalloc does not need any help when the memory operand of CMPXCHG8B
35560     // does not use index register.
35561     if (AM.IndexReg == X86::NoRegister)
35562       return BB;
35563 
35564     // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
35565     // four operand definitions that are E[ABCD] registers. We skip them and
35566     // then insert the LEA.
35567     MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
35568     while (RMBBI != BB->rend() && (RMBBI->definesRegister(X86::EAX) ||
35569                                    RMBBI->definesRegister(X86::EBX) ||
35570                                    RMBBI->definesRegister(X86::ECX) ||
35571                                    RMBBI->definesRegister(X86::EDX))) {
35572       ++RMBBI;
35573     }
35574     MachineBasicBlock::iterator MBBI(RMBBI);
35575     addFullAddress(
35576         BuildMI(*BB, *MBBI, DL, TII->get(X86::LEA32r), computedAddrVReg), AM);
35577 
35578     setDirectAddressInInstr(&MI, 0, computedAddrVReg);
35579 
35580     return BB;
35581   }
35582   case X86::LCMPXCHG16B_NO_RBX: {
35583     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
35584     Register BasePtr = TRI->getBaseRegister();
35585     if (TRI->hasBasePointer(*MF) &&
35586         (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
35587       if (!BB->isLiveIn(BasePtr))
35588         BB->addLiveIn(BasePtr);
35589       // Save RBX into a virtual register.
35590       Register SaveRBX =
35591           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
35592       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), SaveRBX)
35593           .addReg(X86::RBX);
35594       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
35595       MachineInstrBuilder MIB =
35596           BuildMI(*BB, MI, DL, TII->get(X86::LCMPXCHG16B_SAVE_RBX), Dst);
35597       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
35598         MIB.add(MI.getOperand(Idx));
35599       MIB.add(MI.getOperand(X86::AddrNumOperands));
35600       MIB.addReg(SaveRBX);
35601     } else {
35602       // Simple case, just copy the virtual register to RBX.
35603       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::RBX)
35604           .add(MI.getOperand(X86::AddrNumOperands));
35605       MachineInstrBuilder MIB =
35606           BuildMI(*BB, MI, DL, TII->get(X86::LCMPXCHG16B));
35607       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
35608         MIB.add(MI.getOperand(Idx));
35609     }
35610     MI.eraseFromParent();
35611     return BB;
35612   }
35613   case X86::MWAITX: {
35614     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
35615     Register BasePtr = TRI->getBaseRegister();
35616     bool IsRBX = (BasePtr == X86::RBX || BasePtr == X86::EBX);
35617     // If no need to save the base pointer, we generate MWAITXrrr,
35618     // else we generate pseudo MWAITX_SAVE_RBX.
35619     if (!IsRBX || !TRI->hasBasePointer(*MF)) {
35620       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::ECX)
35621           .addReg(MI.getOperand(0).getReg());
35622       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EAX)
35623           .addReg(MI.getOperand(1).getReg());
35624       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EBX)
35625           .addReg(MI.getOperand(2).getReg());
35626       BuildMI(*BB, MI, DL, TII->get(X86::MWAITXrrr));
35627       MI.eraseFromParent();
35628     } else {
35629       if (!BB->isLiveIn(BasePtr)) {
35630         BB->addLiveIn(BasePtr);
35631       }
35632       // Parameters can be copied into ECX and EAX but not EBX yet.
35633       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::ECX)
35634           .addReg(MI.getOperand(0).getReg());
35635       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EAX)
35636           .addReg(MI.getOperand(1).getReg());
35637       assert(Subtarget.is64Bit() && "Expected 64-bit mode!");
35638       // Save RBX into a virtual register.
35639       Register SaveRBX =
35640           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
35641       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), SaveRBX)
35642           .addReg(X86::RBX);
35643       // Generate mwaitx pseudo.
35644       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
35645       BuildMI(*BB, MI, DL, TII->get(X86::MWAITX_SAVE_RBX))
35646           .addDef(Dst) // Destination tied in with SaveRBX.
35647           .addReg(MI.getOperand(2).getReg()) // input value of EBX.
35648           .addUse(SaveRBX);                  // Save of base pointer.
35649       MI.eraseFromParent();
35650     }
35651     return BB;
35652   }
35653   case TargetOpcode::PREALLOCATED_SETUP: {
35654     assert(Subtarget.is32Bit() && "preallocated only used in 32-bit");
35655     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
35656     MFI->setHasPreallocatedCall(true);
35657     int64_t PreallocatedId = MI.getOperand(0).getImm();
35658     size_t StackAdjustment = MFI->getPreallocatedStackSize(PreallocatedId);
35659     assert(StackAdjustment != 0 && "0 stack adjustment");
35660     LLVM_DEBUG(dbgs() << "PREALLOCATED_SETUP stack adjustment "
35661                       << StackAdjustment << "\n");
35662     BuildMI(*BB, MI, DL, TII->get(X86::SUB32ri), X86::ESP)
35663         .addReg(X86::ESP)
35664         .addImm(StackAdjustment);
35665     MI.eraseFromParent();
35666     return BB;
35667   }
35668   case TargetOpcode::PREALLOCATED_ARG: {
35669     assert(Subtarget.is32Bit() && "preallocated calls only used in 32-bit");
35670     int64_t PreallocatedId = MI.getOperand(1).getImm();
35671     int64_t ArgIdx = MI.getOperand(2).getImm();
35672     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
35673     size_t ArgOffset = MFI->getPreallocatedArgOffsets(PreallocatedId)[ArgIdx];
35674     LLVM_DEBUG(dbgs() << "PREALLOCATED_ARG arg index " << ArgIdx
35675                       << ", arg offset " << ArgOffset << "\n");
35676     // stack pointer + offset
35677     addRegOffset(
35678         BuildMI(*BB, MI, DL, TII->get(X86::LEA32r), MI.getOperand(0).getReg()),
35679         X86::ESP, false, ArgOffset);
35680     MI.eraseFromParent();
35681     return BB;
35682   }
35683   case X86::PTDPBSSD:
35684   case X86::PTDPBSUD:
35685   case X86::PTDPBUSD:
35686   case X86::PTDPBUUD:
35687   case X86::PTDPBF16PS: {
35688     unsigned Opc;
35689     switch (MI.getOpcode()) {
35690     default: llvm_unreachable("illegal opcode!");
35691     case X86::PTDPBSSD: Opc = X86::TDPBSSD; break;
35692     case X86::PTDPBSUD: Opc = X86::TDPBSUD; break;
35693     case X86::PTDPBUSD: Opc = X86::TDPBUSD; break;
35694     case X86::PTDPBUUD: Opc = X86::TDPBUUD; break;
35695     case X86::PTDPBF16PS: Opc = X86::TDPBF16PS; break;
35696     }
35697 
35698     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
35699     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
35700     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
35701     MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
35702     MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
35703 
35704     MI.eraseFromParent(); // The pseudo is gone now.
35705     return BB;
35706   }
35707   case X86::PTILEZERO: {
35708     unsigned Imm = MI.getOperand(0).getImm();
35709     BuildMI(*BB, MI, DL, TII->get(X86::TILEZERO), TMMImmToTMMReg(Imm));
35710     MI.eraseFromParent(); // The pseudo is gone now.
35711     return BB;
35712   }
35713   case X86::PTILELOADD:
35714   case X86::PTILELOADDT1:
35715   case X86::PTILESTORED: {
35716     unsigned Opc;
35717     switch (MI.getOpcode()) {
35718     default: llvm_unreachable("illegal opcode!");
35719     case X86::PTILELOADD:   Opc = X86::TILELOADD;   break;
35720     case X86::PTILELOADDT1: Opc = X86::TILELOADDT1; break;
35721     case X86::PTILESTORED:  Opc = X86::TILESTORED;  break;
35722     }
35723 
35724     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
35725     unsigned CurOp = 0;
35726     if (Opc != X86::TILESTORED)
35727       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
35728                  RegState::Define);
35729 
35730     MIB.add(MI.getOperand(CurOp++)); // base
35731     MIB.add(MI.getOperand(CurOp++)); // scale
35732     MIB.add(MI.getOperand(CurOp++)); // index -- stride
35733     MIB.add(MI.getOperand(CurOp++)); // displacement
35734     MIB.add(MI.getOperand(CurOp++)); // segment
35735 
35736     if (Opc == X86::TILESTORED)
35737       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
35738                  RegState::Undef);
35739 
35740     MI.eraseFromParent(); // The pseudo is gone now.
35741     return BB;
35742   }
35743   }
35744 }
35745 
35746 //===----------------------------------------------------------------------===//
35747 //                           X86 Optimization Hooks
35748 //===----------------------------------------------------------------------===//
35749 
35750 bool
35751 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
35752                                                 const APInt &DemandedBits,
35753                                                 const APInt &DemandedElts,
35754                                                 TargetLoweringOpt &TLO) const {
35755   EVT VT = Op.getValueType();
35756   unsigned Opcode = Op.getOpcode();
35757   unsigned EltSize = VT.getScalarSizeInBits();
35758 
35759   if (VT.isVector()) {
35760     // If the constant is only all signbits in the active bits, then we should
35761     // extend it to the entire constant to allow it act as a boolean constant
35762     // vector.
35763     auto NeedsSignExtension = [&](SDValue V, unsigned ActiveBits) {
35764       if (!ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
35765         return false;
35766       for (unsigned i = 0, e = V.getNumOperands(); i != e; ++i) {
35767         if (!DemandedElts[i] || V.getOperand(i).isUndef())
35768           continue;
35769         const APInt &Val = V.getConstantOperandAPInt(i);
35770         if (Val.getBitWidth() > Val.getNumSignBits() &&
35771             Val.trunc(ActiveBits).getNumSignBits() == ActiveBits)
35772           return true;
35773       }
35774       return false;
35775     };
35776     // For vectors - if we have a constant, then try to sign extend.
35777     // TODO: Handle AND/ANDN cases.
35778     unsigned ActiveBits = DemandedBits.getActiveBits();
35779     if (EltSize > ActiveBits && EltSize > 1 && isTypeLegal(VT) &&
35780         (Opcode == ISD::OR || Opcode == ISD::XOR) &&
35781         NeedsSignExtension(Op.getOperand(1), ActiveBits)) {
35782       EVT ExtSVT = EVT::getIntegerVT(*TLO.DAG.getContext(), ActiveBits);
35783       EVT ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtSVT,
35784                                     VT.getVectorNumElements());
35785       SDValue NewC =
35786           TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(Op), VT,
35787                           Op.getOperand(1), TLO.DAG.getValueType(ExtVT));
35788       SDValue NewOp =
35789           TLO.DAG.getNode(Opcode, SDLoc(Op), VT, Op.getOperand(0), NewC);
35790       return TLO.CombineTo(Op, NewOp);
35791     }
35792     return false;
35793   }
35794 
35795   // Only optimize Ands to prevent shrinking a constant that could be
35796   // matched by movzx.
35797   if (Opcode != ISD::AND)
35798     return false;
35799 
35800   // Make sure the RHS really is a constant.
35801   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
35802   if (!C)
35803     return false;
35804 
35805   const APInt &Mask = C->getAPIntValue();
35806 
35807   // Clear all non-demanded bits initially.
35808   APInt ShrunkMask = Mask & DemandedBits;
35809 
35810   // Find the width of the shrunk mask.
35811   unsigned Width = ShrunkMask.getActiveBits();
35812 
35813   // If the mask is all 0s there's nothing to do here.
35814   if (Width == 0)
35815     return false;
35816 
35817   // Find the next power of 2 width, rounding up to a byte.
35818   Width = PowerOf2Ceil(std::max(Width, 8U));
35819   // Truncate the width to size to handle illegal types.
35820   Width = std::min(Width, EltSize);
35821 
35822   // Calculate a possible zero extend mask for this constant.
35823   APInt ZeroExtendMask = APInt::getLowBitsSet(EltSize, Width);
35824 
35825   // If we aren't changing the mask, just return true to keep it and prevent
35826   // the caller from optimizing.
35827   if (ZeroExtendMask == Mask)
35828     return true;
35829 
35830   // Make sure the new mask can be represented by a combination of mask bits
35831   // and non-demanded bits.
35832   if (!ZeroExtendMask.isSubsetOf(Mask | ~DemandedBits))
35833     return false;
35834 
35835   // Replace the constant with the zero extend mask.
35836   SDLoc DL(Op);
35837   SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
35838   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
35839   return TLO.CombineTo(Op, NewOp);
35840 }
35841 
35842 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
35843                                                       KnownBits &Known,
35844                                                       const APInt &DemandedElts,
35845                                                       const SelectionDAG &DAG,
35846                                                       unsigned Depth) const {
35847   unsigned BitWidth = Known.getBitWidth();
35848   unsigned NumElts = DemandedElts.getBitWidth();
35849   unsigned Opc = Op.getOpcode();
35850   EVT VT = Op.getValueType();
35851   assert((Opc >= ISD::BUILTIN_OP_END ||
35852           Opc == ISD::INTRINSIC_WO_CHAIN ||
35853           Opc == ISD::INTRINSIC_W_CHAIN ||
35854           Opc == ISD::INTRINSIC_VOID) &&
35855          "Should use MaskedValueIsZero if you don't know whether Op"
35856          " is a target node!");
35857 
35858   Known.resetAll();
35859   switch (Opc) {
35860   default: break;
35861   case X86ISD::SETCC:
35862     Known.Zero.setBitsFrom(1);
35863     break;
35864   case X86ISD::MOVMSK: {
35865     unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
35866     Known.Zero.setBitsFrom(NumLoBits);
35867     break;
35868   }
35869   case X86ISD::PEXTRB:
35870   case X86ISD::PEXTRW: {
35871     SDValue Src = Op.getOperand(0);
35872     EVT SrcVT = Src.getValueType();
35873     APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
35874                                             Op.getConstantOperandVal(1));
35875     Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
35876     Known = Known.anyextOrTrunc(BitWidth);
35877     Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
35878     break;
35879   }
35880   case X86ISD::VSRAI:
35881   case X86ISD::VSHLI:
35882   case X86ISD::VSRLI: {
35883     unsigned ShAmt = Op.getConstantOperandVal(1);
35884     if (ShAmt >= VT.getScalarSizeInBits()) {
35885       Known.setAllZero();
35886       break;
35887     }
35888 
35889     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
35890     if (Opc == X86ISD::VSHLI) {
35891       Known.Zero <<= ShAmt;
35892       Known.One <<= ShAmt;
35893       // Low bits are known zero.
35894       Known.Zero.setLowBits(ShAmt);
35895     } else if (Opc == X86ISD::VSRLI) {
35896       Known.Zero.lshrInPlace(ShAmt);
35897       Known.One.lshrInPlace(ShAmt);
35898       // High bits are known zero.
35899       Known.Zero.setHighBits(ShAmt);
35900     } else {
35901       Known.Zero.ashrInPlace(ShAmt);
35902       Known.One.ashrInPlace(ShAmt);
35903     }
35904     break;
35905   }
35906   case X86ISD::PACKUS: {
35907     // PACKUS is just a truncation if the upper half is zero.
35908     APInt DemandedLHS, DemandedRHS;
35909     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
35910 
35911     Known.One = APInt::getAllOnes(BitWidth * 2);
35912     Known.Zero = APInt::getAllOnes(BitWidth * 2);
35913 
35914     KnownBits Known2;
35915     if (!!DemandedLHS) {
35916       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
35917       Known = KnownBits::commonBits(Known, Known2);
35918     }
35919     if (!!DemandedRHS) {
35920       Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
35921       Known = KnownBits::commonBits(Known, Known2);
35922     }
35923 
35924     if (Known.countMinLeadingZeros() < BitWidth)
35925       Known.resetAll();
35926     Known = Known.trunc(BitWidth);
35927     break;
35928   }
35929   case X86ISD::VBROADCAST: {
35930     SDValue Src = Op.getOperand(0);
35931     if (!Src.getSimpleValueType().isVector()) {
35932       Known = DAG.computeKnownBits(Src, Depth + 1);
35933       return;
35934     }
35935     break;
35936   }
35937   case X86ISD::ANDNP: {
35938     KnownBits Known2;
35939     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
35940     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
35941 
35942     // ANDNP = (~X & Y);
35943     Known.One &= Known2.Zero;
35944     Known.Zero |= Known2.One;
35945     break;
35946   }
35947   case X86ISD::FOR: {
35948     KnownBits Known2;
35949     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
35950     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
35951 
35952     Known |= Known2;
35953     break;
35954   }
35955   case X86ISD::PSADBW: {
35956     assert(VT.getScalarType() == MVT::i64 &&
35957            Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
35958            "Unexpected PSADBW types");
35959 
35960     // PSADBW - fills low 16 bits and zeros upper 48 bits of each i64 result.
35961     Known.Zero.setBitsFrom(16);
35962     break;
35963   }
35964   case X86ISD::PMULUDQ: {
35965     KnownBits Known2;
35966     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
35967     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
35968 
35969     Known = Known.trunc(BitWidth / 2).zext(BitWidth);
35970     Known2 = Known2.trunc(BitWidth / 2).zext(BitWidth);
35971     Known = KnownBits::mul(Known, Known2);
35972     break;
35973   }
35974   case X86ISD::CMOV: {
35975     Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
35976     // If we don't know any bits, early out.
35977     if (Known.isUnknown())
35978       break;
35979     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
35980 
35981     // Only known if known in both the LHS and RHS.
35982     Known = KnownBits::commonBits(Known, Known2);
35983     break;
35984   }
35985   case X86ISD::BEXTR:
35986   case X86ISD::BEXTRI: {
35987     SDValue Op0 = Op.getOperand(0);
35988     SDValue Op1 = Op.getOperand(1);
35989 
35990     if (auto* Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
35991       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
35992       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
35993 
35994       // If the length is 0, the result is 0.
35995       if (Length == 0) {
35996         Known.setAllZero();
35997         break;
35998       }
35999 
36000       if ((Shift + Length) <= BitWidth) {
36001         Known = DAG.computeKnownBits(Op0, Depth + 1);
36002         Known = Known.extractBits(Length, Shift);
36003         Known = Known.zextOrTrunc(BitWidth);
36004       }
36005     }
36006     break;
36007   }
36008   case X86ISD::PDEP: {
36009     KnownBits Known2;
36010     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36011     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36012     // Zeros are retained from the mask operand. But not ones.
36013     Known.One.clearAllBits();
36014     // The result will have at least as many trailing zeros as the non-mask
36015     // operand since bits can only map to the same or higher bit position.
36016     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
36017     break;
36018   }
36019   case X86ISD::PEXT: {
36020     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36021     // The result has as many leading zeros as the number of zeroes in the mask.
36022     unsigned Count = Known.Zero.countPopulation();
36023     Known.Zero = APInt::getHighBitsSet(BitWidth, Count);
36024     Known.One.clearAllBits();
36025     break;
36026   }
36027   case X86ISD::VTRUNC:
36028   case X86ISD::VTRUNCS:
36029   case X86ISD::VTRUNCUS:
36030   case X86ISD::CVTSI2P:
36031   case X86ISD::CVTUI2P:
36032   case X86ISD::CVTP2SI:
36033   case X86ISD::CVTP2UI:
36034   case X86ISD::MCVTP2SI:
36035   case X86ISD::MCVTP2UI:
36036   case X86ISD::CVTTP2SI:
36037   case X86ISD::CVTTP2UI:
36038   case X86ISD::MCVTTP2SI:
36039   case X86ISD::MCVTTP2UI:
36040   case X86ISD::MCVTSI2P:
36041   case X86ISD::MCVTUI2P:
36042   case X86ISD::VFPROUND:
36043   case X86ISD::VMFPROUND:
36044   case X86ISD::CVTPS2PH:
36045   case X86ISD::MCVTPS2PH: {
36046     // Truncations/Conversions - upper elements are known zero.
36047     EVT SrcVT = Op.getOperand(0).getValueType();
36048     if (SrcVT.isVector()) {
36049       unsigned NumSrcElts = SrcVT.getVectorNumElements();
36050       if (NumElts > NumSrcElts &&
36051           DemandedElts.countTrailingZeros() >= NumSrcElts)
36052         Known.setAllZero();
36053     }
36054     break;
36055   }
36056   case X86ISD::STRICT_CVTTP2SI:
36057   case X86ISD::STRICT_CVTTP2UI:
36058   case X86ISD::STRICT_CVTSI2P:
36059   case X86ISD::STRICT_CVTUI2P:
36060   case X86ISD::STRICT_VFPROUND:
36061   case X86ISD::STRICT_CVTPS2PH: {
36062     // Strict Conversions - upper elements are known zero.
36063     EVT SrcVT = Op.getOperand(1).getValueType();
36064     if (SrcVT.isVector()) {
36065       unsigned NumSrcElts = SrcVT.getVectorNumElements();
36066       if (NumElts > NumSrcElts &&
36067           DemandedElts.countTrailingZeros() >= NumSrcElts)
36068         Known.setAllZero();
36069     }
36070     break;
36071   }
36072   case X86ISD::MOVQ2DQ: {
36073     // Move from MMX to XMM. Upper half of XMM should be 0.
36074     if (DemandedElts.countTrailingZeros() >= (NumElts / 2))
36075       Known.setAllZero();
36076     break;
36077   }
36078   }
36079 
36080   // Handle target shuffles.
36081   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
36082   if (isTargetShuffle(Opc)) {
36083     SmallVector<int, 64> Mask;
36084     SmallVector<SDValue, 2> Ops;
36085     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
36086       unsigned NumOps = Ops.size();
36087       unsigned NumElts = VT.getVectorNumElements();
36088       if (Mask.size() == NumElts) {
36089         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
36090         Known.Zero.setAllBits(); Known.One.setAllBits();
36091         for (unsigned i = 0; i != NumElts; ++i) {
36092           if (!DemandedElts[i])
36093             continue;
36094           int M = Mask[i];
36095           if (M == SM_SentinelUndef) {
36096             // For UNDEF elements, we don't know anything about the common state
36097             // of the shuffle result.
36098             Known.resetAll();
36099             break;
36100           }
36101           if (M == SM_SentinelZero) {
36102             Known.One.clearAllBits();
36103             continue;
36104           }
36105           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
36106                  "Shuffle index out of range");
36107 
36108           unsigned OpIdx = (unsigned)M / NumElts;
36109           unsigned EltIdx = (unsigned)M % NumElts;
36110           if (Ops[OpIdx].getValueType() != VT) {
36111             // TODO - handle target shuffle ops with different value types.
36112             Known.resetAll();
36113             break;
36114           }
36115           DemandedOps[OpIdx].setBit(EltIdx);
36116         }
36117         // Known bits are the values that are shared by every demanded element.
36118         for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
36119           if (!DemandedOps[i])
36120             continue;
36121           KnownBits Known2 =
36122               DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
36123           Known = KnownBits::commonBits(Known, Known2);
36124         }
36125       }
36126     }
36127   }
36128 }
36129 
36130 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
36131     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
36132     unsigned Depth) const {
36133   EVT VT = Op.getValueType();
36134   unsigned VTBits = VT.getScalarSizeInBits();
36135   unsigned Opcode = Op.getOpcode();
36136   switch (Opcode) {
36137   case X86ISD::SETCC_CARRY:
36138     // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
36139     return VTBits;
36140 
36141   case X86ISD::VTRUNC: {
36142     SDValue Src = Op.getOperand(0);
36143     MVT SrcVT = Src.getSimpleValueType();
36144     unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
36145     assert(VTBits < NumSrcBits && "Illegal truncation input type");
36146     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
36147     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
36148     if (Tmp > (NumSrcBits - VTBits))
36149       return Tmp - (NumSrcBits - VTBits);
36150     return 1;
36151   }
36152 
36153   case X86ISD::PACKSS: {
36154     // PACKSS is just a truncation if the sign bits extend to the packed size.
36155     APInt DemandedLHS, DemandedRHS;
36156     getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
36157                         DemandedRHS);
36158 
36159     unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
36160     unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
36161     if (!!DemandedLHS)
36162       Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
36163     if (!!DemandedRHS)
36164       Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
36165     unsigned Tmp = std::min(Tmp0, Tmp1);
36166     if (Tmp > (SrcBits - VTBits))
36167       return Tmp - (SrcBits - VTBits);
36168     return 1;
36169   }
36170 
36171   case X86ISD::VBROADCAST: {
36172     SDValue Src = Op.getOperand(0);
36173     if (!Src.getSimpleValueType().isVector())
36174       return DAG.ComputeNumSignBits(Src, Depth + 1);
36175     break;
36176   }
36177 
36178   case X86ISD::VSHLI: {
36179     SDValue Src = Op.getOperand(0);
36180     const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
36181     if (ShiftVal.uge(VTBits))
36182       return VTBits; // Shifted all bits out --> zero.
36183     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
36184     if (ShiftVal.uge(Tmp))
36185       return 1; // Shifted all sign bits out --> unknown.
36186     return Tmp - ShiftVal.getZExtValue();
36187   }
36188 
36189   case X86ISD::VSRAI: {
36190     SDValue Src = Op.getOperand(0);
36191     APInt ShiftVal = Op.getConstantOperandAPInt(1);
36192     if (ShiftVal.uge(VTBits - 1))
36193       return VTBits; // Sign splat.
36194     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
36195     ShiftVal += Tmp;
36196     return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
36197   }
36198 
36199   case X86ISD::FSETCC:
36200     // cmpss/cmpsd return zero/all-bits result values in the bottom element.
36201     if (VT == MVT::f32 || VT == MVT::f64 ||
36202         ((VT == MVT::v4f32 || VT == MVT::v2f64) && DemandedElts == 1))
36203       return VTBits;
36204     break;
36205 
36206   case X86ISD::PCMPGT:
36207   case X86ISD::PCMPEQ:
36208   case X86ISD::CMPP:
36209   case X86ISD::VPCOM:
36210   case X86ISD::VPCOMU:
36211     // Vector compares return zero/all-bits result values.
36212     return VTBits;
36213 
36214   case X86ISD::ANDNP: {
36215     unsigned Tmp0 =
36216         DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
36217     if (Tmp0 == 1) return 1; // Early out.
36218     unsigned Tmp1 =
36219         DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
36220     return std::min(Tmp0, Tmp1);
36221   }
36222 
36223   case X86ISD::CMOV: {
36224     unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
36225     if (Tmp0 == 1) return 1;  // Early out.
36226     unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
36227     return std::min(Tmp0, Tmp1);
36228   }
36229   }
36230 
36231   // Handle target shuffles.
36232   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
36233   if (isTargetShuffle(Opcode)) {
36234     SmallVector<int, 64> Mask;
36235     SmallVector<SDValue, 2> Ops;
36236     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
36237       unsigned NumOps = Ops.size();
36238       unsigned NumElts = VT.getVectorNumElements();
36239       if (Mask.size() == NumElts) {
36240         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
36241         for (unsigned i = 0; i != NumElts; ++i) {
36242           if (!DemandedElts[i])
36243             continue;
36244           int M = Mask[i];
36245           if (M == SM_SentinelUndef) {
36246             // For UNDEF elements, we don't know anything about the common state
36247             // of the shuffle result.
36248             return 1;
36249           } else if (M == SM_SentinelZero) {
36250             // Zero = all sign bits.
36251             continue;
36252           }
36253           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
36254                  "Shuffle index out of range");
36255 
36256           unsigned OpIdx = (unsigned)M / NumElts;
36257           unsigned EltIdx = (unsigned)M % NumElts;
36258           if (Ops[OpIdx].getValueType() != VT) {
36259             // TODO - handle target shuffle ops with different value types.
36260             return 1;
36261           }
36262           DemandedOps[OpIdx].setBit(EltIdx);
36263         }
36264         unsigned Tmp0 = VTBits;
36265         for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
36266           if (!DemandedOps[i])
36267             continue;
36268           unsigned Tmp1 =
36269               DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
36270           Tmp0 = std::min(Tmp0, Tmp1);
36271         }
36272         return Tmp0;
36273       }
36274     }
36275   }
36276 
36277   // Fallback case.
36278   return 1;
36279 }
36280 
36281 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
36282   if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
36283     return N->getOperand(0);
36284   return N;
36285 }
36286 
36287 // Helper to look for a normal load that can be narrowed into a vzload with the
36288 // specified VT and memory VT. Returns SDValue() on failure.
36289 static SDValue narrowLoadToVZLoad(LoadSDNode *LN, MVT MemVT, MVT VT,
36290                                   SelectionDAG &DAG) {
36291   // Can't if the load is volatile or atomic.
36292   if (!LN->isSimple())
36293     return SDValue();
36294 
36295   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36296   SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
36297   return DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, SDLoc(LN), Tys, Ops, MemVT,
36298                                  LN->getPointerInfo(), LN->getOriginalAlign(),
36299                                  LN->getMemOperand()->getFlags());
36300 }
36301 
36302 // Attempt to match a combined shuffle mask against supported unary shuffle
36303 // instructions.
36304 // TODO: Investigate sharing more of this with shuffle lowering.
36305 static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
36306                               bool AllowFloatDomain, bool AllowIntDomain,
36307                               SDValue &V1, const SDLoc &DL, SelectionDAG &DAG,
36308                               const X86Subtarget &Subtarget, unsigned &Shuffle,
36309                               MVT &SrcVT, MVT &DstVT) {
36310   unsigned NumMaskElts = Mask.size();
36311   unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
36312 
36313   // Match against a VZEXT_MOVL vXi32 and vXi16 zero-extending instruction.
36314   if (Mask[0] == 0 &&
36315       (MaskEltSize == 32 || (MaskEltSize == 16 && Subtarget.hasFP16()))) {
36316     if ((isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) ||
36317         (V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
36318          isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1))) {
36319       Shuffle = X86ISD::VZEXT_MOVL;
36320       if (MaskEltSize == 16)
36321         SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
36322       else
36323         SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
36324       return true;
36325     }
36326   }
36327 
36328   // Match against a ANY/ZERO_EXTEND_VECTOR_INREG instruction.
36329   // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
36330   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
36331                          (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
36332     unsigned MaxScale = 64 / MaskEltSize;
36333     for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
36334       bool MatchAny = true;
36335       bool MatchZero = true;
36336       unsigned NumDstElts = NumMaskElts / Scale;
36337       for (unsigned i = 0; i != NumDstElts && (MatchAny || MatchZero); ++i) {
36338         if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
36339           MatchAny = MatchZero = false;
36340           break;
36341         }
36342         MatchAny &= isUndefInRange(Mask, (i * Scale) + 1, Scale - 1);
36343         MatchZero &= isUndefOrZeroInRange(Mask, (i * Scale) + 1, Scale - 1);
36344       }
36345       if (MatchAny || MatchZero) {
36346         assert(MatchZero && "Failed to match zext but matched aext?");
36347         unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
36348         MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType() :
36349                                             MVT::getIntegerVT(MaskEltSize);
36350         SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
36351 
36352         if (SrcVT.getSizeInBits() != MaskVT.getSizeInBits())
36353           V1 = extractSubVector(V1, 0, DAG, DL, SrcSize);
36354 
36355         Shuffle = unsigned(MatchAny ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND);
36356         if (SrcVT.getVectorNumElements() != NumDstElts)
36357           Shuffle = getOpcode_EXTEND_VECTOR_INREG(Shuffle);
36358 
36359         DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
36360         DstVT = MVT::getVectorVT(DstVT, NumDstElts);
36361         return true;
36362       }
36363     }
36364   }
36365 
36366   // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
36367   if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2()) ||
36368        (MaskEltSize == 16 && Subtarget.hasFP16())) &&
36369       isUndefOrEqual(Mask[0], 0) &&
36370       isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
36371     Shuffle = X86ISD::VZEXT_MOVL;
36372     if (MaskEltSize == 16)
36373       SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
36374     else
36375       SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
36376     return true;
36377   }
36378 
36379   // Check if we have SSE3 which will let us use MOVDDUP etc. The
36380   // instructions are no slower than UNPCKLPD but has the option to
36381   // fold the input operand into even an unaligned memory load.
36382   if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
36383     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, V1)) {
36384       Shuffle = X86ISD::MOVDDUP;
36385       SrcVT = DstVT = MVT::v2f64;
36386       return true;
36387     }
36388     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, V1)) {
36389       Shuffle = X86ISD::MOVSLDUP;
36390       SrcVT = DstVT = MVT::v4f32;
36391       return true;
36392     }
36393     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3}, V1)) {
36394       Shuffle = X86ISD::MOVSHDUP;
36395       SrcVT = DstVT = MVT::v4f32;
36396       return true;
36397     }
36398   }
36399 
36400   if (MaskVT.is256BitVector() && AllowFloatDomain) {
36401     assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
36402     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, V1)) {
36403       Shuffle = X86ISD::MOVDDUP;
36404       SrcVT = DstVT = MVT::v4f64;
36405       return true;
36406     }
36407     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1)) {
36408       Shuffle = X86ISD::MOVSLDUP;
36409       SrcVT = DstVT = MVT::v8f32;
36410       return true;
36411     }
36412     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3, 5, 5, 7, 7}, V1)) {
36413       Shuffle = X86ISD::MOVSHDUP;
36414       SrcVT = DstVT = MVT::v8f32;
36415       return true;
36416     }
36417   }
36418 
36419   if (MaskVT.is512BitVector() && AllowFloatDomain) {
36420     assert(Subtarget.hasAVX512() &&
36421            "AVX512 required for 512-bit vector shuffles");
36422     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1)) {
36423       Shuffle = X86ISD::MOVDDUP;
36424       SrcVT = DstVT = MVT::v8f64;
36425       return true;
36426     }
36427     if (isTargetShuffleEquivalent(
36428             MaskVT, Mask,
36429             {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14}, V1)) {
36430       Shuffle = X86ISD::MOVSLDUP;
36431       SrcVT = DstVT = MVT::v16f32;
36432       return true;
36433     }
36434     if (isTargetShuffleEquivalent(
36435             MaskVT, Mask,
36436             {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15}, V1)) {
36437       Shuffle = X86ISD::MOVSHDUP;
36438       SrcVT = DstVT = MVT::v16f32;
36439       return true;
36440     }
36441   }
36442 
36443   return false;
36444 }
36445 
36446 // Attempt to match a combined shuffle mask against supported unary immediate
36447 // permute instructions.
36448 // TODO: Investigate sharing more of this with shuffle lowering.
36449 static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
36450                                      const APInt &Zeroable,
36451                                      bool AllowFloatDomain, bool AllowIntDomain,
36452                                      const X86Subtarget &Subtarget,
36453                                      unsigned &Shuffle, MVT &ShuffleVT,
36454                                      unsigned &PermuteImm) {
36455   unsigned NumMaskElts = Mask.size();
36456   unsigned InputSizeInBits = MaskVT.getSizeInBits();
36457   unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
36458   MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
36459   bool ContainsZeros = isAnyZero(Mask);
36460 
36461   // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
36462   if (!ContainsZeros && MaskScalarSizeInBits == 64) {
36463     // Check for lane crossing permutes.
36464     if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
36465       // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
36466       if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
36467         Shuffle = X86ISD::VPERMI;
36468         ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
36469         PermuteImm = getV4X86ShuffleImm(Mask);
36470         return true;
36471       }
36472       if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
36473         SmallVector<int, 4> RepeatedMask;
36474         if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
36475           Shuffle = X86ISD::VPERMI;
36476           ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
36477           PermuteImm = getV4X86ShuffleImm(RepeatedMask);
36478           return true;
36479         }
36480       }
36481     } else if (AllowFloatDomain && Subtarget.hasAVX()) {
36482       // VPERMILPD can permute with a non-repeating shuffle.
36483       Shuffle = X86ISD::VPERMILPI;
36484       ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
36485       PermuteImm = 0;
36486       for (int i = 0, e = Mask.size(); i != e; ++i) {
36487         int M = Mask[i];
36488         if (M == SM_SentinelUndef)
36489           continue;
36490         assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
36491         PermuteImm |= (M & 1) << i;
36492       }
36493       return true;
36494     }
36495   }
36496 
36497   // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
36498   // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
36499   // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
36500   if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
36501       !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
36502     SmallVector<int, 4> RepeatedMask;
36503     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
36504       // Narrow the repeated mask to create 32-bit element permutes.
36505       SmallVector<int, 4> WordMask = RepeatedMask;
36506       if (MaskScalarSizeInBits == 64)
36507         narrowShuffleMaskElts(2, RepeatedMask, WordMask);
36508 
36509       Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
36510       ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
36511       ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
36512       PermuteImm = getV4X86ShuffleImm(WordMask);
36513       return true;
36514     }
36515   }
36516 
36517   // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
36518   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16 &&
36519       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
36520        (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
36521        (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
36522     SmallVector<int, 4> RepeatedMask;
36523     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
36524       ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
36525       ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
36526 
36527       // PSHUFLW: permute lower 4 elements only.
36528       if (isUndefOrInRange(LoMask, 0, 4) &&
36529           isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
36530         Shuffle = X86ISD::PSHUFLW;
36531         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
36532         PermuteImm = getV4X86ShuffleImm(LoMask);
36533         return true;
36534       }
36535 
36536       // PSHUFHW: permute upper 4 elements only.
36537       if (isUndefOrInRange(HiMask, 4, 8) &&
36538           isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
36539         // Offset the HiMask so that we can create the shuffle immediate.
36540         int OffsetHiMask[4];
36541         for (int i = 0; i != 4; ++i)
36542           OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
36543 
36544         Shuffle = X86ISD::PSHUFHW;
36545         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
36546         PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
36547         return true;
36548       }
36549     }
36550   }
36551 
36552   // Attempt to match against byte/bit shifts.
36553   if (AllowIntDomain &&
36554       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
36555        (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
36556        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
36557     int ShiftAmt = matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits,
36558                                        Mask, 0, Zeroable, Subtarget);
36559     if (0 < ShiftAmt && (!ShuffleVT.is512BitVector() || Subtarget.hasBWI() ||
36560                          32 <= ShuffleVT.getScalarSizeInBits())) {
36561       PermuteImm = (unsigned)ShiftAmt;
36562       return true;
36563     }
36564   }
36565 
36566   // Attempt to match against bit rotates.
36567   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits < 64 &&
36568       ((MaskVT.is128BitVector() && Subtarget.hasXOP()) ||
36569        Subtarget.hasAVX512())) {
36570     int RotateAmt = matchShuffleAsBitRotate(ShuffleVT, MaskScalarSizeInBits,
36571                                             Subtarget, Mask);
36572     if (0 < RotateAmt) {
36573       Shuffle = X86ISD::VROTLI;
36574       PermuteImm = (unsigned)RotateAmt;
36575       return true;
36576     }
36577   }
36578 
36579   return false;
36580 }
36581 
36582 // Attempt to match a combined unary shuffle mask against supported binary
36583 // shuffle instructions.
36584 // TODO: Investigate sharing more of this with shuffle lowering.
36585 static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
36586                                bool AllowFloatDomain, bool AllowIntDomain,
36587                                SDValue &V1, SDValue &V2, const SDLoc &DL,
36588                                SelectionDAG &DAG, const X86Subtarget &Subtarget,
36589                                unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
36590                                bool IsUnary) {
36591   unsigned NumMaskElts = Mask.size();
36592   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
36593 
36594   if (MaskVT.is128BitVector()) {
36595     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}) && AllowFloatDomain) {
36596       V2 = V1;
36597       V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
36598       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
36599       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
36600       return true;
36601     }
36602     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1}) && AllowFloatDomain) {
36603       V2 = V1;
36604       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
36605       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
36606       return true;
36607     }
36608     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 3}) &&
36609         Subtarget.hasSSE2() && (AllowFloatDomain || !Subtarget.hasSSE41())) {
36610       std::swap(V1, V2);
36611       Shuffle = X86ISD::MOVSD;
36612       SrcVT = DstVT = MVT::v2f64;
36613       return true;
36614     }
36615     if (isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}) &&
36616         (AllowFloatDomain || !Subtarget.hasSSE41())) {
36617       Shuffle = X86ISD::MOVSS;
36618       SrcVT = DstVT = MVT::v4f32;
36619       return true;
36620     }
36621     if (isTargetShuffleEquivalent(MaskVT, Mask, {8, 1, 2, 3, 4, 5, 6, 7}) &&
36622         Subtarget.hasFP16()) {
36623       Shuffle = X86ISD::MOVSH;
36624       SrcVT = DstVT = MVT::v8f16;
36625       return true;
36626     }
36627   }
36628 
36629   // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
36630   if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
36631       ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
36632       ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
36633     if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
36634                              Subtarget)) {
36635       DstVT = MaskVT;
36636       return true;
36637     }
36638   }
36639 
36640   // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
36641   if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
36642       (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
36643       (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
36644       (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
36645       (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
36646     if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
36647                               Subtarget)) {
36648       SrcVT = DstVT = MaskVT;
36649       if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
36650         SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
36651       return true;
36652     }
36653   }
36654 
36655   // Attempt to match against a OR if we're performing a blend shuffle and the
36656   // non-blended source element is zero in each case.
36657   if ((EltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
36658       (EltSizeInBits % V2.getScalarValueSizeInBits()) == 0) {
36659     bool IsBlend = true;
36660     unsigned NumV1Elts = V1.getValueType().getVectorNumElements();
36661     unsigned NumV2Elts = V2.getValueType().getVectorNumElements();
36662     unsigned Scale1 = NumV1Elts / NumMaskElts;
36663     unsigned Scale2 = NumV2Elts / NumMaskElts;
36664     APInt DemandedZeroV1 = APInt::getZero(NumV1Elts);
36665     APInt DemandedZeroV2 = APInt::getZero(NumV2Elts);
36666     for (unsigned i = 0; i != NumMaskElts; ++i) {
36667       int M = Mask[i];
36668       if (M == SM_SentinelUndef)
36669         continue;
36670       if (M == SM_SentinelZero) {
36671         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
36672         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
36673         continue;
36674       }
36675       if (M == (int)i) {
36676         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
36677         continue;
36678       }
36679       if (M == (int)(i + NumMaskElts)) {
36680         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
36681         continue;
36682       }
36683       IsBlend = false;
36684       break;
36685     }
36686     if (IsBlend) {
36687       if (DAG.computeKnownBits(V1, DemandedZeroV1).isZero() &&
36688           DAG.computeKnownBits(V2, DemandedZeroV2).isZero()) {
36689         Shuffle = ISD::OR;
36690         SrcVT = DstVT = MaskVT.changeTypeToInteger();
36691         return true;
36692       }
36693       if (NumV1Elts == NumV2Elts && NumV1Elts == NumMaskElts) {
36694         // FIXME: handle mismatched sizes?
36695         // TODO: investigate if `ISD::OR` handling in
36696         // `TargetLowering::SimplifyDemandedVectorElts` can be improved instead.
36697         auto computeKnownBitsElementWise = [&DAG](SDValue V) {
36698           unsigned NumElts = V.getValueType().getVectorNumElements();
36699           KnownBits Known(NumElts);
36700           for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
36701             APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
36702             KnownBits PeepholeKnown = DAG.computeKnownBits(V, Mask);
36703             if (PeepholeKnown.isZero())
36704               Known.Zero.setBit(EltIdx);
36705             if (PeepholeKnown.isAllOnes())
36706               Known.One.setBit(EltIdx);
36707           }
36708           return Known;
36709         };
36710 
36711         KnownBits V1Known = computeKnownBitsElementWise(V1);
36712         KnownBits V2Known = computeKnownBitsElementWise(V2);
36713 
36714         for (unsigned i = 0; i != NumMaskElts && IsBlend; ++i) {
36715           int M = Mask[i];
36716           if (M == SM_SentinelUndef)
36717             continue;
36718           if (M == SM_SentinelZero) {
36719             IsBlend &= V1Known.Zero[i] && V2Known.Zero[i];
36720             continue;
36721           }
36722           if (M == (int)i) {
36723             IsBlend &= V2Known.Zero[i] || V1Known.One[i];
36724             continue;
36725           }
36726           if (M == (int)(i + NumMaskElts)) {
36727             IsBlend &= V1Known.Zero[i] || V2Known.One[i];
36728             continue;
36729           }
36730           llvm_unreachable("will not get here.");
36731         }
36732         if (IsBlend) {
36733           Shuffle = ISD::OR;
36734           SrcVT = DstVT = MaskVT.changeTypeToInteger();
36735           return true;
36736         }
36737       }
36738     }
36739   }
36740 
36741   return false;
36742 }
36743 
36744 static bool matchBinaryPermuteShuffle(
36745     MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
36746     bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
36747     const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
36748     unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
36749   unsigned NumMaskElts = Mask.size();
36750   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
36751 
36752   // Attempt to match against VALIGND/VALIGNQ rotate.
36753   if (AllowIntDomain && (EltSizeInBits == 64 || EltSizeInBits == 32) &&
36754       ((MaskVT.is128BitVector() && Subtarget.hasVLX()) ||
36755        (MaskVT.is256BitVector() && Subtarget.hasVLX()) ||
36756        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
36757     if (!isAnyZero(Mask)) {
36758       int Rotation = matchShuffleAsElementRotate(V1, V2, Mask);
36759       if (0 < Rotation) {
36760         Shuffle = X86ISD::VALIGN;
36761         if (EltSizeInBits == 64)
36762           ShuffleVT = MVT::getVectorVT(MVT::i64, MaskVT.getSizeInBits() / 64);
36763         else
36764           ShuffleVT = MVT::getVectorVT(MVT::i32, MaskVT.getSizeInBits() / 32);
36765         PermuteImm = Rotation;
36766         return true;
36767       }
36768     }
36769   }
36770 
36771   // Attempt to match against PALIGNR byte rotate.
36772   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
36773                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
36774                          (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
36775     int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
36776     if (0 < ByteRotation) {
36777       Shuffle = X86ISD::PALIGNR;
36778       ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
36779       PermuteImm = ByteRotation;
36780       return true;
36781     }
36782   }
36783 
36784   // Attempt to combine to X86ISD::BLENDI.
36785   if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
36786                             (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
36787       (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
36788     uint64_t BlendMask = 0;
36789     bool ForceV1Zero = false, ForceV2Zero = false;
36790     SmallVector<int, 8> TargetMask(Mask.begin(), Mask.end());
36791     if (matchShuffleAsBlend(V1, V2, TargetMask, Zeroable, ForceV1Zero,
36792                             ForceV2Zero, BlendMask)) {
36793       if (MaskVT == MVT::v16i16) {
36794         // We can only use v16i16 PBLENDW if the lanes are repeated.
36795         SmallVector<int, 8> RepeatedMask;
36796         if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
36797                                         RepeatedMask)) {
36798           assert(RepeatedMask.size() == 8 &&
36799                  "Repeated mask size doesn't match!");
36800           PermuteImm = 0;
36801           for (int i = 0; i < 8; ++i)
36802             if (RepeatedMask[i] >= 8)
36803               PermuteImm |= 1 << i;
36804           V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
36805           V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
36806           Shuffle = X86ISD::BLENDI;
36807           ShuffleVT = MaskVT;
36808           return true;
36809         }
36810       } else {
36811         V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
36812         V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
36813         PermuteImm = (unsigned)BlendMask;
36814         Shuffle = X86ISD::BLENDI;
36815         ShuffleVT = MaskVT;
36816         return true;
36817       }
36818     }
36819   }
36820 
36821   // Attempt to combine to INSERTPS, but only if it has elements that need to
36822   // be set to zero.
36823   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
36824       MaskVT.is128BitVector() && isAnyZero(Mask) &&
36825       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
36826     Shuffle = X86ISD::INSERTPS;
36827     ShuffleVT = MVT::v4f32;
36828     return true;
36829   }
36830 
36831   // Attempt to combine to SHUFPD.
36832   if (AllowFloatDomain && EltSizeInBits == 64 &&
36833       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
36834        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
36835        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
36836     bool ForceV1Zero = false, ForceV2Zero = false;
36837     if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
36838                                PermuteImm, Mask, Zeroable)) {
36839       V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
36840       V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
36841       Shuffle = X86ISD::SHUFP;
36842       ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
36843       return true;
36844     }
36845   }
36846 
36847   // Attempt to combine to SHUFPS.
36848   if (AllowFloatDomain && EltSizeInBits == 32 &&
36849       ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
36850        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
36851        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
36852     SmallVector<int, 4> RepeatedMask;
36853     if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
36854       // Match each half of the repeated mask, to determine if its just
36855       // referencing one of the vectors, is zeroable or entirely undef.
36856       auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
36857         int M0 = RepeatedMask[Offset];
36858         int M1 = RepeatedMask[Offset + 1];
36859 
36860         if (isUndefInRange(RepeatedMask, Offset, 2)) {
36861           return DAG.getUNDEF(MaskVT);
36862         } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
36863           S0 = (SM_SentinelUndef == M0 ? -1 : 0);
36864           S1 = (SM_SentinelUndef == M1 ? -1 : 1);
36865           return getZeroVector(MaskVT, Subtarget, DAG, DL);
36866         } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
36867           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
36868           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
36869           return V1;
36870         } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
36871           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
36872           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
36873           return V2;
36874         }
36875 
36876         return SDValue();
36877       };
36878 
36879       int ShufMask[4] = {-1, -1, -1, -1};
36880       SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
36881       SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
36882 
36883       if (Lo && Hi) {
36884         V1 = Lo;
36885         V2 = Hi;
36886         Shuffle = X86ISD::SHUFP;
36887         ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
36888         PermuteImm = getV4X86ShuffleImm(ShufMask);
36889         return true;
36890       }
36891     }
36892   }
36893 
36894   // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
36895   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
36896       MaskVT.is128BitVector() &&
36897       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
36898     Shuffle = X86ISD::INSERTPS;
36899     ShuffleVT = MVT::v4f32;
36900     return true;
36901   }
36902 
36903   return false;
36904 }
36905 
36906 static SDValue combineX86ShuffleChainWithExtract(
36907     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
36908     bool HasVariableMask, bool AllowVariableCrossLaneMask,
36909     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
36910     const X86Subtarget &Subtarget);
36911 
36912 /// Combine an arbitrary chain of shuffles into a single instruction if
36913 /// possible.
36914 ///
36915 /// This is the leaf of the recursive combine below. When we have found some
36916 /// chain of single-use x86 shuffle instructions and accumulated the combined
36917 /// shuffle mask represented by them, this will try to pattern match that mask
36918 /// into either a single instruction if there is a special purpose instruction
36919 /// for this operation, or into a PSHUFB instruction which is a fully general
36920 /// instruction but should only be used to replace chains over a certain depth.
36921 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
36922                                       ArrayRef<int> BaseMask, int Depth,
36923                                       bool HasVariableMask,
36924                                       bool AllowVariableCrossLaneMask,
36925                                       bool AllowVariablePerLaneMask,
36926                                       SelectionDAG &DAG,
36927                                       const X86Subtarget &Subtarget) {
36928   assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
36929   assert((Inputs.size() == 1 || Inputs.size() == 2) &&
36930          "Unexpected number of shuffle inputs!");
36931 
36932   MVT RootVT = Root.getSimpleValueType();
36933   unsigned RootSizeInBits = RootVT.getSizeInBits();
36934   unsigned NumRootElts = RootVT.getVectorNumElements();
36935 
36936   // Canonicalize shuffle input op to the requested type.
36937   // TODO: Support cases where Op is smaller than VT.
36938   auto CanonicalizeShuffleInput = [&](MVT VT, SDValue Op) {
36939     return DAG.getBitcast(VT, Op);
36940   };
36941 
36942   // Find the inputs that enter the chain. Note that multiple uses are OK
36943   // here, we're not going to remove the operands we find.
36944   bool UnaryShuffle = (Inputs.size() == 1);
36945   SDValue V1 = peekThroughBitcasts(Inputs[0]);
36946   SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
36947                              : peekThroughBitcasts(Inputs[1]));
36948 
36949   MVT VT1 = V1.getSimpleValueType();
36950   MVT VT2 = V2.getSimpleValueType();
36951   assert(VT1.getSizeInBits() == RootSizeInBits &&
36952          VT2.getSizeInBits() == RootSizeInBits && "Vector size mismatch");
36953 
36954   SDLoc DL(Root);
36955   SDValue Res;
36956 
36957   unsigned NumBaseMaskElts = BaseMask.size();
36958   if (NumBaseMaskElts == 1) {
36959     assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
36960     return CanonicalizeShuffleInput(RootVT, V1);
36961   }
36962 
36963   bool OptForSize = DAG.shouldOptForSize();
36964   unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
36965   bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
36966                      (RootVT.isFloatingPoint() && Depth >= 1) ||
36967                      (RootVT.is256BitVector() && !Subtarget.hasAVX2());
36968 
36969   // Don't combine if we are a AVX512/EVEX target and the mask element size
36970   // is different from the root element size - this would prevent writemasks
36971   // from being reused.
36972   bool IsMaskedShuffle = false;
36973   if (RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128)) {
36974     if (Root.hasOneUse() && Root->use_begin()->getOpcode() == ISD::VSELECT &&
36975         Root->use_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
36976       IsMaskedShuffle = true;
36977     }
36978   }
36979 
36980   // If we are shuffling a broadcast (and not introducing zeros) then
36981   // we can just use the broadcast directly. This works for smaller broadcast
36982   // elements as well as they already repeat across each mask element
36983   if (UnaryShuffle && isTargetShuffleSplat(V1) && !isAnyZero(BaseMask) &&
36984       (BaseMaskEltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
36985       V1.getValueSizeInBits() >= RootSizeInBits) {
36986     return CanonicalizeShuffleInput(RootVT, V1);
36987   }
36988 
36989   SmallVector<int, 64> Mask(BaseMask.begin(), BaseMask.end());
36990 
36991   // See if the shuffle is a hidden identity shuffle - repeated args in HOPs
36992   // etc. can be simplified.
36993   if (VT1 == VT2 && VT1.getSizeInBits() == RootSizeInBits && VT1.isVector()) {
36994     SmallVector<int> ScaledMask, IdentityMask;
36995     unsigned NumElts = VT1.getVectorNumElements();
36996     if (Mask.size() <= NumElts &&
36997         scaleShuffleElements(Mask, NumElts, ScaledMask)) {
36998       for (unsigned i = 0; i != NumElts; ++i)
36999         IdentityMask.push_back(i);
37000       if (isTargetShuffleEquivalent(RootVT, ScaledMask, IdentityMask, V1, V2))
37001         return CanonicalizeShuffleInput(RootVT, V1);
37002     }
37003   }
37004 
37005   // Handle 128/256-bit lane shuffles of 512-bit vectors.
37006   if (RootVT.is512BitVector() &&
37007       (NumBaseMaskElts == 2 || NumBaseMaskElts == 4)) {
37008     // If the upper subvectors are zeroable, then an extract+insert is more
37009     // optimal than using X86ISD::SHUF128. The insertion is free, even if it has
37010     // to zero the upper subvectors.
37011     if (isUndefOrZeroInRange(Mask, 1, NumBaseMaskElts - 1)) {
37012       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
37013         return SDValue(); // Nothing to do!
37014       assert(isInRange(Mask[0], 0, NumBaseMaskElts) &&
37015              "Unexpected lane shuffle");
37016       Res = CanonicalizeShuffleInput(RootVT, V1);
37017       unsigned SubIdx = Mask[0] * (NumRootElts / NumBaseMaskElts);
37018       bool UseZero = isAnyZero(Mask);
37019       Res = extractSubVector(Res, SubIdx, DAG, DL, BaseMaskEltSizeInBits);
37020       return widenSubVector(Res, UseZero, Subtarget, DAG, DL, RootSizeInBits);
37021     }
37022 
37023     // Narrow shuffle mask to v4x128.
37024     SmallVector<int, 4> ScaledMask;
37025     assert((BaseMaskEltSizeInBits % 128) == 0 && "Illegal mask size");
37026     narrowShuffleMaskElts(BaseMaskEltSizeInBits / 128, Mask, ScaledMask);
37027 
37028     // Try to lower to vshuf64x2/vshuf32x4.
37029     auto MatchSHUF128 = [&](MVT ShuffleVT, const SDLoc &DL,
37030                             ArrayRef<int> ScaledMask, SDValue V1, SDValue V2,
37031                             SelectionDAG &DAG) {
37032       unsigned PermMask = 0;
37033       // Insure elements came from the same Op.
37034       SDValue Ops[2] = {DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT)};
37035       for (int i = 0; i < 4; ++i) {
37036         assert(ScaledMask[i] >= -1 && "Illegal shuffle sentinel value");
37037         if (ScaledMask[i] < 0)
37038           continue;
37039 
37040         SDValue Op = ScaledMask[i] >= 4 ? V2 : V1;
37041         unsigned OpIndex = i / 2;
37042         if (Ops[OpIndex].isUndef())
37043           Ops[OpIndex] = Op;
37044         else if (Ops[OpIndex] != Op)
37045           return SDValue();
37046 
37047         // Convert the 128-bit shuffle mask selection values into 128-bit
37048         // selection bits defined by a vshuf64x2 instruction's immediate control
37049         // byte.
37050         PermMask |= (ScaledMask[i] % 4) << (i * 2);
37051       }
37052 
37053       return DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
37054                          CanonicalizeShuffleInput(ShuffleVT, Ops[0]),
37055                          CanonicalizeShuffleInput(ShuffleVT, Ops[1]),
37056                          DAG.getTargetConstant(PermMask, DL, MVT::i8));
37057     };
37058 
37059     // FIXME: Is there a better way to do this? is256BitLaneRepeatedShuffleMask
37060     // doesn't work because our mask is for 128 bits and we don't have an MVT
37061     // to match that.
37062     bool PreferPERMQ = UnaryShuffle && isUndefOrInRange(ScaledMask[0], 0, 2) &&
37063                        isUndefOrInRange(ScaledMask[1], 0, 2) &&
37064                        isUndefOrInRange(ScaledMask[2], 2, 4) &&
37065                        isUndefOrInRange(ScaledMask[3], 2, 4) &&
37066                        (ScaledMask[0] < 0 || ScaledMask[2] < 0 ||
37067                         ScaledMask[0] == (ScaledMask[2] % 2)) &&
37068                        (ScaledMask[1] < 0 || ScaledMask[3] < 0 ||
37069                         ScaledMask[1] == (ScaledMask[3] % 2));
37070 
37071     if (!isAnyZero(ScaledMask) && !PreferPERMQ) {
37072       if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
37073         return SDValue(); // Nothing to do!
37074       MVT ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
37075       if (SDValue V = MatchSHUF128(ShuffleVT, DL, ScaledMask, V1, V2, DAG))
37076         return DAG.getBitcast(RootVT, V);
37077     }
37078   }
37079 
37080   // Handle 128-bit lane shuffles of 256-bit vectors.
37081   if (RootVT.is256BitVector() && NumBaseMaskElts == 2) {
37082     // If the upper half is zeroable, then an extract+insert is more optimal
37083     // than using X86ISD::VPERM2X128. The insertion is free, even if it has to
37084     // zero the upper half.
37085     if (isUndefOrZero(Mask[1])) {
37086       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
37087         return SDValue(); // Nothing to do!
37088       assert(isInRange(Mask[0], 0, 2) && "Unexpected lane shuffle");
37089       Res = CanonicalizeShuffleInput(RootVT, V1);
37090       Res = extract128BitVector(Res, Mask[0] * (NumRootElts / 2), DAG, DL);
37091       return widenSubVector(Res, Mask[1] == SM_SentinelZero, Subtarget, DAG, DL,
37092                             256);
37093     }
37094 
37095     // If we're inserting the low subvector, an insert-subvector 'concat'
37096     // pattern is quicker than VPERM2X128.
37097     // TODO: Add AVX2 support instead of VPERMQ/VPERMPD.
37098     if (BaseMask[0] == 0 && (BaseMask[1] == 0 || BaseMask[1] == 2) &&
37099         !Subtarget.hasAVX2()) {
37100       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
37101         return SDValue(); // Nothing to do!
37102       SDValue Lo = CanonicalizeShuffleInput(RootVT, V1);
37103       SDValue Hi = CanonicalizeShuffleInput(RootVT, BaseMask[1] == 0 ? V1 : V2);
37104       Hi = extractSubVector(Hi, 0, DAG, DL, 128);
37105       return insertSubVector(Lo, Hi, NumRootElts / 2, DAG, DL, 128);
37106     }
37107 
37108     if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
37109       return SDValue(); // Nothing to do!
37110 
37111     // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
37112     // we need to use the zeroing feature.
37113     // Prefer blends for sequential shuffles unless we are optimizing for size.
37114     if (UnaryShuffle &&
37115         !(Subtarget.hasAVX2() && isUndefOrInRange(Mask, 0, 2)) &&
37116         (OptForSize || !isSequentialOrUndefOrZeroInRange(Mask, 0, 2, 0))) {
37117       unsigned PermMask = 0;
37118       PermMask |= ((Mask[0] < 0 ? 0x8 : (Mask[0] & 1)) << 0);
37119       PermMask |= ((Mask[1] < 0 ? 0x8 : (Mask[1] & 1)) << 4);
37120       return DAG.getNode(
37121           X86ISD::VPERM2X128, DL, RootVT, CanonicalizeShuffleInput(RootVT, V1),
37122           DAG.getUNDEF(RootVT), DAG.getTargetConstant(PermMask, DL, MVT::i8));
37123     }
37124 
37125     if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
37126       return SDValue(); // Nothing to do!
37127 
37128     // TODO - handle AVX512VL cases with X86ISD::SHUF128.
37129     if (!UnaryShuffle && !IsMaskedShuffle) {
37130       assert(llvm::all_of(Mask, [](int M) { return 0 <= M && M < 4; }) &&
37131              "Unexpected shuffle sentinel value");
37132       // Prefer blends to X86ISD::VPERM2X128.
37133       if (!((Mask[0] == 0 && Mask[1] == 3) || (Mask[0] == 2 && Mask[1] == 1))) {
37134         unsigned PermMask = 0;
37135         PermMask |= ((Mask[0] & 3) << 0);
37136         PermMask |= ((Mask[1] & 3) << 4);
37137         SDValue LHS = isInRange(Mask[0], 0, 2) ? V1 : V2;
37138         SDValue RHS = isInRange(Mask[1], 0, 2) ? V1 : V2;
37139         return DAG.getNode(X86ISD::VPERM2X128, DL, RootVT,
37140                           CanonicalizeShuffleInput(RootVT, LHS),
37141                           CanonicalizeShuffleInput(RootVT, RHS),
37142                           DAG.getTargetConstant(PermMask, DL, MVT::i8));
37143       }
37144     }
37145   }
37146 
37147   // For masks that have been widened to 128-bit elements or more,
37148   // narrow back down to 64-bit elements.
37149   if (BaseMaskEltSizeInBits > 64) {
37150     assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
37151     int MaskScale = BaseMaskEltSizeInBits / 64;
37152     SmallVector<int, 64> ScaledMask;
37153     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
37154     Mask = std::move(ScaledMask);
37155   }
37156 
37157   // For masked shuffles, we're trying to match the root width for better
37158   // writemask folding, attempt to scale the mask.
37159   // TODO - variable shuffles might need this to be widened again.
37160   if (IsMaskedShuffle && NumRootElts > Mask.size()) {
37161     assert((NumRootElts % Mask.size()) == 0 && "Illegal mask size");
37162     int MaskScale = NumRootElts / Mask.size();
37163     SmallVector<int, 64> ScaledMask;
37164     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
37165     Mask = std::move(ScaledMask);
37166   }
37167 
37168   unsigned NumMaskElts = Mask.size();
37169   unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
37170 
37171   // Determine the effective mask value type.
37172   FloatDomain &= (32 <= MaskEltSizeInBits);
37173   MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
37174                            : MVT::getIntegerVT(MaskEltSizeInBits);
37175   MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
37176 
37177   // Only allow legal mask types.
37178   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
37179     return SDValue();
37180 
37181   // Attempt to match the mask against known shuffle patterns.
37182   MVT ShuffleSrcVT, ShuffleVT;
37183   unsigned Shuffle, PermuteImm;
37184 
37185   // Which shuffle domains are permitted?
37186   // Permit domain crossing at higher combine depths.
37187   // TODO: Should we indicate which domain is preferred if both are allowed?
37188   bool AllowFloatDomain = FloatDomain || (Depth >= 3);
37189   bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
37190                         (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
37191 
37192   // Determine zeroable mask elements.
37193   APInt KnownUndef, KnownZero;
37194   resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
37195   APInt Zeroable = KnownUndef | KnownZero;
37196 
37197   if (UnaryShuffle) {
37198     // Attempt to match against broadcast-from-vector.
37199     // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
37200     if ((Subtarget.hasAVX2() ||
37201          (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits)) &&
37202         (!IsMaskedShuffle || NumRootElts == NumMaskElts)) {
37203       if (isUndefOrEqual(Mask, 0)) {
37204         if (V1.getValueType() == MaskVT &&
37205             V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
37206             X86::mayFoldLoad(V1.getOperand(0), Subtarget)) {
37207           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
37208             return SDValue(); // Nothing to do!
37209           Res = V1.getOperand(0);
37210           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
37211           return DAG.getBitcast(RootVT, Res);
37212         }
37213         if (Subtarget.hasAVX2()) {
37214           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
37215             return SDValue(); // Nothing to do!
37216           Res = CanonicalizeShuffleInput(MaskVT, V1);
37217           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
37218           return DAG.getBitcast(RootVT, Res);
37219         }
37220       }
37221     }
37222 
37223     SDValue NewV1 = V1; // Save operand in case early exit happens.
37224     if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
37225                           DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
37226                           ShuffleVT) &&
37227         (!IsMaskedShuffle ||
37228          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
37229       if (Depth == 0 && Root.getOpcode() == Shuffle)
37230         return SDValue(); // Nothing to do!
37231       Res = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
37232       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
37233       return DAG.getBitcast(RootVT, Res);
37234     }
37235 
37236     if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
37237                                  AllowIntDomain, Subtarget, Shuffle, ShuffleVT,
37238                                  PermuteImm) &&
37239         (!IsMaskedShuffle ||
37240          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
37241       if (Depth == 0 && Root.getOpcode() == Shuffle)
37242         return SDValue(); // Nothing to do!
37243       Res = CanonicalizeShuffleInput(ShuffleVT, V1);
37244       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
37245                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
37246       return DAG.getBitcast(RootVT, Res);
37247     }
37248   }
37249 
37250   // Attempt to combine to INSERTPS, but only if the inserted element has come
37251   // from a scalar.
37252   // TODO: Handle other insertions here as well?
37253   if (!UnaryShuffle && AllowFloatDomain && RootSizeInBits == 128 &&
37254       Subtarget.hasSSE41() &&
37255       !isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3})) {
37256     if (MaskEltSizeInBits == 32) {
37257       SDValue SrcV1 = V1, SrcV2 = V2;
37258       if (matchShuffleAsInsertPS(SrcV1, SrcV2, PermuteImm, Zeroable, Mask,
37259                                  DAG) &&
37260           SrcV2.getOpcode() == ISD::SCALAR_TO_VECTOR) {
37261         if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
37262           return SDValue(); // Nothing to do!
37263         Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
37264                           CanonicalizeShuffleInput(MVT::v4f32, SrcV1),
37265                           CanonicalizeShuffleInput(MVT::v4f32, SrcV2),
37266                           DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
37267         return DAG.getBitcast(RootVT, Res);
37268       }
37269     }
37270     if (MaskEltSizeInBits == 64 &&
37271         isTargetShuffleEquivalent(MaskVT, Mask, {0, 2}) &&
37272         V2.getOpcode() == ISD::SCALAR_TO_VECTOR &&
37273         V2.getScalarValueSizeInBits() <= 32) {
37274       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
37275         return SDValue(); // Nothing to do!
37276       PermuteImm = (/*DstIdx*/2 << 4) | (/*SrcIdx*/0 << 0);
37277       Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
37278                         CanonicalizeShuffleInput(MVT::v4f32, V1),
37279                         CanonicalizeShuffleInput(MVT::v4f32, V2),
37280                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
37281       return DAG.getBitcast(RootVT, Res);
37282     }
37283   }
37284 
37285   SDValue NewV1 = V1; // Save operands in case early exit happens.
37286   SDValue NewV2 = V2;
37287   if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
37288                          NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
37289                          ShuffleVT, UnaryShuffle) &&
37290       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
37291     if (Depth == 0 && Root.getOpcode() == Shuffle)
37292       return SDValue(); // Nothing to do!
37293     NewV1 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
37294     NewV2 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV2);
37295     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
37296     return DAG.getBitcast(RootVT, Res);
37297   }
37298 
37299   NewV1 = V1; // Save operands in case early exit happens.
37300   NewV2 = V2;
37301   if (matchBinaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
37302                                 AllowIntDomain, NewV1, NewV2, DL, DAG,
37303                                 Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
37304       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
37305     if (Depth == 0 && Root.getOpcode() == Shuffle)
37306       return SDValue(); // Nothing to do!
37307     NewV1 = CanonicalizeShuffleInput(ShuffleVT, NewV1);
37308     NewV2 = CanonicalizeShuffleInput(ShuffleVT, NewV2);
37309     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
37310                       DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
37311     return DAG.getBitcast(RootVT, Res);
37312   }
37313 
37314   // Typically from here on, we need an integer version of MaskVT.
37315   MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
37316   IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
37317 
37318   // Annoyingly, SSE4A instructions don't map into the above match helpers.
37319   if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
37320     uint64_t BitLen, BitIdx;
37321     if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
37322                             Zeroable)) {
37323       if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
37324         return SDValue(); // Nothing to do!
37325       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
37326       Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
37327                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
37328                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
37329       return DAG.getBitcast(RootVT, Res);
37330     }
37331 
37332     if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
37333       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
37334         return SDValue(); // Nothing to do!
37335       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
37336       V2 = CanonicalizeShuffleInput(IntMaskVT, V2);
37337       Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
37338                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
37339                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
37340       return DAG.getBitcast(RootVT, Res);
37341     }
37342   }
37343 
37344   // Match shuffle against TRUNCATE patterns.
37345   if (AllowIntDomain && MaskEltSizeInBits < 64 && Subtarget.hasAVX512()) {
37346     // Match against a VTRUNC instruction, accounting for src/dst sizes.
37347     if (matchShuffleAsVTRUNC(ShuffleSrcVT, ShuffleVT, IntMaskVT, Mask, Zeroable,
37348                              Subtarget)) {
37349       bool IsTRUNCATE = ShuffleVT.getVectorNumElements() ==
37350                         ShuffleSrcVT.getVectorNumElements();
37351       unsigned Opc =
37352           IsTRUNCATE ? (unsigned)ISD::TRUNCATE : (unsigned)X86ISD::VTRUNC;
37353       if (Depth == 0 && Root.getOpcode() == Opc)
37354         return SDValue(); // Nothing to do!
37355       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
37356       Res = DAG.getNode(Opc, DL, ShuffleVT, V1);
37357       if (ShuffleVT.getSizeInBits() < RootSizeInBits)
37358         Res = widenSubVector(Res, true, Subtarget, DAG, DL, RootSizeInBits);
37359       return DAG.getBitcast(RootVT, Res);
37360     }
37361 
37362     // Do we need a more general binary truncation pattern?
37363     if (RootSizeInBits < 512 &&
37364         ((RootVT.is256BitVector() && Subtarget.useAVX512Regs()) ||
37365          (RootVT.is128BitVector() && Subtarget.hasVLX())) &&
37366         (MaskEltSizeInBits > 8 || Subtarget.hasBWI()) &&
37367         isSequentialOrUndefInRange(Mask, 0, NumMaskElts, 0, 2)) {
37368       if (Depth == 0 && Root.getOpcode() == ISD::TRUNCATE)
37369         return SDValue(); // Nothing to do!
37370       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
37371       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts / 2);
37372       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
37373       V2 = CanonicalizeShuffleInput(ShuffleSrcVT, V2);
37374       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
37375       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts);
37376       Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShuffleSrcVT, V1, V2);
37377       Res = DAG.getNode(ISD::TRUNCATE, DL, IntMaskVT, Res);
37378       return DAG.getBitcast(RootVT, Res);
37379     }
37380   }
37381 
37382   // Don't try to re-form single instruction chains under any circumstances now
37383   // that we've done encoding canonicalization for them.
37384   if (Depth < 1)
37385     return SDValue();
37386 
37387   // Depth threshold above which we can efficiently use variable mask shuffles.
37388   int VariableCrossLaneShuffleDepth =
37389       Subtarget.hasFastVariableCrossLaneShuffle() ? 1 : 2;
37390   int VariablePerLaneShuffleDepth =
37391       Subtarget.hasFastVariablePerLaneShuffle() ? 1 : 2;
37392   AllowVariableCrossLaneMask &=
37393       (Depth >= VariableCrossLaneShuffleDepth) || HasVariableMask;
37394   AllowVariablePerLaneMask &=
37395       (Depth >= VariablePerLaneShuffleDepth) || HasVariableMask;
37396   // VPERMI2W/VPERMI2B are 3 uops on Skylake and Icelake so we require a
37397   // higher depth before combining them.
37398   bool AllowBWIVPERMV3 =
37399       (Depth >= (VariableCrossLaneShuffleDepth + 2) || HasVariableMask);
37400 
37401   bool MaskContainsZeros = isAnyZero(Mask);
37402 
37403   if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
37404     // If we have a single input lane-crossing shuffle then lower to VPERMV.
37405     if (UnaryShuffle && AllowVariableCrossLaneMask && !MaskContainsZeros) {
37406       if (Subtarget.hasAVX2() &&
37407           (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) {
37408         SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
37409         Res = CanonicalizeShuffleInput(MaskVT, V1);
37410         Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
37411         return DAG.getBitcast(RootVT, Res);
37412       }
37413       // AVX512 variants (non-VLX will pad to 512-bit shuffles).
37414       if ((Subtarget.hasAVX512() &&
37415            (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
37416             MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
37417           (Subtarget.hasBWI() &&
37418            (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
37419           (Subtarget.hasVBMI() &&
37420            (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8))) {
37421         V1 = CanonicalizeShuffleInput(MaskVT, V1);
37422         V2 = DAG.getUNDEF(MaskVT);
37423         Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
37424         return DAG.getBitcast(RootVT, Res);
37425       }
37426     }
37427 
37428     // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
37429     // vector as the second source (non-VLX will pad to 512-bit shuffles).
37430     if (UnaryShuffle && AllowVariableCrossLaneMask &&
37431         ((Subtarget.hasAVX512() &&
37432           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
37433            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
37434            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32 ||
37435            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
37436          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
37437           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
37438          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
37439           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
37440       // Adjust shuffle mask - replace SM_SentinelZero with second source index.
37441       for (unsigned i = 0; i != NumMaskElts; ++i)
37442         if (Mask[i] == SM_SentinelZero)
37443           Mask[i] = NumMaskElts + i;
37444       V1 = CanonicalizeShuffleInput(MaskVT, V1);
37445       V2 = getZeroVector(MaskVT, Subtarget, DAG, DL);
37446       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
37447       return DAG.getBitcast(RootVT, Res);
37448     }
37449 
37450     // If that failed and either input is extracted then try to combine as a
37451     // shuffle with the larger type.
37452     if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
37453             Inputs, Root, BaseMask, Depth, HasVariableMask,
37454             AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG,
37455             Subtarget))
37456       return WideShuffle;
37457 
37458     // If we have a dual input lane-crossing shuffle then lower to VPERMV3,
37459     // (non-VLX will pad to 512-bit shuffles).
37460     if (AllowVariableCrossLaneMask && !MaskContainsZeros &&
37461         ((Subtarget.hasAVX512() &&
37462           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
37463            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
37464            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32 ||
37465            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
37466          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
37467           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
37468          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
37469           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
37470       V1 = CanonicalizeShuffleInput(MaskVT, V1);
37471       V2 = CanonicalizeShuffleInput(MaskVT, V2);
37472       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
37473       return DAG.getBitcast(RootVT, Res);
37474     }
37475     return SDValue();
37476   }
37477 
37478   // See if we can combine a single input shuffle with zeros to a bit-mask,
37479   // which is much simpler than any shuffle.
37480   if (UnaryShuffle && MaskContainsZeros && AllowVariablePerLaneMask &&
37481       isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
37482       DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
37483     APInt Zero = APInt::getZero(MaskEltSizeInBits);
37484     APInt AllOnes = APInt::getAllOnes(MaskEltSizeInBits);
37485     APInt UndefElts(NumMaskElts, 0);
37486     SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
37487     for (unsigned i = 0; i != NumMaskElts; ++i) {
37488       int M = Mask[i];
37489       if (M == SM_SentinelUndef) {
37490         UndefElts.setBit(i);
37491         continue;
37492       }
37493       if (M == SM_SentinelZero)
37494         continue;
37495       EltBits[i] = AllOnes;
37496     }
37497     SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
37498     Res = CanonicalizeShuffleInput(MaskVT, V1);
37499     unsigned AndOpcode =
37500         MaskVT.isFloatingPoint() ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
37501     Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
37502     return DAG.getBitcast(RootVT, Res);
37503   }
37504 
37505   // If we have a single input shuffle with different shuffle patterns in the
37506   // the 128-bit lanes use the variable mask to VPERMILPS.
37507   // TODO Combine other mask types at higher depths.
37508   if (UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
37509       ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
37510        (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
37511     SmallVector<SDValue, 16> VPermIdx;
37512     for (int M : Mask) {
37513       SDValue Idx =
37514           M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
37515       VPermIdx.push_back(Idx);
37516     }
37517     SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
37518     Res = CanonicalizeShuffleInput(MaskVT, V1);
37519     Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
37520     return DAG.getBitcast(RootVT, Res);
37521   }
37522 
37523   // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
37524   // to VPERMIL2PD/VPERMIL2PS.
37525   if (AllowVariablePerLaneMask && Subtarget.hasXOP() &&
37526       (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
37527        MaskVT == MVT::v8f32)) {
37528     // VPERMIL2 Operation.
37529     // Bits[3] - Match Bit.
37530     // Bits[2:1] - (Per Lane) PD Shuffle Mask.
37531     // Bits[2:0] - (Per Lane) PS Shuffle Mask.
37532     unsigned NumLanes = MaskVT.getSizeInBits() / 128;
37533     unsigned NumEltsPerLane = NumMaskElts / NumLanes;
37534     SmallVector<int, 8> VPerm2Idx;
37535     unsigned M2ZImm = 0;
37536     for (int M : Mask) {
37537       if (M == SM_SentinelUndef) {
37538         VPerm2Idx.push_back(-1);
37539         continue;
37540       }
37541       if (M == SM_SentinelZero) {
37542         M2ZImm = 2;
37543         VPerm2Idx.push_back(8);
37544         continue;
37545       }
37546       int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
37547       Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
37548       VPerm2Idx.push_back(Index);
37549     }
37550     V1 = CanonicalizeShuffleInput(MaskVT, V1);
37551     V2 = CanonicalizeShuffleInput(MaskVT, V2);
37552     SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
37553     Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
37554                       DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
37555     return DAG.getBitcast(RootVT, Res);
37556   }
37557 
37558   // If we have 3 or more shuffle instructions or a chain involving a variable
37559   // mask, we can replace them with a single PSHUFB instruction profitably.
37560   // Intel's manuals suggest only using PSHUFB if doing so replacing 5
37561   // instructions, but in practice PSHUFB tends to be *very* fast so we're
37562   // more aggressive.
37563   if (UnaryShuffle && AllowVariablePerLaneMask &&
37564       ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
37565        (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
37566        (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
37567     SmallVector<SDValue, 16> PSHUFBMask;
37568     int NumBytes = RootVT.getSizeInBits() / 8;
37569     int Ratio = NumBytes / NumMaskElts;
37570     for (int i = 0; i < NumBytes; ++i) {
37571       int M = Mask[i / Ratio];
37572       if (M == SM_SentinelUndef) {
37573         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
37574         continue;
37575       }
37576       if (M == SM_SentinelZero) {
37577         PSHUFBMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
37578         continue;
37579       }
37580       M = Ratio * M + i % Ratio;
37581       assert((M / 16) == (i / 16) && "Lane crossing detected");
37582       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
37583     }
37584     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
37585     Res = CanonicalizeShuffleInput(ByteVT, V1);
37586     SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
37587     Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
37588     return DAG.getBitcast(RootVT, Res);
37589   }
37590 
37591   // With XOP, if we have a 128-bit binary input shuffle we can always combine
37592   // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
37593   // slower than PSHUFB on targets that support both.
37594   if (AllowVariablePerLaneMask && RootVT.is128BitVector() &&
37595       Subtarget.hasXOP()) {
37596     // VPPERM Mask Operation
37597     // Bits[4:0] - Byte Index (0 - 31)
37598     // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
37599     SmallVector<SDValue, 16> VPPERMMask;
37600     int NumBytes = 16;
37601     int Ratio = NumBytes / NumMaskElts;
37602     for (int i = 0; i < NumBytes; ++i) {
37603       int M = Mask[i / Ratio];
37604       if (M == SM_SentinelUndef) {
37605         VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
37606         continue;
37607       }
37608       if (M == SM_SentinelZero) {
37609         VPPERMMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
37610         continue;
37611       }
37612       M = Ratio * M + i % Ratio;
37613       VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
37614     }
37615     MVT ByteVT = MVT::v16i8;
37616     V1 = CanonicalizeShuffleInput(ByteVT, V1);
37617     V2 = CanonicalizeShuffleInput(ByteVT, V2);
37618     SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
37619     Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
37620     return DAG.getBitcast(RootVT, Res);
37621   }
37622 
37623   // If that failed and either input is extracted then try to combine as a
37624   // shuffle with the larger type.
37625   if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
37626           Inputs, Root, BaseMask, Depth, HasVariableMask,
37627           AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG, Subtarget))
37628     return WideShuffle;
37629 
37630   // If we have a dual input shuffle then lower to VPERMV3,
37631   // (non-VLX will pad to 512-bit shuffles)
37632   if (!UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
37633       ((Subtarget.hasAVX512() &&
37634         (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v8f64 ||
37635          MaskVT == MVT::v2i64 || MaskVT == MVT::v4i64 || MaskVT == MVT::v8i64 ||
37636          MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 || MaskVT == MVT::v8f32 ||
37637          MaskVT == MVT::v8i32 || MaskVT == MVT::v16f32 ||
37638          MaskVT == MVT::v16i32)) ||
37639        (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
37640         (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16 ||
37641          MaskVT == MVT::v32i16)) ||
37642        (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
37643         (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8 ||
37644          MaskVT == MVT::v64i8)))) {
37645     V1 = CanonicalizeShuffleInput(MaskVT, V1);
37646     V2 = CanonicalizeShuffleInput(MaskVT, V2);
37647     Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
37648     return DAG.getBitcast(RootVT, Res);
37649   }
37650 
37651   // Failed to find any combines.
37652   return SDValue();
37653 }
37654 
37655 // Combine an arbitrary chain of shuffles + extract_subvectors into a single
37656 // instruction if possible.
37657 //
37658 // Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
37659 // type size to attempt to combine:
37660 // shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
37661 // -->
37662 // extract_subvector(shuffle(x,y,m2),0)
37663 static SDValue combineX86ShuffleChainWithExtract(
37664     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
37665     bool HasVariableMask, bool AllowVariableCrossLaneMask,
37666     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
37667     const X86Subtarget &Subtarget) {
37668   unsigned NumMaskElts = BaseMask.size();
37669   unsigned NumInputs = Inputs.size();
37670   if (NumInputs == 0)
37671     return SDValue();
37672 
37673   EVT RootVT = Root.getValueType();
37674   unsigned RootSizeInBits = RootVT.getSizeInBits();
37675   assert((RootSizeInBits % NumMaskElts) == 0 && "Unexpected root shuffle mask");
37676 
37677   SmallVector<SDValue, 4> WideInputs(Inputs.begin(), Inputs.end());
37678   SmallVector<unsigned, 4> Offsets(NumInputs, 0);
37679 
37680   // Peek through subvectors.
37681   // TODO: Support inter-mixed EXTRACT_SUBVECTORs + BITCASTs?
37682   unsigned WideSizeInBits = RootSizeInBits;
37683   for (unsigned i = 0; i != NumInputs; ++i) {
37684     SDValue &Src = WideInputs[i];
37685     unsigned &Offset = Offsets[i];
37686     Src = peekThroughBitcasts(Src);
37687     EVT BaseVT = Src.getValueType();
37688     while (Src.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
37689       Offset += Src.getConstantOperandVal(1);
37690       Src = Src.getOperand(0);
37691     }
37692     WideSizeInBits = std::max(WideSizeInBits,
37693                               (unsigned)Src.getValueSizeInBits());
37694     assert((Offset % BaseVT.getVectorNumElements()) == 0 &&
37695            "Unexpected subvector extraction");
37696     Offset /= BaseVT.getVectorNumElements();
37697     Offset *= NumMaskElts;
37698   }
37699 
37700   // Bail if we're always extracting from the lowest subvectors,
37701   // combineX86ShuffleChain should match this for the current width.
37702   if (llvm::all_of(Offsets, [](unsigned Offset) { return Offset == 0; }))
37703     return SDValue();
37704 
37705   unsigned Scale = WideSizeInBits / RootSizeInBits;
37706   assert((WideSizeInBits % RootSizeInBits) == 0 &&
37707          "Unexpected subvector extraction");
37708 
37709   // If the src vector types aren't the same, see if we can extend
37710   // them to match each other.
37711   // TODO: Support different scalar types?
37712   EVT WideSVT = WideInputs[0].getValueType().getScalarType();
37713   if (llvm::any_of(WideInputs, [&WideSVT, &DAG](SDValue Op) {
37714         return !DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()) ||
37715                Op.getValueType().getScalarType() != WideSVT;
37716       }))
37717     return SDValue();
37718 
37719   for (SDValue &NewInput : WideInputs) {
37720     assert((WideSizeInBits % NewInput.getValueSizeInBits()) == 0 &&
37721            "Shuffle vector size mismatch");
37722     if (WideSizeInBits > NewInput.getValueSizeInBits())
37723       NewInput = widenSubVector(NewInput, false, Subtarget, DAG,
37724                                 SDLoc(NewInput), WideSizeInBits);
37725     assert(WideSizeInBits == NewInput.getValueSizeInBits() &&
37726            "Unexpected subvector extraction");
37727   }
37728 
37729   // Create new mask for larger type.
37730   for (unsigned i = 1; i != NumInputs; ++i)
37731     Offsets[i] += i * Scale * NumMaskElts;
37732 
37733   SmallVector<int, 64> WideMask(BaseMask.begin(), BaseMask.end());
37734   for (int &M : WideMask) {
37735     if (M < 0)
37736       continue;
37737     M = (M % NumMaskElts) + Offsets[M / NumMaskElts];
37738   }
37739   WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
37740 
37741   // Remove unused/repeated shuffle source ops.
37742   resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
37743   assert(!WideInputs.empty() && "Shuffle with no inputs detected");
37744 
37745   if (WideInputs.size() > 2)
37746     return SDValue();
37747 
37748   // Increase depth for every upper subvector we've peeked through.
37749   Depth += count_if(Offsets, [](unsigned Offset) { return Offset > 0; });
37750 
37751   // Attempt to combine wider chain.
37752   // TODO: Can we use a better Root?
37753   SDValue WideRoot = WideInputs[0];
37754   if (SDValue WideShuffle =
37755           combineX86ShuffleChain(WideInputs, WideRoot, WideMask, Depth,
37756                                  HasVariableMask, AllowVariableCrossLaneMask,
37757                                  AllowVariablePerLaneMask, DAG, Subtarget)) {
37758     WideShuffle =
37759         extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
37760     return DAG.getBitcast(RootVT, WideShuffle);
37761   }
37762   return SDValue();
37763 }
37764 
37765 // Canonicalize the combined shuffle mask chain with horizontal ops.
37766 // NOTE: This may update the Ops and Mask.
37767 static SDValue canonicalizeShuffleMaskWithHorizOp(
37768     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
37769     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
37770     const X86Subtarget &Subtarget) {
37771   if (Mask.empty() || Ops.empty())
37772     return SDValue();
37773 
37774   SmallVector<SDValue> BC;
37775   for (SDValue Op : Ops)
37776     BC.push_back(peekThroughBitcasts(Op));
37777 
37778   // All ops must be the same horizop + type.
37779   SDValue BC0 = BC[0];
37780   EVT VT0 = BC0.getValueType();
37781   unsigned Opcode0 = BC0.getOpcode();
37782   if (VT0.getSizeInBits() != RootSizeInBits || llvm::any_of(BC, [&](SDValue V) {
37783         return V.getOpcode() != Opcode0 || V.getValueType() != VT0;
37784       }))
37785     return SDValue();
37786 
37787   bool isHoriz = (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
37788                   Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB);
37789   bool isPack = (Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS);
37790   if (!isHoriz && !isPack)
37791     return SDValue();
37792 
37793   // Do all ops have a single use?
37794   bool OneUseOps = llvm::all_of(Ops, [](SDValue Op) {
37795     return Op.hasOneUse() &&
37796            peekThroughBitcasts(Op) == peekThroughOneUseBitcasts(Op);
37797   });
37798 
37799   int NumElts = VT0.getVectorNumElements();
37800   int NumLanes = VT0.getSizeInBits() / 128;
37801   int NumEltsPerLane = NumElts / NumLanes;
37802   int NumHalfEltsPerLane = NumEltsPerLane / 2;
37803   MVT SrcVT = BC0.getOperand(0).getSimpleValueType();
37804   unsigned EltSizeInBits = RootSizeInBits / Mask.size();
37805 
37806   if (NumEltsPerLane >= 4 &&
37807       (isPack || shouldUseHorizontalOp(Ops.size() == 1, DAG, Subtarget))) {
37808     SmallVector<int> LaneMask, ScaledMask;
37809     if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, LaneMask) &&
37810         scaleShuffleElements(LaneMask, 4, ScaledMask)) {
37811       // See if we can remove the shuffle by resorting the HOP chain so that
37812       // the HOP args are pre-shuffled.
37813       // TODO: Generalize to any sized/depth chain.
37814       // TODO: Add support for PACKSS/PACKUS.
37815       if (isHoriz) {
37816         // Attempt to find a HOP(HOP(X,Y),HOP(Z,W)) source operand.
37817         auto GetHOpSrc = [&](int M) {
37818           if (M == SM_SentinelUndef)
37819             return DAG.getUNDEF(VT0);
37820           if (M == SM_SentinelZero)
37821             return getZeroVector(VT0.getSimpleVT(), Subtarget, DAG, DL);
37822           SDValue Src0 = BC[M / 4];
37823           SDValue Src1 = Src0.getOperand((M % 4) >= 2);
37824           if (Src1.getOpcode() == Opcode0 && Src0->isOnlyUserOf(Src1.getNode()))
37825             return Src1.getOperand(M % 2);
37826           return SDValue();
37827         };
37828         SDValue M0 = GetHOpSrc(ScaledMask[0]);
37829         SDValue M1 = GetHOpSrc(ScaledMask[1]);
37830         SDValue M2 = GetHOpSrc(ScaledMask[2]);
37831         SDValue M3 = GetHOpSrc(ScaledMask[3]);
37832         if (M0 && M1 && M2 && M3) {
37833           SDValue LHS = DAG.getNode(Opcode0, DL, SrcVT, M0, M1);
37834           SDValue RHS = DAG.getNode(Opcode0, DL, SrcVT, M2, M3);
37835           return DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
37836         }
37837       }
37838       // shuffle(hop(x,y),hop(z,w)) -> permute(hop(x,z)) etc.
37839       if (Ops.size() >= 2) {
37840         SDValue LHS, RHS;
37841         auto GetHOpSrc = [&](int M, int &OutM) {
37842           // TODO: Support SM_SentinelZero
37843           if (M < 0)
37844             return M == SM_SentinelUndef;
37845           SDValue Src = BC[M / 4].getOperand((M % 4) >= 2);
37846           if (!LHS || LHS == Src) {
37847             LHS = Src;
37848             OutM = (M % 2);
37849             return true;
37850           }
37851           if (!RHS || RHS == Src) {
37852             RHS = Src;
37853             OutM = (M % 2) + 2;
37854             return true;
37855           }
37856           return false;
37857         };
37858         int PostMask[4] = {-1, -1, -1, -1};
37859         if (GetHOpSrc(ScaledMask[0], PostMask[0]) &&
37860             GetHOpSrc(ScaledMask[1], PostMask[1]) &&
37861             GetHOpSrc(ScaledMask[2], PostMask[2]) &&
37862             GetHOpSrc(ScaledMask[3], PostMask[3])) {
37863           LHS = DAG.getBitcast(SrcVT, LHS);
37864           RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
37865           SDValue Res = DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
37866           // Use SHUFPS for the permute so this will work on SSE3 targets,
37867           // shuffle combining and domain handling will simplify this later on.
37868           MVT ShuffleVT = MVT::getVectorVT(MVT::f32, RootSizeInBits / 32);
37869           Res = DAG.getBitcast(ShuffleVT, Res);
37870           return DAG.getNode(X86ISD::SHUFP, DL, ShuffleVT, Res, Res,
37871                              getV4X86ShuffleImm8ForMask(PostMask, DL, DAG));
37872         }
37873       }
37874     }
37875   }
37876 
37877   if (2 < Ops.size())
37878     return SDValue();
37879 
37880   SDValue BC1 = BC[BC.size() - 1];
37881   if (Mask.size() == VT0.getVectorNumElements()) {
37882     // Canonicalize binary shuffles of horizontal ops that use the
37883     // same sources to an unary shuffle.
37884     // TODO: Try to perform this fold even if the shuffle remains.
37885     if (Ops.size() == 2) {
37886       auto ContainsOps = [](SDValue HOp, SDValue Op) {
37887         return Op == HOp.getOperand(0) || Op == HOp.getOperand(1);
37888       };
37889       // Commute if all BC0's ops are contained in BC1.
37890       if (ContainsOps(BC1, BC0.getOperand(0)) &&
37891           ContainsOps(BC1, BC0.getOperand(1))) {
37892         ShuffleVectorSDNode::commuteMask(Mask);
37893         std::swap(Ops[0], Ops[1]);
37894         std::swap(BC0, BC1);
37895       }
37896 
37897       // If BC1 can be represented by BC0, then convert to unary shuffle.
37898       if (ContainsOps(BC0, BC1.getOperand(0)) &&
37899           ContainsOps(BC0, BC1.getOperand(1))) {
37900         for (int &M : Mask) {
37901           if (M < NumElts) // BC0 element or UNDEF/Zero sentinel.
37902             continue;
37903           int SubLane = ((M % NumEltsPerLane) >= NumHalfEltsPerLane) ? 1 : 0;
37904           M -= NumElts + (SubLane * NumHalfEltsPerLane);
37905           if (BC1.getOperand(SubLane) != BC0.getOperand(0))
37906             M += NumHalfEltsPerLane;
37907         }
37908       }
37909     }
37910 
37911     // Canonicalize unary horizontal ops to only refer to lower halves.
37912     for (int i = 0; i != NumElts; ++i) {
37913       int &M = Mask[i];
37914       if (isUndefOrZero(M))
37915         continue;
37916       if (M < NumElts && BC0.getOperand(0) == BC0.getOperand(1) &&
37917           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
37918         M -= NumHalfEltsPerLane;
37919       if (NumElts <= M && BC1.getOperand(0) == BC1.getOperand(1) &&
37920           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
37921         M -= NumHalfEltsPerLane;
37922     }
37923   }
37924 
37925   // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
37926   // single instruction. Attempt to match a v2X64 repeating shuffle pattern that
37927   // represents the LHS/RHS inputs for the lower/upper halves.
37928   SmallVector<int, 16> TargetMask128, WideMask128;
37929   if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, TargetMask128) &&
37930       scaleShuffleElements(TargetMask128, 2, WideMask128)) {
37931     assert(isUndefOrZeroOrInRange(WideMask128, 0, 4) && "Illegal shuffle");
37932     bool SingleOp = (Ops.size() == 1);
37933     if (isPack || OneUseOps ||
37934         shouldUseHorizontalOp(SingleOp, DAG, Subtarget)) {
37935       SDValue Lo = isInRange(WideMask128[0], 0, 2) ? BC0 : BC1;
37936       SDValue Hi = isInRange(WideMask128[1], 0, 2) ? BC0 : BC1;
37937       Lo = Lo.getOperand(WideMask128[0] & 1);
37938       Hi = Hi.getOperand(WideMask128[1] & 1);
37939       if (SingleOp) {
37940         SDValue Undef = DAG.getUNDEF(SrcVT);
37941         SDValue Zero = getZeroVector(SrcVT, Subtarget, DAG, DL);
37942         Lo = (WideMask128[0] == SM_SentinelZero ? Zero : Lo);
37943         Hi = (WideMask128[1] == SM_SentinelZero ? Zero : Hi);
37944         Lo = (WideMask128[0] == SM_SentinelUndef ? Undef : Lo);
37945         Hi = (WideMask128[1] == SM_SentinelUndef ? Undef : Hi);
37946       }
37947       return DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
37948     }
37949   }
37950 
37951   return SDValue();
37952 }
37953 
37954 // Attempt to constant fold all of the constant source ops.
37955 // Returns true if the entire shuffle is folded to a constant.
37956 // TODO: Extend this to merge multiple constant Ops and update the mask.
37957 static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
37958                                            ArrayRef<int> Mask, SDValue Root,
37959                                            bool HasVariableMask,
37960                                            SelectionDAG &DAG,
37961                                            const X86Subtarget &Subtarget) {
37962   MVT VT = Root.getSimpleValueType();
37963 
37964   unsigned SizeInBits = VT.getSizeInBits();
37965   unsigned NumMaskElts = Mask.size();
37966   unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
37967   unsigned NumOps = Ops.size();
37968 
37969   // Extract constant bits from each source op.
37970   bool OneUseConstantOp = false;
37971   SmallVector<APInt, 16> UndefEltsOps(NumOps);
37972   SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
37973   for (unsigned i = 0; i != NumOps; ++i) {
37974     SDValue SrcOp = Ops[i];
37975     OneUseConstantOp |= SrcOp.hasOneUse();
37976     if (!getTargetConstantBitsFromNode(SrcOp, MaskSizeInBits, UndefEltsOps[i],
37977                                        RawBitsOps[i]))
37978       return SDValue();
37979   }
37980 
37981   // If we're optimizing for size, only fold if at least one of the constants is
37982   // only used once or the combined shuffle has included a variable mask
37983   // shuffle, this is to avoid constant pool bloat.
37984   bool IsOptimizingSize = DAG.shouldOptForSize();
37985   if (IsOptimizingSize && !OneUseConstantOp && !HasVariableMask)
37986     return SDValue();
37987 
37988   // Shuffle the constant bits according to the mask.
37989   SDLoc DL(Root);
37990   APInt UndefElts(NumMaskElts, 0);
37991   APInt ZeroElts(NumMaskElts, 0);
37992   APInt ConstantElts(NumMaskElts, 0);
37993   SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
37994                                         APInt::getZero(MaskSizeInBits));
37995   for (unsigned i = 0; i != NumMaskElts; ++i) {
37996     int M = Mask[i];
37997     if (M == SM_SentinelUndef) {
37998       UndefElts.setBit(i);
37999       continue;
38000     } else if (M == SM_SentinelZero) {
38001       ZeroElts.setBit(i);
38002       continue;
38003     }
38004     assert(0 <= M && M < (int)(NumMaskElts * NumOps));
38005 
38006     unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
38007     unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
38008 
38009     auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
38010     if (SrcUndefElts[SrcMaskIdx]) {
38011       UndefElts.setBit(i);
38012       continue;
38013     }
38014 
38015     auto &SrcEltBits = RawBitsOps[SrcOpIdx];
38016     APInt &Bits = SrcEltBits[SrcMaskIdx];
38017     if (!Bits) {
38018       ZeroElts.setBit(i);
38019       continue;
38020     }
38021 
38022     ConstantElts.setBit(i);
38023     ConstantBitData[i] = Bits;
38024   }
38025   assert((UndefElts | ZeroElts | ConstantElts).isAllOnes());
38026 
38027   // Attempt to create a zero vector.
38028   if ((UndefElts | ZeroElts).isAllOnes())
38029     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG, DL);
38030 
38031   // Create the constant data.
38032   MVT MaskSVT;
38033   if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
38034     MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
38035   else
38036     MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
38037 
38038   MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
38039   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
38040     return SDValue();
38041 
38042   SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
38043   return DAG.getBitcast(VT, CstOp);
38044 }
38045 
38046 namespace llvm {
38047   namespace X86 {
38048     enum {
38049       MaxShuffleCombineDepth = 8
38050     };
38051   }
38052 } // namespace llvm
38053 
38054 /// Fully generic combining of x86 shuffle instructions.
38055 ///
38056 /// This should be the last combine run over the x86 shuffle instructions. Once
38057 /// they have been fully optimized, this will recursively consider all chains
38058 /// of single-use shuffle instructions, build a generic model of the cumulative
38059 /// shuffle operation, and check for simpler instructions which implement this
38060 /// operation. We use this primarily for two purposes:
38061 ///
38062 /// 1) Collapse generic shuffles to specialized single instructions when
38063 ///    equivalent. In most cases, this is just an encoding size win, but
38064 ///    sometimes we will collapse multiple generic shuffles into a single
38065 ///    special-purpose shuffle.
38066 /// 2) Look for sequences of shuffle instructions with 3 or more total
38067 ///    instructions, and replace them with the slightly more expensive SSSE3
38068 ///    PSHUFB instruction if available. We do this as the last combining step
38069 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
38070 ///    a suitable short sequence of other instructions. The PSHUFB will either
38071 ///    use a register or have to read from memory and so is slightly (but only
38072 ///    slightly) more expensive than the other shuffle instructions.
38073 ///
38074 /// Because this is inherently a quadratic operation (for each shuffle in
38075 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
38076 /// This should never be an issue in practice as the shuffle lowering doesn't
38077 /// produce sequences of more than 8 instructions.
38078 ///
38079 /// FIXME: We will currently miss some cases where the redundant shuffling
38080 /// would simplify under the threshold for PSHUFB formation because of
38081 /// combine-ordering. To fix this, we should do the redundant instruction
38082 /// combining in this recursive walk.
38083 static SDValue combineX86ShufflesRecursively(
38084     ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
38085     ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
38086     unsigned MaxDepth, bool HasVariableMask, bool AllowVariableCrossLaneMask,
38087     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
38088     const X86Subtarget &Subtarget) {
38089   assert(RootMask.size() > 0 &&
38090          (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&
38091          "Illegal shuffle root mask");
38092   assert(Root.getSimpleValueType().isVector() &&
38093          "Shuffles operate on vector types!");
38094   unsigned RootSizeInBits = Root.getSimpleValueType().getSizeInBits();
38095 
38096   // Bound the depth of our recursive combine because this is ultimately
38097   // quadratic in nature.
38098   if (Depth >= MaxDepth)
38099     return SDValue();
38100 
38101   // Directly rip through bitcasts to find the underlying operand.
38102   SDValue Op = SrcOps[SrcOpIndex];
38103   Op = peekThroughOneUseBitcasts(Op);
38104 
38105   EVT VT = Op.getValueType();
38106   if (!VT.isVector() || !VT.isSimple())
38107     return SDValue(); // Bail if we hit a non-simple non-vector.
38108 
38109   // FIXME: Just bail on f16 for now.
38110   if (VT.getVectorElementType() == MVT::f16)
38111     return SDValue();
38112 
38113   assert((RootSizeInBits % VT.getSizeInBits()) == 0 &&
38114          "Can only combine shuffles upto size of the root op.");
38115 
38116   // Extract target shuffle mask and resolve sentinels and inputs.
38117   // TODO - determine Op's demanded elts from RootMask.
38118   SmallVector<int, 64> OpMask;
38119   SmallVector<SDValue, 2> OpInputs;
38120   APInt OpUndef, OpZero;
38121   APInt OpDemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
38122   bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
38123   if (!getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
38124                               OpZero, DAG, Depth, false))
38125     return SDValue();
38126 
38127   // Shuffle inputs must not be larger than the shuffle result.
38128   // TODO: Relax this for single input faux shuffles (trunc/extract_subvector).
38129   if (llvm::any_of(OpInputs, [VT](SDValue OpInput) {
38130         return OpInput.getValueSizeInBits() > VT.getSizeInBits();
38131       }))
38132     return SDValue();
38133 
38134   // If the shuffle result was smaller than the root, we need to adjust the
38135   // mask indices and pad the mask with undefs.
38136   if (RootSizeInBits > VT.getSizeInBits()) {
38137     unsigned NumSubVecs = RootSizeInBits / VT.getSizeInBits();
38138     unsigned OpMaskSize = OpMask.size();
38139     if (OpInputs.size() > 1) {
38140       unsigned PaddedMaskSize = NumSubVecs * OpMaskSize;
38141       for (int &M : OpMask) {
38142         if (M < 0)
38143           continue;
38144         int EltIdx = M % OpMaskSize;
38145         int OpIdx = M / OpMaskSize;
38146         M = (PaddedMaskSize * OpIdx) + EltIdx;
38147       }
38148     }
38149     OpZero = OpZero.zext(NumSubVecs * OpMaskSize);
38150     OpUndef = OpUndef.zext(NumSubVecs * OpMaskSize);
38151     OpMask.append((NumSubVecs - 1) * OpMaskSize, SM_SentinelUndef);
38152   }
38153 
38154   SmallVector<int, 64> Mask;
38155   SmallVector<SDValue, 16> Ops;
38156 
38157   // We don't need to merge masks if the root is empty.
38158   bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
38159   if (EmptyRoot) {
38160     // Only resolve zeros if it will remove an input, otherwise we might end
38161     // up in an infinite loop.
38162     bool ResolveKnownZeros = true;
38163     if (!OpZero.isZero()) {
38164       APInt UsedInputs = APInt::getZero(OpInputs.size());
38165       for (int i = 0, e = OpMask.size(); i != e; ++i) {
38166         int M = OpMask[i];
38167         if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
38168           continue;
38169         UsedInputs.setBit(M / OpMask.size());
38170         if (UsedInputs.isAllOnes()) {
38171           ResolveKnownZeros = false;
38172           break;
38173         }
38174       }
38175     }
38176     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
38177                                       ResolveKnownZeros);
38178 
38179     Mask = OpMask;
38180     Ops.append(OpInputs.begin(), OpInputs.end());
38181   } else {
38182     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
38183 
38184     // Add the inputs to the Ops list, avoiding duplicates.
38185     Ops.append(SrcOps.begin(), SrcOps.end());
38186 
38187     auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
38188       // Attempt to find an existing match.
38189       SDValue InputBC = peekThroughBitcasts(Input);
38190       for (int i = 0, e = Ops.size(); i < e; ++i)
38191         if (InputBC == peekThroughBitcasts(Ops[i]))
38192           return i;
38193       // Match failed - should we replace an existing Op?
38194       if (InsertionPoint >= 0) {
38195         Ops[InsertionPoint] = Input;
38196         return InsertionPoint;
38197       }
38198       // Add to the end of the Ops list.
38199       Ops.push_back(Input);
38200       return Ops.size() - 1;
38201     };
38202 
38203     SmallVector<int, 2> OpInputIdx;
38204     for (SDValue OpInput : OpInputs)
38205       OpInputIdx.push_back(
38206           AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
38207 
38208     assert(((RootMask.size() > OpMask.size() &&
38209              RootMask.size() % OpMask.size() == 0) ||
38210             (OpMask.size() > RootMask.size() &&
38211              OpMask.size() % RootMask.size() == 0) ||
38212             OpMask.size() == RootMask.size()) &&
38213            "The smaller number of elements must divide the larger.");
38214 
38215     // This function can be performance-critical, so we rely on the power-of-2
38216     // knowledge that we have about the mask sizes to replace div/rem ops with
38217     // bit-masks and shifts.
38218     assert(isPowerOf2_32(RootMask.size()) &&
38219            "Non-power-of-2 shuffle mask sizes");
38220     assert(isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes");
38221     unsigned RootMaskSizeLog2 = countTrailingZeros(RootMask.size());
38222     unsigned OpMaskSizeLog2 = countTrailingZeros(OpMask.size());
38223 
38224     unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
38225     unsigned RootRatio =
38226         std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
38227     unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
38228     assert((RootRatio == 1 || OpRatio == 1) &&
38229            "Must not have a ratio for both incoming and op masks!");
38230 
38231     assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
38232     assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
38233     assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
38234     unsigned RootRatioLog2 = countTrailingZeros(RootRatio);
38235     unsigned OpRatioLog2 = countTrailingZeros(OpRatio);
38236 
38237     Mask.resize(MaskWidth, SM_SentinelUndef);
38238 
38239     // Merge this shuffle operation's mask into our accumulated mask. Note that
38240     // this shuffle's mask will be the first applied to the input, followed by
38241     // the root mask to get us all the way to the root value arrangement. The
38242     // reason for this order is that we are recursing up the operation chain.
38243     for (unsigned i = 0; i < MaskWidth; ++i) {
38244       unsigned RootIdx = i >> RootRatioLog2;
38245       if (RootMask[RootIdx] < 0) {
38246         // This is a zero or undef lane, we're done.
38247         Mask[i] = RootMask[RootIdx];
38248         continue;
38249       }
38250 
38251       unsigned RootMaskedIdx =
38252           RootRatio == 1
38253               ? RootMask[RootIdx]
38254               : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
38255 
38256       // Just insert the scaled root mask value if it references an input other
38257       // than the SrcOp we're currently inserting.
38258       if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
38259           (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
38260         Mask[i] = RootMaskedIdx;
38261         continue;
38262       }
38263 
38264       RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
38265       unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
38266       if (OpMask[OpIdx] < 0) {
38267         // The incoming lanes are zero or undef, it doesn't matter which ones we
38268         // are using.
38269         Mask[i] = OpMask[OpIdx];
38270         continue;
38271       }
38272 
38273       // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
38274       unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
38275                                           : (OpMask[OpIdx] << OpRatioLog2) +
38276                                                 (RootMaskedIdx & (OpRatio - 1));
38277 
38278       OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
38279       int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
38280       assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input");
38281       OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
38282 
38283       Mask[i] = OpMaskedIdx;
38284     }
38285   }
38286 
38287   // Remove unused/repeated shuffle source ops.
38288   resolveTargetShuffleInputsAndMask(Ops, Mask);
38289 
38290   // Handle the all undef/zero/ones cases early.
38291   if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
38292     return DAG.getUNDEF(Root.getValueType());
38293   if (all_of(Mask, [](int Idx) { return Idx < 0; }))
38294     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG,
38295                          SDLoc(Root));
38296   if (Ops.size() == 1 && ISD::isBuildVectorAllOnes(Ops[0].getNode()) &&
38297       none_of(Mask, [](int M) { return M == SM_SentinelZero; }))
38298     return getOnesVector(Root.getValueType(), DAG, SDLoc(Root));
38299 
38300   assert(!Ops.empty() && "Shuffle with no inputs detected");
38301   HasVariableMask |= IsOpVariableMask;
38302 
38303   // Update the list of shuffle nodes that have been combined so far.
38304   SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
38305                                                 SrcNodes.end());
38306   CombinedNodes.push_back(Op.getNode());
38307 
38308   // See if we can recurse into each shuffle source op (if it's a target
38309   // shuffle). The source op should only be generally combined if it either has
38310   // a single use (i.e. current Op) or all its users have already been combined,
38311   // if not then we can still combine but should prevent generation of variable
38312   // shuffles to avoid constant pool bloat.
38313   // Don't recurse if we already have more source ops than we can combine in
38314   // the remaining recursion depth.
38315   if (Ops.size() < (MaxDepth - Depth)) {
38316     for (int i = 0, e = Ops.size(); i < e; ++i) {
38317       // For empty roots, we need to resolve zeroable elements before combining
38318       // them with other shuffles.
38319       SmallVector<int, 64> ResolvedMask = Mask;
38320       if (EmptyRoot)
38321         resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
38322       bool AllowCrossLaneVar = false;
38323       bool AllowPerLaneVar = false;
38324       if (Ops[i].getNode()->hasOneUse() ||
38325           SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode())) {
38326         AllowCrossLaneVar = AllowVariableCrossLaneMask;
38327         AllowPerLaneVar = AllowVariablePerLaneMask;
38328       }
38329       if (SDValue Res = combineX86ShufflesRecursively(
38330               Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1, MaxDepth,
38331               HasVariableMask, AllowCrossLaneVar, AllowPerLaneVar, DAG,
38332               Subtarget))
38333         return Res;
38334     }
38335   }
38336 
38337   // Attempt to constant fold all of the constant source ops.
38338   if (SDValue Cst = combineX86ShufflesConstants(
38339           Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
38340     return Cst;
38341 
38342   // If constant fold failed and we only have constants - then we have
38343   // multiple uses by a single non-variable shuffle - just bail.
38344   if (Depth == 0 && llvm::all_of(Ops, [&](SDValue Op) {
38345         APInt UndefElts;
38346         SmallVector<APInt> RawBits;
38347         unsigned EltSizeInBits = RootSizeInBits / Mask.size();
38348         return getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
38349                                              RawBits);
38350       })) {
38351     return SDValue();
38352   }
38353 
38354   // Canonicalize the combined shuffle mask chain with horizontal ops.
38355   // NOTE: This will update the Ops and Mask.
38356   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
38357           Ops, Mask, RootSizeInBits, SDLoc(Root), DAG, Subtarget))
38358     return DAG.getBitcast(Root.getValueType(), HOp);
38359 
38360   // Try to refine our inputs given our knowledge of target shuffle mask.
38361   for (auto I : enumerate(Ops)) {
38362     int OpIdx = I.index();
38363     SDValue &Op = I.value();
38364 
38365     // What range of shuffle mask element values results in picking from Op?
38366     int Lo = OpIdx * Mask.size();
38367     int Hi = Lo + Mask.size();
38368 
38369     // Which elements of Op do we demand, given the mask's granularity?
38370     APInt OpDemandedElts(Mask.size(), 0);
38371     for (int MaskElt : Mask) {
38372       if (isInRange(MaskElt, Lo, Hi)) { // Picks from Op?
38373         int OpEltIdx = MaskElt - Lo;
38374         OpDemandedElts.setBit(OpEltIdx);
38375       }
38376     }
38377 
38378     // Is the shuffle result smaller than the root?
38379     if (Op.getValueSizeInBits() < RootSizeInBits) {
38380       // We padded the mask with undefs. But we now need to undo that.
38381       unsigned NumExpectedVectorElts = Mask.size();
38382       unsigned EltSizeInBits = RootSizeInBits / NumExpectedVectorElts;
38383       unsigned NumOpVectorElts = Op.getValueSizeInBits() / EltSizeInBits;
38384       assert(!OpDemandedElts.extractBits(
38385                  NumExpectedVectorElts - NumOpVectorElts, NumOpVectorElts) &&
38386              "Demanding the virtual undef widening padding?");
38387       OpDemandedElts = OpDemandedElts.trunc(NumOpVectorElts); // NUW
38388     }
38389 
38390     // The Op itself may be of different VT, so we need to scale the mask.
38391     unsigned NumOpElts = Op.getValueType().getVectorNumElements();
38392     APInt OpScaledDemandedElts = APIntOps::ScaleBitMask(OpDemandedElts, NumOpElts);
38393 
38394     // Can this operand be simplified any further, given it's demanded elements?
38395     if (SDValue NewOp =
38396             DAG.getTargetLoweringInfo().SimplifyMultipleUseDemandedVectorElts(
38397                 Op, OpScaledDemandedElts, DAG))
38398       Op = NewOp;
38399   }
38400   // FIXME: should we rerun resolveTargetShuffleInputsAndMask() now?
38401 
38402   // Widen any subvector shuffle inputs we've collected.
38403   if (any_of(Ops, [RootSizeInBits](SDValue Op) {
38404         return Op.getValueSizeInBits() < RootSizeInBits;
38405       })) {
38406     for (SDValue &Op : Ops)
38407       if (Op.getValueSizeInBits() < RootSizeInBits)
38408         Op = widenSubVector(Op, false, Subtarget, DAG, SDLoc(Op),
38409                             RootSizeInBits);
38410     // Reresolve - we might have repeated subvector sources.
38411     resolveTargetShuffleInputsAndMask(Ops, Mask);
38412   }
38413 
38414   // We can only combine unary and binary shuffle mask cases.
38415   if (Ops.size() <= 2) {
38416     // Minor canonicalization of the accumulated shuffle mask to make it easier
38417     // to match below. All this does is detect masks with sequential pairs of
38418     // elements, and shrink them to the half-width mask. It does this in a loop
38419     // so it will reduce the size of the mask to the minimal width mask which
38420     // performs an equivalent shuffle.
38421     while (Mask.size() > 1) {
38422       SmallVector<int, 64> WidenedMask;
38423       if (!canWidenShuffleElements(Mask, WidenedMask))
38424         break;
38425       Mask = std::move(WidenedMask);
38426     }
38427 
38428     // Canonicalization of binary shuffle masks to improve pattern matching by
38429     // commuting the inputs.
38430     if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
38431       ShuffleVectorSDNode::commuteMask(Mask);
38432       std::swap(Ops[0], Ops[1]);
38433     }
38434 
38435     // Finally, try to combine into a single shuffle instruction.
38436     return combineX86ShuffleChain(Ops, Root, Mask, Depth, HasVariableMask,
38437                                   AllowVariableCrossLaneMask,
38438                                   AllowVariablePerLaneMask, DAG, Subtarget);
38439   }
38440 
38441   // If that failed and any input is extracted then try to combine as a
38442   // shuffle with the larger type.
38443   return combineX86ShuffleChainWithExtract(
38444       Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
38445       AllowVariablePerLaneMask, DAG, Subtarget);
38446 }
38447 
38448 /// Helper entry wrapper to combineX86ShufflesRecursively.
38449 static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
38450                                              const X86Subtarget &Subtarget) {
38451   return combineX86ShufflesRecursively(
38452       {Op}, 0, Op, {0}, {}, /*Depth*/ 0, X86::MaxShuffleCombineDepth,
38453       /*HasVarMask*/ false,
38454       /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, DAG,
38455       Subtarget);
38456 }
38457 
38458 /// Get the PSHUF-style mask from PSHUF node.
38459 ///
38460 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
38461 /// PSHUF-style masks that can be reused with such instructions.
38462 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
38463   MVT VT = N.getSimpleValueType();
38464   SmallVector<int, 4> Mask;
38465   SmallVector<SDValue, 2> Ops;
38466   bool HaveMask =
38467       getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask);
38468   (void)HaveMask;
38469   assert(HaveMask);
38470 
38471   // If we have more than 128-bits, only the low 128-bits of shuffle mask
38472   // matter. Check that the upper masks are repeats and remove them.
38473   if (VT.getSizeInBits() > 128) {
38474     int LaneElts = 128 / VT.getScalarSizeInBits();
38475 #ifndef NDEBUG
38476     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
38477       for (int j = 0; j < LaneElts; ++j)
38478         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
38479                "Mask doesn't repeat in high 128-bit lanes!");
38480 #endif
38481     Mask.resize(LaneElts);
38482   }
38483 
38484   switch (N.getOpcode()) {
38485   case X86ISD::PSHUFD:
38486     return Mask;
38487   case X86ISD::PSHUFLW:
38488     Mask.resize(4);
38489     return Mask;
38490   case X86ISD::PSHUFHW:
38491     Mask.erase(Mask.begin(), Mask.begin() + 4);
38492     for (int &M : Mask)
38493       M -= 4;
38494     return Mask;
38495   default:
38496     llvm_unreachable("No valid shuffle instruction found!");
38497   }
38498 }
38499 
38500 /// Search for a combinable shuffle across a chain ending in pshufd.
38501 ///
38502 /// We walk up the chain and look for a combinable shuffle, skipping over
38503 /// shuffles that we could hoist this shuffle's transformation past without
38504 /// altering anything.
38505 static SDValue
38506 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
38507                              SelectionDAG &DAG) {
38508   assert(N.getOpcode() == X86ISD::PSHUFD &&
38509          "Called with something other than an x86 128-bit half shuffle!");
38510   SDLoc DL(N);
38511 
38512   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
38513   // of the shuffles in the chain so that we can form a fresh chain to replace
38514   // this one.
38515   SmallVector<SDValue, 8> Chain;
38516   SDValue V = N.getOperand(0);
38517   for (; V.hasOneUse(); V = V.getOperand(0)) {
38518     switch (V.getOpcode()) {
38519     default:
38520       return SDValue(); // Nothing combined!
38521 
38522     case ISD::BITCAST:
38523       // Skip bitcasts as we always know the type for the target specific
38524       // instructions.
38525       continue;
38526 
38527     case X86ISD::PSHUFD:
38528       // Found another dword shuffle.
38529       break;
38530 
38531     case X86ISD::PSHUFLW:
38532       // Check that the low words (being shuffled) are the identity in the
38533       // dword shuffle, and the high words are self-contained.
38534       if (Mask[0] != 0 || Mask[1] != 1 ||
38535           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
38536         return SDValue();
38537 
38538       Chain.push_back(V);
38539       continue;
38540 
38541     case X86ISD::PSHUFHW:
38542       // Check that the high words (being shuffled) are the identity in the
38543       // dword shuffle, and the low words are self-contained.
38544       if (Mask[2] != 2 || Mask[3] != 3 ||
38545           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
38546         return SDValue();
38547 
38548       Chain.push_back(V);
38549       continue;
38550 
38551     case X86ISD::UNPCKL:
38552     case X86ISD::UNPCKH:
38553       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
38554       // shuffle into a preceding word shuffle.
38555       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
38556           V.getSimpleValueType().getVectorElementType() != MVT::i16)
38557         return SDValue();
38558 
38559       // Search for a half-shuffle which we can combine with.
38560       unsigned CombineOp =
38561           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
38562       if (V.getOperand(0) != V.getOperand(1) ||
38563           !V->isOnlyUserOf(V.getOperand(0).getNode()))
38564         return SDValue();
38565       Chain.push_back(V);
38566       V = V.getOperand(0);
38567       do {
38568         switch (V.getOpcode()) {
38569         default:
38570           return SDValue(); // Nothing to combine.
38571 
38572         case X86ISD::PSHUFLW:
38573         case X86ISD::PSHUFHW:
38574           if (V.getOpcode() == CombineOp)
38575             break;
38576 
38577           Chain.push_back(V);
38578 
38579           LLVM_FALLTHROUGH;
38580         case ISD::BITCAST:
38581           V = V.getOperand(0);
38582           continue;
38583         }
38584         break;
38585       } while (V.hasOneUse());
38586       break;
38587     }
38588     // Break out of the loop if we break out of the switch.
38589     break;
38590   }
38591 
38592   if (!V.hasOneUse())
38593     // We fell out of the loop without finding a viable combining instruction.
38594     return SDValue();
38595 
38596   // Merge this node's mask and our incoming mask.
38597   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
38598   for (int &M : Mask)
38599     M = VMask[M];
38600   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
38601                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
38602 
38603   // Rebuild the chain around this new shuffle.
38604   while (!Chain.empty()) {
38605     SDValue W = Chain.pop_back_val();
38606 
38607     if (V.getValueType() != W.getOperand(0).getValueType())
38608       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
38609 
38610     switch (W.getOpcode()) {
38611     default:
38612       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
38613 
38614     case X86ISD::UNPCKL:
38615     case X86ISD::UNPCKH:
38616       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
38617       break;
38618 
38619     case X86ISD::PSHUFD:
38620     case X86ISD::PSHUFLW:
38621     case X86ISD::PSHUFHW:
38622       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
38623       break;
38624     }
38625   }
38626   if (V.getValueType() != N.getValueType())
38627     V = DAG.getBitcast(N.getValueType(), V);
38628 
38629   // Return the new chain to replace N.
38630   return V;
38631 }
38632 
38633 // Attempt to commute shufps LHS loads:
38634 // permilps(shufps(load(),x)) --> permilps(shufps(x,load()))
38635 static SDValue combineCommutableSHUFP(SDValue N, MVT VT, const SDLoc &DL,
38636                                       SelectionDAG &DAG) {
38637   // TODO: Add vXf64 support.
38638   if (VT != MVT::v4f32 && VT != MVT::v8f32 && VT != MVT::v16f32)
38639     return SDValue();
38640 
38641   // SHUFP(LHS, RHS) -> SHUFP(RHS, LHS) iff LHS is foldable + RHS is not.
38642   auto commuteSHUFP = [&VT, &DL, &DAG](SDValue Parent, SDValue V) {
38643     if (V.getOpcode() != X86ISD::SHUFP || !Parent->isOnlyUserOf(V.getNode()))
38644       return SDValue();
38645     SDValue N0 = V.getOperand(0);
38646     SDValue N1 = V.getOperand(1);
38647     unsigned Imm = V.getConstantOperandVal(2);
38648     const X86Subtarget &Subtarget =
38649         static_cast<const X86Subtarget &>(DAG.getSubtarget());
38650     if (!X86::mayFoldLoad(peekThroughOneUseBitcasts(N0), Subtarget) ||
38651         X86::mayFoldLoad(peekThroughOneUseBitcasts(N1), Subtarget))
38652       return SDValue();
38653     Imm = ((Imm & 0x0F) << 4) | ((Imm & 0xF0) >> 4);
38654     return DAG.getNode(X86ISD::SHUFP, DL, VT, N1, N0,
38655                        DAG.getTargetConstant(Imm, DL, MVT::i8));
38656   };
38657 
38658   switch (N.getOpcode()) {
38659   case X86ISD::VPERMILPI:
38660     if (SDValue NewSHUFP = commuteSHUFP(N, N.getOperand(0))) {
38661       unsigned Imm = N.getConstantOperandVal(1);
38662       return DAG.getNode(X86ISD::VPERMILPI, DL, VT, NewSHUFP,
38663                          DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
38664     }
38665     break;
38666   case X86ISD::SHUFP: {
38667     SDValue N0 = N.getOperand(0);
38668     SDValue N1 = N.getOperand(1);
38669     unsigned Imm = N.getConstantOperandVal(2);
38670     if (N0 == N1) {
38671       if (SDValue NewSHUFP = commuteSHUFP(N, N0))
38672         return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, NewSHUFP,
38673                            DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
38674     } else if (SDValue NewSHUFP = commuteSHUFP(N, N0)) {
38675       return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, N1,
38676                          DAG.getTargetConstant(Imm ^ 0x0A, DL, MVT::i8));
38677     } else if (SDValue NewSHUFP = commuteSHUFP(N, N1)) {
38678       return DAG.getNode(X86ISD::SHUFP, DL, VT, N0, NewSHUFP,
38679                          DAG.getTargetConstant(Imm ^ 0xA0, DL, MVT::i8));
38680     }
38681     break;
38682   }
38683   }
38684 
38685   return SDValue();
38686 }
38687 
38688 // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
38689 static SDValue canonicalizeShuffleWithBinOps(SDValue N, SelectionDAG &DAG,
38690                                              const SDLoc &DL) {
38691   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38692   EVT ShuffleVT = N.getValueType();
38693 
38694   auto IsMergeableWithShuffle = [](SDValue Op) {
38695     // AllZeros/AllOnes constants are freely shuffled and will peek through
38696     // bitcasts. Other constant build vectors do not peek through bitcasts. Only
38697     // merge with target shuffles if it has one use so shuffle combining is
38698     // likely to kick in.
38699     return ISD::isBuildVectorAllOnes(Op.getNode()) ||
38700            ISD::isBuildVectorAllZeros(Op.getNode()) ||
38701            ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
38702            ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()) ||
38703            (isTargetShuffle(Op.getOpcode()) && Op->hasOneUse());
38704   };
38705   auto IsSafeToMoveShuffle = [ShuffleVT](SDValue Op, unsigned BinOp) {
38706     // Ensure we only shuffle whole vector src elements, unless its a logical
38707     // binops where we can more aggressively move shuffles from dst to src.
38708     return BinOp == ISD::AND || BinOp == ISD::OR || BinOp == ISD::XOR ||
38709            (Op.getScalarValueSizeInBits() <= ShuffleVT.getScalarSizeInBits());
38710   };
38711 
38712   unsigned Opc = N.getOpcode();
38713   switch (Opc) {
38714   // Unary and Unary+Permute Shuffles.
38715   case X86ISD::PSHUFB: {
38716     // Don't merge PSHUFB if it contains zero'd elements.
38717     SmallVector<int> Mask;
38718     SmallVector<SDValue> Ops;
38719     if (!getTargetShuffleMask(N.getNode(), ShuffleVT.getSimpleVT(), false, Ops,
38720                               Mask))
38721       break;
38722     LLVM_FALLTHROUGH;
38723   }
38724   case X86ISD::VBROADCAST:
38725   case X86ISD::MOVDDUP:
38726   case X86ISD::PSHUFD:
38727   case X86ISD::VPERMI:
38728   case X86ISD::VPERMILPI: {
38729     if (N.getOperand(0).getValueType() == ShuffleVT &&
38730         N->isOnlyUserOf(N.getOperand(0).getNode())) {
38731       SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
38732       unsigned SrcOpcode = N0.getOpcode();
38733       if (TLI.isBinOp(SrcOpcode) && IsSafeToMoveShuffle(N0, SrcOpcode)) {
38734         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
38735         SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
38736         if (IsMergeableWithShuffle(Op00) || IsMergeableWithShuffle(Op01)) {
38737           SDValue LHS, RHS;
38738           Op00 = DAG.getBitcast(ShuffleVT, Op00);
38739           Op01 = DAG.getBitcast(ShuffleVT, Op01);
38740           if (N.getNumOperands() == 2) {
38741             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, N.getOperand(1));
38742             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, N.getOperand(1));
38743           } else {
38744             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00);
38745             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01);
38746           }
38747           EVT OpVT = N0.getValueType();
38748           return DAG.getBitcast(ShuffleVT,
38749                                 DAG.getNode(SrcOpcode, DL, OpVT,
38750                                             DAG.getBitcast(OpVT, LHS),
38751                                             DAG.getBitcast(OpVT, RHS)));
38752         }
38753       }
38754     }
38755     break;
38756   }
38757   // Binary and Binary+Permute Shuffles.
38758   case X86ISD::INSERTPS: {
38759     // Don't merge INSERTPS if it contains zero'd elements.
38760     unsigned InsertPSMask = N.getConstantOperandVal(2);
38761     unsigned ZeroMask = InsertPSMask & 0xF;
38762     if (ZeroMask != 0)
38763       break;
38764     LLVM_FALLTHROUGH;
38765   }
38766   case X86ISD::MOVSD:
38767   case X86ISD::MOVSS:
38768   case X86ISD::BLENDI:
38769   case X86ISD::SHUFP:
38770   case X86ISD::UNPCKH:
38771   case X86ISD::UNPCKL: {
38772     if (N->isOnlyUserOf(N.getOperand(0).getNode()) &&
38773         N->isOnlyUserOf(N.getOperand(1).getNode())) {
38774       SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
38775       SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
38776       unsigned SrcOpcode = N0.getOpcode();
38777       if (TLI.isBinOp(SrcOpcode) && N1.getOpcode() == SrcOpcode &&
38778           IsSafeToMoveShuffle(N0, SrcOpcode) &&
38779           IsSafeToMoveShuffle(N1, SrcOpcode)) {
38780         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
38781         SDValue Op10 = peekThroughOneUseBitcasts(N1.getOperand(0));
38782         SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
38783         SDValue Op11 = peekThroughOneUseBitcasts(N1.getOperand(1));
38784         // Ensure the total number of shuffles doesn't increase by folding this
38785         // shuffle through to the source ops.
38786         if (((IsMergeableWithShuffle(Op00) && IsMergeableWithShuffle(Op10)) ||
38787              (IsMergeableWithShuffle(Op01) && IsMergeableWithShuffle(Op11))) ||
38788             ((IsMergeableWithShuffle(Op00) || IsMergeableWithShuffle(Op10)) &&
38789              (IsMergeableWithShuffle(Op01) || IsMergeableWithShuffle(Op11)))) {
38790           SDValue LHS, RHS;
38791           Op00 = DAG.getBitcast(ShuffleVT, Op00);
38792           Op10 = DAG.getBitcast(ShuffleVT, Op10);
38793           Op01 = DAG.getBitcast(ShuffleVT, Op01);
38794           Op11 = DAG.getBitcast(ShuffleVT, Op11);
38795           if (N.getNumOperands() == 3) {
38796             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10, N.getOperand(2));
38797             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11, N.getOperand(2));
38798           } else {
38799             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10);
38800             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11);
38801           }
38802           EVT OpVT = N0.getValueType();
38803           return DAG.getBitcast(ShuffleVT,
38804                                 DAG.getNode(SrcOpcode, DL, OpVT,
38805                                             DAG.getBitcast(OpVT, LHS),
38806                                             DAG.getBitcast(OpVT, RHS)));
38807         }
38808       }
38809     }
38810     break;
38811   }
38812   }
38813   return SDValue();
38814 }
38815 
38816 /// Attempt to fold vpermf128(op(),op()) -> op(vpermf128(),vpermf128()).
38817 static SDValue canonicalizeLaneShuffleWithRepeatedOps(SDValue V,
38818                                                       SelectionDAG &DAG,
38819                                                       const SDLoc &DL) {
38820   assert(V.getOpcode() == X86ISD::VPERM2X128 && "Unknown lane shuffle");
38821 
38822   MVT VT = V.getSimpleValueType();
38823   SDValue Src0 = peekThroughBitcasts(V.getOperand(0));
38824   SDValue Src1 = peekThroughBitcasts(V.getOperand(1));
38825   unsigned SrcOpc0 = Src0.getOpcode();
38826   unsigned SrcOpc1 = Src1.getOpcode();
38827   EVT SrcVT0 = Src0.getValueType();
38828   EVT SrcVT1 = Src1.getValueType();
38829 
38830   if (!Src1.isUndef() && (SrcVT0 != SrcVT1 || SrcOpc0 != SrcOpc1))
38831     return SDValue();
38832 
38833   switch (SrcOpc0) {
38834   case X86ISD::MOVDDUP: {
38835     SDValue LHS = Src0.getOperand(0);
38836     SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
38837     SDValue Res =
38838         DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS, V.getOperand(2));
38839     Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res);
38840     return DAG.getBitcast(VT, Res);
38841   }
38842   case X86ISD::VPERMILPI:
38843     // TODO: Handle v4f64 permutes with different low/high lane masks.
38844     if (SrcVT0 == MVT::v4f64) {
38845       uint64_t Mask = Src0.getConstantOperandVal(1);
38846       if ((Mask & 0x3) != ((Mask >> 2) & 0x3))
38847         break;
38848     }
38849     LLVM_FALLTHROUGH;
38850   case X86ISD::VSHLI:
38851   case X86ISD::VSRLI:
38852   case X86ISD::VSRAI:
38853   case X86ISD::PSHUFD:
38854     if (Src1.isUndef() || Src0.getOperand(1) == Src1.getOperand(1)) {
38855       SDValue LHS = Src0.getOperand(0);
38856       SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
38857       SDValue Res = DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS,
38858                                 V.getOperand(2));
38859       Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res, Src0.getOperand(1));
38860       return DAG.getBitcast(VT, Res);
38861     }
38862     break;
38863   }
38864 
38865   return SDValue();
38866 }
38867 
38868 /// Try to combine x86 target specific shuffles.
38869 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
38870                                     TargetLowering::DAGCombinerInfo &DCI,
38871                                     const X86Subtarget &Subtarget) {
38872   SDLoc DL(N);
38873   MVT VT = N.getSimpleValueType();
38874   SmallVector<int, 4> Mask;
38875   unsigned Opcode = N.getOpcode();
38876 
38877   if (SDValue R = combineCommutableSHUFP(N, VT, DL, DAG))
38878     return R;
38879 
38880   if (SDValue R = canonicalizeShuffleWithBinOps(N, DAG, DL))
38881     return R;
38882 
38883   // Handle specific target shuffles.
38884   switch (Opcode) {
38885   case X86ISD::MOVDDUP: {
38886     SDValue Src = N.getOperand(0);
38887     // Turn a 128-bit MOVDDUP of a full vector load into movddup+vzload.
38888     if (VT == MVT::v2f64 && Src.hasOneUse() &&
38889         ISD::isNormalLoad(Src.getNode())) {
38890       LoadSDNode *LN = cast<LoadSDNode>(Src);
38891       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::f64, MVT::v2f64, DAG)) {
38892         SDValue Movddup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, VZLoad);
38893         DCI.CombineTo(N.getNode(), Movddup);
38894         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
38895         DCI.recursivelyDeleteUnusedNodes(LN);
38896         return N; // Return N so it doesn't get rechecked!
38897       }
38898     }
38899 
38900     return SDValue();
38901   }
38902   case X86ISD::VBROADCAST: {
38903     SDValue Src = N.getOperand(0);
38904     SDValue BC = peekThroughBitcasts(Src);
38905     EVT SrcVT = Src.getValueType();
38906     EVT BCVT = BC.getValueType();
38907 
38908     // If broadcasting from another shuffle, attempt to simplify it.
38909     // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
38910     if (isTargetShuffle(BC.getOpcode()) &&
38911         VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
38912       unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
38913       SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
38914                                         SM_SentinelUndef);
38915       for (unsigned i = 0; i != Scale; ++i)
38916         DemandedMask[i] = i;
38917       if (SDValue Res = combineX86ShufflesRecursively(
38918               {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
38919               X86::MaxShuffleCombineDepth,
38920               /*HasVarMask*/ false, /*AllowCrossLaneVarMask*/ true,
38921               /*AllowPerLaneVarMask*/ true, DAG, Subtarget))
38922         return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
38923                            DAG.getBitcast(SrcVT, Res));
38924     }
38925 
38926     // broadcast(bitcast(src)) -> bitcast(broadcast(src))
38927     // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
38928     if (Src.getOpcode() == ISD::BITCAST &&
38929         SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits() &&
38930         DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
38931         FixedVectorType::isValidElementType(
38932             BCVT.getScalarType().getTypeForEVT(*DAG.getContext()))) {
38933       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
38934                                    VT.getVectorNumElements());
38935       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
38936     }
38937 
38938     // Reduce broadcast source vector to lowest 128-bits.
38939     if (SrcVT.getSizeInBits() > 128)
38940       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
38941                          extract128BitVector(Src, 0, DAG, DL));
38942 
38943     // broadcast(scalar_to_vector(x)) -> broadcast(x).
38944     if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR)
38945       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
38946 
38947     // broadcast(extract_vector_elt(x, 0)) -> broadcast(x).
38948     if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
38949         isNullConstant(Src.getOperand(1)) &&
38950         DAG.getTargetLoweringInfo().isTypeLegal(
38951             Src.getOperand(0).getValueType()))
38952       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
38953 
38954     // Share broadcast with the longest vector and extract low subvector (free).
38955     // Ensure the same SDValue from the SDNode use is being used.
38956     for (SDNode *User : Src->uses())
38957       if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
38958           Src == User->getOperand(0) &&
38959           User->getValueSizeInBits(0).getFixedSize() >
38960               VT.getFixedSizeInBits()) {
38961         return extractSubVector(SDValue(User, 0), 0, DAG, DL,
38962                                 VT.getSizeInBits());
38963       }
38964 
38965     // vbroadcast(scalarload X) -> vbroadcast_load X
38966     // For float loads, extract other uses of the scalar from the broadcast.
38967     if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
38968         ISD::isNormalLoad(Src.getNode())) {
38969       LoadSDNode *LN = cast<LoadSDNode>(Src);
38970       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
38971       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
38972       SDValue BcastLd =
38973           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
38974                                   LN->getMemoryVT(), LN->getMemOperand());
38975       // If the load value is used only by N, replace it via CombineTo N.
38976       bool NoReplaceExtract = Src.hasOneUse();
38977       DCI.CombineTo(N.getNode(), BcastLd);
38978       if (NoReplaceExtract) {
38979         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
38980         DCI.recursivelyDeleteUnusedNodes(LN);
38981       } else {
38982         SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
38983                                   DAG.getIntPtrConstant(0, DL));
38984         DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
38985       }
38986       return N; // Return N so it doesn't get rechecked!
38987     }
38988 
38989     // Due to isTypeDesirableForOp, we won't always shrink a load truncated to
38990     // i16. So shrink it ourselves if we can make a broadcast_load.
38991     if (SrcVT == MVT::i16 && Src.getOpcode() == ISD::TRUNCATE &&
38992         Src.hasOneUse() && Src.getOperand(0).hasOneUse()) {
38993       assert(Subtarget.hasAVX2() && "Expected AVX2");
38994       SDValue TruncIn = Src.getOperand(0);
38995 
38996       // If this is a truncate of a non extending load we can just narrow it to
38997       // use a broadcast_load.
38998       if (ISD::isNormalLoad(TruncIn.getNode())) {
38999         LoadSDNode *LN = cast<LoadSDNode>(TruncIn);
39000         // Unless its volatile or atomic.
39001         if (LN->isSimple()) {
39002           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39003           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
39004           SDValue BcastLd = DAG.getMemIntrinsicNode(
39005               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
39006               LN->getPointerInfo(), LN->getOriginalAlign(),
39007               LN->getMemOperand()->getFlags());
39008           DCI.CombineTo(N.getNode(), BcastLd);
39009           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39010           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
39011           return N; // Return N so it doesn't get rechecked!
39012         }
39013       }
39014 
39015       // If this is a truncate of an i16 extload, we can directly replace it.
39016       if (ISD::isUNINDEXEDLoad(Src.getOperand(0).getNode()) &&
39017           ISD::isEXTLoad(Src.getOperand(0).getNode())) {
39018         LoadSDNode *LN = cast<LoadSDNode>(Src.getOperand(0));
39019         if (LN->getMemoryVT().getSizeInBits() == 16) {
39020           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39021           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
39022           SDValue BcastLd =
39023               DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
39024                                       LN->getMemoryVT(), LN->getMemOperand());
39025           DCI.CombineTo(N.getNode(), BcastLd);
39026           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39027           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
39028           return N; // Return N so it doesn't get rechecked!
39029         }
39030       }
39031 
39032       // If this is a truncate of load that has been shifted right, we can
39033       // offset the pointer and use a narrower load.
39034       if (TruncIn.getOpcode() == ISD::SRL &&
39035           TruncIn.getOperand(0).hasOneUse() &&
39036           isa<ConstantSDNode>(TruncIn.getOperand(1)) &&
39037           ISD::isNormalLoad(TruncIn.getOperand(0).getNode())) {
39038         LoadSDNode *LN = cast<LoadSDNode>(TruncIn.getOperand(0));
39039         unsigned ShiftAmt = TruncIn.getConstantOperandVal(1);
39040         // Make sure the shift amount and the load size are divisible by 16.
39041         // Don't do this if the load is volatile or atomic.
39042         if (ShiftAmt % 16 == 0 && TruncIn.getValueSizeInBits() % 16 == 0 &&
39043             LN->isSimple()) {
39044           unsigned Offset = ShiftAmt / 8;
39045           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39046           SDValue Ptr = DAG.getMemBasePlusOffset(LN->getBasePtr(),
39047                                                  TypeSize::Fixed(Offset), DL);
39048           SDValue Ops[] = { LN->getChain(), Ptr };
39049           SDValue BcastLd = DAG.getMemIntrinsicNode(
39050               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
39051               LN->getPointerInfo().getWithOffset(Offset),
39052               LN->getOriginalAlign(),
39053               LN->getMemOperand()->getFlags());
39054           DCI.CombineTo(N.getNode(), BcastLd);
39055           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39056           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
39057           return N; // Return N so it doesn't get rechecked!
39058         }
39059       }
39060     }
39061 
39062     // vbroadcast(vzload X) -> vbroadcast_load X
39063     if (Src.getOpcode() == X86ISD::VZEXT_LOAD && Src.hasOneUse()) {
39064       MemSDNode *LN = cast<MemIntrinsicSDNode>(Src);
39065       if (LN->getMemoryVT().getSizeInBits() == VT.getScalarSizeInBits()) {
39066         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39067         SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
39068         SDValue BcastLd =
39069             DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
39070                                     LN->getMemoryVT(), LN->getMemOperand());
39071         DCI.CombineTo(N.getNode(), BcastLd);
39072         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39073         DCI.recursivelyDeleteUnusedNodes(LN);
39074         return N; // Return N so it doesn't get rechecked!
39075       }
39076     }
39077 
39078     // vbroadcast(vector load X) -> vbroadcast_load
39079     if ((SrcVT == MVT::v2f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v2i64 ||
39080          SrcVT == MVT::v4i32) &&
39081         Src.hasOneUse() && ISD::isNormalLoad(Src.getNode())) {
39082       LoadSDNode *LN = cast<LoadSDNode>(Src);
39083       // Unless the load is volatile or atomic.
39084       if (LN->isSimple()) {
39085         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39086         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
39087         SDValue BcastLd = DAG.getMemIntrinsicNode(
39088             X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SrcVT.getScalarType(),
39089             LN->getPointerInfo(), LN->getOriginalAlign(),
39090             LN->getMemOperand()->getFlags());
39091         DCI.CombineTo(N.getNode(), BcastLd);
39092         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39093         DCI.recursivelyDeleteUnusedNodes(LN);
39094         return N; // Return N so it doesn't get rechecked!
39095       }
39096     }
39097 
39098     return SDValue();
39099   }
39100   case X86ISD::VZEXT_MOVL: {
39101     SDValue N0 = N.getOperand(0);
39102 
39103     // If this a vzmovl of a full vector load, replace it with a vzload, unless
39104     // the load is volatile.
39105     if (N0.hasOneUse() && ISD::isNormalLoad(N0.getNode())) {
39106       auto *LN = cast<LoadSDNode>(N0);
39107       if (SDValue VZLoad =
39108               narrowLoadToVZLoad(LN, VT.getVectorElementType(), VT, DAG)) {
39109         DCI.CombineTo(N.getNode(), VZLoad);
39110         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
39111         DCI.recursivelyDeleteUnusedNodes(LN);
39112         return N;
39113       }
39114     }
39115 
39116     // If this a VZEXT_MOVL of a VBROADCAST_LOAD, we don't need the broadcast
39117     // and can just use a VZEXT_LOAD.
39118     // FIXME: Is there some way to do this with SimplifyDemandedVectorElts?
39119     if (N0.hasOneUse() && N0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
39120       auto *LN = cast<MemSDNode>(N0);
39121       if (VT.getScalarSizeInBits() == LN->getMemoryVT().getSizeInBits()) {
39122         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39123         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
39124         SDValue VZLoad =
39125             DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
39126                                     LN->getMemoryVT(), LN->getMemOperand());
39127         DCI.CombineTo(N.getNode(), VZLoad);
39128         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
39129         DCI.recursivelyDeleteUnusedNodes(LN);
39130         return N;
39131       }
39132     }
39133 
39134     // Turn (v2i64 (vzext_movl (scalar_to_vector (i64 X)))) into
39135     // (v2i64 (bitcast (v4i32 (vzext_movl (scalar_to_vector (i32 (trunc X)))))))
39136     // if the upper bits of the i64 are zero.
39137     if (N0.hasOneUse() && N0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
39138         N0.getOperand(0).hasOneUse() &&
39139         N0.getOperand(0).getValueType() == MVT::i64) {
39140       SDValue In = N0.getOperand(0);
39141       APInt Mask = APInt::getHighBitsSet(64, 32);
39142       if (DAG.MaskedValueIsZero(In, Mask)) {
39143         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, In);
39144         MVT VecVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
39145         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Trunc);
39146         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, SclVec);
39147         return DAG.getBitcast(VT, Movl);
39148       }
39149     }
39150 
39151     // Load a scalar integer constant directly to XMM instead of transferring an
39152     // immediate value from GPR.
39153     // vzext_movl (scalar_to_vector C) --> load [C,0...]
39154     if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR) {
39155       if (auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
39156         // Create a vector constant - scalar constant followed by zeros.
39157         EVT ScalarVT = N0.getOperand(0).getValueType();
39158         Type *ScalarTy = ScalarVT.getTypeForEVT(*DAG.getContext());
39159         unsigned NumElts = VT.getVectorNumElements();
39160         Constant *Zero = ConstantInt::getNullValue(ScalarTy);
39161         SmallVector<Constant *, 32> ConstantVec(NumElts, Zero);
39162         ConstantVec[0] = const_cast<ConstantInt *>(C->getConstantIntValue());
39163 
39164         // Load the vector constant from constant pool.
39165         MVT PVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
39166         SDValue CP = DAG.getConstantPool(ConstantVector::get(ConstantVec), PVT);
39167         MachinePointerInfo MPI =
39168             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
39169         Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
39170         return DAG.getLoad(VT, DL, DAG.getEntryNode(), CP, MPI, Alignment,
39171                            MachineMemOperand::MOLoad);
39172       }
39173     }
39174 
39175     // Pull subvector inserts into undef through VZEXT_MOVL by making it an
39176     // insert into a zero vector. This helps get VZEXT_MOVL closer to
39177     // scalar_to_vectors where 256/512 are canonicalized to an insert and a
39178     // 128-bit scalar_to_vector. This reduces the number of isel patterns.
39179     if (!DCI.isBeforeLegalizeOps() && N0.hasOneUse()) {
39180       SDValue V = peekThroughOneUseBitcasts(N0);
39181 
39182       if (V.getOpcode() == ISD::INSERT_SUBVECTOR && V.getOperand(0).isUndef() &&
39183           isNullConstant(V.getOperand(2))) {
39184         SDValue In = V.getOperand(1);
39185         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
39186                                      In.getValueSizeInBits() /
39187                                          VT.getScalarSizeInBits());
39188         In = DAG.getBitcast(SubVT, In);
39189         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, SubVT, In);
39190         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
39191                            getZeroVector(VT, Subtarget, DAG, DL), Movl,
39192                            V.getOperand(2));
39193       }
39194     }
39195 
39196     return SDValue();
39197   }
39198   case X86ISD::BLENDI: {
39199     SDValue N0 = N.getOperand(0);
39200     SDValue N1 = N.getOperand(1);
39201 
39202     // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
39203     // TODO: Handle MVT::v16i16 repeated blend mask.
39204     if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
39205         N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
39206       MVT SrcVT = N0.getOperand(0).getSimpleValueType();
39207       if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
39208           SrcVT.getScalarSizeInBits() >= 32) {
39209         unsigned BlendMask = N.getConstantOperandVal(2);
39210         unsigned Size = VT.getVectorNumElements();
39211         unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
39212         BlendMask = scaleVectorShuffleBlendMask(BlendMask, Size, Scale);
39213         return DAG.getBitcast(
39214             VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
39215                             N1.getOperand(0),
39216                             DAG.getTargetConstant(BlendMask, DL, MVT::i8)));
39217       }
39218     }
39219     return SDValue();
39220   }
39221   case X86ISD::SHUFP: {
39222     // Fold shufps(shuffle(x),shuffle(y)) -> shufps(x,y).
39223     // This is a more relaxed shuffle combiner that can ignore oneuse limits.
39224     // TODO: Support types other than v4f32.
39225     if (VT == MVT::v4f32) {
39226       bool Updated = false;
39227       SmallVector<int> Mask;
39228       SmallVector<SDValue> Ops;
39229       if (getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask) &&
39230           Ops.size() == 2) {
39231         for (int i = 0; i != 2; ++i) {
39232           SmallVector<SDValue> SubOps;
39233           SmallVector<int> SubMask, SubScaledMask;
39234           SDValue Sub = peekThroughBitcasts(Ops[i]);
39235           // TODO: Scaling might be easier if we specify the demanded elts.
39236           if (getTargetShuffleInputs(Sub, SubOps, SubMask, DAG, 0, false) &&
39237               scaleShuffleElements(SubMask, 4, SubScaledMask) &&
39238               SubOps.size() == 1 && isUndefOrInRange(SubScaledMask, 0, 4)) {
39239             int Ofs = i * 2;
39240             Mask[Ofs + 0] = SubScaledMask[Mask[Ofs + 0] % 4] + (i * 4);
39241             Mask[Ofs + 1] = SubScaledMask[Mask[Ofs + 1] % 4] + (i * 4);
39242             Ops[i] = DAG.getBitcast(VT, SubOps[0]);
39243             Updated = true;
39244           }
39245         }
39246       }
39247       if (Updated) {
39248         for (int &M : Mask)
39249           M %= 4;
39250         Ops.push_back(getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
39251         return DAG.getNode(X86ISD::SHUFP, DL, VT, Ops);
39252       }
39253     }
39254     return SDValue();
39255   }
39256   case X86ISD::VPERMI: {
39257     // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
39258     // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
39259     SDValue N0 = N.getOperand(0);
39260     SDValue N1 = N.getOperand(1);
39261     unsigned EltSizeInBits = VT.getScalarSizeInBits();
39262     if (N0.getOpcode() == ISD::BITCAST &&
39263         N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
39264       SDValue Src = N0.getOperand(0);
39265       EVT SrcVT = Src.getValueType();
39266       SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
39267       return DAG.getBitcast(VT, Res);
39268     }
39269     return SDValue();
39270   }
39271   case X86ISD::VPERM2X128: {
39272     // Fold vperm2x128(bitcast(x),bitcast(y),c) -> bitcast(vperm2x128(x,y,c)).
39273     SDValue LHS = N->getOperand(0);
39274     SDValue RHS = N->getOperand(1);
39275     if (LHS.getOpcode() == ISD::BITCAST &&
39276         (RHS.getOpcode() == ISD::BITCAST || RHS.isUndef())) {
39277       EVT SrcVT = LHS.getOperand(0).getValueType();
39278       if (RHS.isUndef() || SrcVT == RHS.getOperand(0).getValueType()) {
39279         return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT,
39280                                               DAG.getBitcast(SrcVT, LHS),
39281                                               DAG.getBitcast(SrcVT, RHS),
39282                                               N->getOperand(2)));
39283       }
39284     }
39285 
39286     // Fold vperm2x128(op(),op()) -> op(vperm2x128(),vperm2x128()).
39287     if (SDValue Res = canonicalizeLaneShuffleWithRepeatedOps(N, DAG, DL))
39288       return Res;
39289 
39290     // Fold vperm2x128 subvector shuffle with an inner concat pattern.
39291     // vperm2x128(concat(X,Y),concat(Z,W)) --> concat X,Y etc.
39292     auto FindSubVector128 = [&](unsigned Idx) {
39293       if (Idx > 3)
39294         return SDValue();
39295       SDValue Src = peekThroughBitcasts(N.getOperand(Idx < 2 ? 0 : 1));
39296       SmallVector<SDValue> SubOps;
39297       if (collectConcatOps(Src.getNode(), SubOps) && SubOps.size() == 2)
39298         return SubOps[Idx & 1];
39299       unsigned NumElts = Src.getValueType().getVectorNumElements();
39300       if ((Idx & 1) == 1 && Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
39301           Src.getOperand(1).getValueSizeInBits() == 128 &&
39302           Src.getConstantOperandAPInt(2) == (NumElts / 2)) {
39303         return Src.getOperand(1);
39304       }
39305       return SDValue();
39306     };
39307     unsigned Imm = N.getConstantOperandVal(2);
39308     if (SDValue SubLo = FindSubVector128(Imm & 0x0F)) {
39309       if (SDValue SubHi = FindSubVector128((Imm & 0xF0) >> 4)) {
39310         MVT SubVT = VT.getHalfNumVectorElementsVT();
39311         SubLo = DAG.getBitcast(SubVT, SubLo);
39312         SubHi = DAG.getBitcast(SubVT, SubHi);
39313         return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SubLo, SubHi);
39314       }
39315     }
39316     return SDValue();
39317   }
39318   case X86ISD::PSHUFD:
39319   case X86ISD::PSHUFLW:
39320   case X86ISD::PSHUFHW:
39321     Mask = getPSHUFShuffleMask(N);
39322     assert(Mask.size() == 4);
39323     break;
39324   case X86ISD::MOVSD:
39325   case X86ISD::MOVSH:
39326   case X86ISD::MOVSS: {
39327     SDValue N0 = N.getOperand(0);
39328     SDValue N1 = N.getOperand(1);
39329 
39330     // Canonicalize scalar FPOps:
39331     // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
39332     // If commutable, allow OP(N1[0], N0[0]).
39333     unsigned Opcode1 = N1.getOpcode();
39334     if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
39335         Opcode1 == ISD::FDIV) {
39336       SDValue N10 = N1.getOperand(0);
39337       SDValue N11 = N1.getOperand(1);
39338       if (N10 == N0 ||
39339           (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
39340         if (N10 != N0)
39341           std::swap(N10, N11);
39342         MVT SVT = VT.getVectorElementType();
39343         SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
39344         N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
39345         N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
39346         SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
39347         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
39348         return DAG.getNode(Opcode, DL, VT, N0, SclVec);
39349       }
39350     }
39351 
39352     return SDValue();
39353   }
39354   case X86ISD::INSERTPS: {
39355     assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
39356     SDValue Op0 = N.getOperand(0);
39357     SDValue Op1 = N.getOperand(1);
39358     unsigned InsertPSMask = N.getConstantOperandVal(2);
39359     unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
39360     unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
39361     unsigned ZeroMask = InsertPSMask & 0xF;
39362 
39363     // If we zero out all elements from Op0 then we don't need to reference it.
39364     if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
39365       return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
39366                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
39367 
39368     // If we zero out the element from Op1 then we don't need to reference it.
39369     if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
39370       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
39371                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
39372 
39373     // Attempt to merge insertps Op1 with an inner target shuffle node.
39374     SmallVector<int, 8> TargetMask1;
39375     SmallVector<SDValue, 2> Ops1;
39376     APInt KnownUndef1, KnownZero1;
39377     if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
39378                                      KnownZero1)) {
39379       if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
39380         // Zero/UNDEF insertion - zero out element and remove dependency.
39381         InsertPSMask |= (1u << DstIdx);
39382         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
39383                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
39384       }
39385       // Update insertps mask srcidx and reference the source input directly.
39386       int M = TargetMask1[SrcIdx];
39387       assert(0 <= M && M < 8 && "Shuffle index out of range");
39388       InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
39389       Op1 = Ops1[M < 4 ? 0 : 1];
39390       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
39391                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
39392     }
39393 
39394     // Attempt to merge insertps Op0 with an inner target shuffle node.
39395     SmallVector<int, 8> TargetMask0;
39396     SmallVector<SDValue, 2> Ops0;
39397     APInt KnownUndef0, KnownZero0;
39398     if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
39399                                      KnownZero0)) {
39400       bool Updated = false;
39401       bool UseInput00 = false;
39402       bool UseInput01 = false;
39403       for (int i = 0; i != 4; ++i) {
39404         if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
39405           // No change if element is already zero or the inserted element.
39406           continue;
39407         } else if (KnownUndef0[i] || KnownZero0[i]) {
39408           // If the target mask is undef/zero then we must zero the element.
39409           InsertPSMask |= (1u << i);
39410           Updated = true;
39411           continue;
39412         }
39413 
39414         // The input vector element must be inline.
39415         int M = TargetMask0[i];
39416         if (M != i && M != (i + 4))
39417           return SDValue();
39418 
39419         // Determine which inputs of the target shuffle we're using.
39420         UseInput00 |= (0 <= M && M < 4);
39421         UseInput01 |= (4 <= M);
39422       }
39423 
39424       // If we're not using both inputs of the target shuffle then use the
39425       // referenced input directly.
39426       if (UseInput00 && !UseInput01) {
39427         Updated = true;
39428         Op0 = Ops0[0];
39429       } else if (!UseInput00 && UseInput01) {
39430         Updated = true;
39431         Op0 = Ops0[1];
39432       }
39433 
39434       if (Updated)
39435         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
39436                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
39437     }
39438 
39439     // If we're inserting an element from a vbroadcast load, fold the
39440     // load into the X86insertps instruction. We need to convert the scalar
39441     // load to a vector and clear the source lane of the INSERTPS control.
39442     if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
39443       auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
39444       if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
39445         SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
39446                                    MemIntr->getBasePtr(),
39447                                    MemIntr->getMemOperand());
39448         SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
39449                            DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
39450                                        Load),
39451                            DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
39452         DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
39453         return Insert;
39454       }
39455     }
39456 
39457     return SDValue();
39458   }
39459   default:
39460     return SDValue();
39461   }
39462 
39463   // Nuke no-op shuffles that show up after combining.
39464   if (isNoopShuffleMask(Mask))
39465     return N.getOperand(0);
39466 
39467   // Look for simplifications involving one or two shuffle instructions.
39468   SDValue V = N.getOperand(0);
39469   switch (N.getOpcode()) {
39470   default:
39471     break;
39472   case X86ISD::PSHUFLW:
39473   case X86ISD::PSHUFHW:
39474     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
39475 
39476     // See if this reduces to a PSHUFD which is no more expensive and can
39477     // combine with more operations. Note that it has to at least flip the
39478     // dwords as otherwise it would have been removed as a no-op.
39479     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
39480       int DMask[] = {0, 1, 2, 3};
39481       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
39482       DMask[DOffset + 0] = DOffset + 1;
39483       DMask[DOffset + 1] = DOffset + 0;
39484       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
39485       V = DAG.getBitcast(DVT, V);
39486       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
39487                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
39488       return DAG.getBitcast(VT, V);
39489     }
39490 
39491     // Look for shuffle patterns which can be implemented as a single unpack.
39492     // FIXME: This doesn't handle the location of the PSHUFD generically, and
39493     // only works when we have a PSHUFD followed by two half-shuffles.
39494     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
39495         (V.getOpcode() == X86ISD::PSHUFLW ||
39496          V.getOpcode() == X86ISD::PSHUFHW) &&
39497         V.getOpcode() != N.getOpcode() &&
39498         V.hasOneUse() && V.getOperand(0).hasOneUse()) {
39499       SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
39500       if (D.getOpcode() == X86ISD::PSHUFD) {
39501         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
39502         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
39503         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
39504         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
39505         int WordMask[8];
39506         for (int i = 0; i < 4; ++i) {
39507           WordMask[i + NOffset] = Mask[i] + NOffset;
39508           WordMask[i + VOffset] = VMask[i] + VOffset;
39509         }
39510         // Map the word mask through the DWord mask.
39511         int MappedMask[8];
39512         for (int i = 0; i < 8; ++i)
39513           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
39514         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
39515             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
39516           // We can replace all three shuffles with an unpack.
39517           V = DAG.getBitcast(VT, D.getOperand(0));
39518           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
39519                                                 : X86ISD::UNPCKH,
39520                              DL, VT, V, V);
39521         }
39522       }
39523     }
39524 
39525     break;
39526 
39527   case X86ISD::PSHUFD:
39528     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
39529       return NewN;
39530 
39531     break;
39532   }
39533 
39534   return SDValue();
39535 }
39536 
39537 /// Checks if the shuffle mask takes subsequent elements
39538 /// alternately from two vectors.
39539 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
39540 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
39541 
39542   int ParitySrc[2] = {-1, -1};
39543   unsigned Size = Mask.size();
39544   for (unsigned i = 0; i != Size; ++i) {
39545     int M = Mask[i];
39546     if (M < 0)
39547       continue;
39548 
39549     // Make sure we are using the matching element from the input.
39550     if ((M % Size) != i)
39551       return false;
39552 
39553     // Make sure we use the same input for all elements of the same parity.
39554     int Src = M / Size;
39555     if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
39556       return false;
39557     ParitySrc[i % 2] = Src;
39558   }
39559 
39560   // Make sure each input is used.
39561   if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
39562     return false;
39563 
39564   Op0Even = ParitySrc[0] == 0;
39565   return true;
39566 }
39567 
39568 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
39569 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
39570 /// are written to the parameters \p Opnd0 and \p Opnd1.
39571 ///
39572 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
39573 /// so it is easier to generically match. We also insert dummy vector shuffle
39574 /// nodes for the operands which explicitly discard the lanes which are unused
39575 /// by this operation to try to flow through the rest of the combiner
39576 /// the fact that they're unused.
39577 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
39578                              SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
39579                              bool &IsSubAdd) {
39580 
39581   EVT VT = N->getValueType(0);
39582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39583   if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
39584       !VT.getSimpleVT().isFloatingPoint())
39585     return false;
39586 
39587   // We only handle target-independent shuffles.
39588   // FIXME: It would be easy and harmless to use the target shuffle mask
39589   // extraction tool to support more.
39590   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
39591     return false;
39592 
39593   SDValue V1 = N->getOperand(0);
39594   SDValue V2 = N->getOperand(1);
39595 
39596   // Make sure we have an FADD and an FSUB.
39597   if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
39598       (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
39599       V1.getOpcode() == V2.getOpcode())
39600     return false;
39601 
39602   // If there are other uses of these operations we can't fold them.
39603   if (!V1->hasOneUse() || !V2->hasOneUse())
39604     return false;
39605 
39606   // Ensure that both operations have the same operands. Note that we can
39607   // commute the FADD operands.
39608   SDValue LHS, RHS;
39609   if (V1.getOpcode() == ISD::FSUB) {
39610     LHS = V1->getOperand(0); RHS = V1->getOperand(1);
39611     if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
39612         (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
39613       return false;
39614   } else {
39615     assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
39616     LHS = V2->getOperand(0); RHS = V2->getOperand(1);
39617     if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
39618         (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
39619       return false;
39620   }
39621 
39622   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
39623   bool Op0Even;
39624   if (!isAddSubOrSubAddMask(Mask, Op0Even))
39625     return false;
39626 
39627   // It's a subadd if the vector in the even parity is an FADD.
39628   IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
39629                      : V2->getOpcode() == ISD::FADD;
39630 
39631   Opnd0 = LHS;
39632   Opnd1 = RHS;
39633   return true;
39634 }
39635 
39636 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
39637 static SDValue combineShuffleToFMAddSub(SDNode *N,
39638                                         const X86Subtarget &Subtarget,
39639                                         SelectionDAG &DAG) {
39640   // We only handle target-independent shuffles.
39641   // FIXME: It would be easy and harmless to use the target shuffle mask
39642   // extraction tool to support more.
39643   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
39644     return SDValue();
39645 
39646   MVT VT = N->getSimpleValueType(0);
39647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39648   if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
39649     return SDValue();
39650 
39651   // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
39652   SDValue Op0 = N->getOperand(0);
39653   SDValue Op1 = N->getOperand(1);
39654   SDValue FMAdd = Op0, FMSub = Op1;
39655   if (FMSub.getOpcode() != X86ISD::FMSUB)
39656     std::swap(FMAdd, FMSub);
39657 
39658   if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
39659       FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
39660       FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
39661       FMAdd.getOperand(2) != FMSub.getOperand(2))
39662     return SDValue();
39663 
39664   // Check for correct shuffle mask.
39665   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
39666   bool Op0Even;
39667   if (!isAddSubOrSubAddMask(Mask, Op0Even))
39668     return SDValue();
39669 
39670   // FMAddSub takes zeroth operand from FMSub node.
39671   SDLoc DL(N);
39672   bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
39673   unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
39674   return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
39675                      FMAdd.getOperand(2));
39676 }
39677 
39678 /// Try to combine a shuffle into a target-specific add-sub or
39679 /// mul-add-sub node.
39680 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
39681                                                 const X86Subtarget &Subtarget,
39682                                                 SelectionDAG &DAG) {
39683   if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
39684     return V;
39685 
39686   SDValue Opnd0, Opnd1;
39687   bool IsSubAdd;
39688   if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
39689     return SDValue();
39690 
39691   MVT VT = N->getSimpleValueType(0);
39692   SDLoc DL(N);
39693 
39694   // Try to generate X86ISD::FMADDSUB node here.
39695   SDValue Opnd2;
39696   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
39697     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
39698     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
39699   }
39700 
39701   if (IsSubAdd)
39702     return SDValue();
39703 
39704   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
39705   // the ADDSUB idiom has been successfully recognized. There are no known
39706   // X86 targets with 512-bit ADDSUB instructions!
39707   if (VT.is512BitVector())
39708     return SDValue();
39709 
39710   // Do not generate X86ISD::ADDSUB node for FP16's vector types even though
39711   // the ADDSUB idiom has been successfully recognized. There are no known
39712   // X86 targets with FP16 ADDSUB instructions!
39713   if (VT.getVectorElementType() == MVT::f16)
39714     return SDValue();
39715 
39716   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
39717 }
39718 
39719 // We are looking for a shuffle where both sources are concatenated with undef
39720 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
39721 // if we can express this as a single-source shuffle, that's preferable.
39722 static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
39723                                            const X86Subtarget &Subtarget) {
39724   if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
39725     return SDValue();
39726 
39727   EVT VT = N->getValueType(0);
39728 
39729   // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
39730   if (!VT.is128BitVector() && !VT.is256BitVector())
39731     return SDValue();
39732 
39733   if (VT.getVectorElementType() != MVT::i32 &&
39734       VT.getVectorElementType() != MVT::i64 &&
39735       VT.getVectorElementType() != MVT::f32 &&
39736       VT.getVectorElementType() != MVT::f64)
39737     return SDValue();
39738 
39739   SDValue N0 = N->getOperand(0);
39740   SDValue N1 = N->getOperand(1);
39741 
39742   // Check that both sources are concats with undef.
39743   if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
39744       N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
39745       N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
39746       !N1.getOperand(1).isUndef())
39747     return SDValue();
39748 
39749   // Construct the new shuffle mask. Elements from the first source retain their
39750   // index, but elements from the second source no longer need to skip an undef.
39751   SmallVector<int, 8> Mask;
39752   int NumElts = VT.getVectorNumElements();
39753 
39754   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
39755   for (int Elt : SVOp->getMask())
39756     Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
39757 
39758   SDLoc DL(N);
39759   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
39760                                N1.getOperand(0));
39761   return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
39762 }
39763 
39764 /// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
39765 /// low half of each source vector and does not set any high half elements in
39766 /// the destination vector, narrow the shuffle to half its original size.
39767 static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
39768   if (!Shuf->getValueType(0).isSimple())
39769     return SDValue();
39770   MVT VT = Shuf->getSimpleValueType(0);
39771   if (!VT.is256BitVector() && !VT.is512BitVector())
39772     return SDValue();
39773 
39774   // See if we can ignore all of the high elements of the shuffle.
39775   ArrayRef<int> Mask = Shuf->getMask();
39776   if (!isUndefUpperHalf(Mask))
39777     return SDValue();
39778 
39779   // Check if the shuffle mask accesses only the low half of each input vector
39780   // (half-index output is 0 or 2).
39781   int HalfIdx1, HalfIdx2;
39782   SmallVector<int, 8> HalfMask(Mask.size() / 2);
39783   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
39784       (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
39785     return SDValue();
39786 
39787   // Create a half-width shuffle to replace the unnecessarily wide shuffle.
39788   // The trick is knowing that all of the insert/extract are actually free
39789   // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
39790   // of narrow inputs into a narrow output, and that is always cheaper than
39791   // the wide shuffle that we started with.
39792   return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
39793                                Shuf->getOperand(1), HalfMask, HalfIdx1,
39794                                HalfIdx2, false, DAG, /*UseConcat*/true);
39795 }
39796 
39797 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
39798                               TargetLowering::DAGCombinerInfo &DCI,
39799                               const X86Subtarget &Subtarget) {
39800   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
39801     if (SDValue V = narrowShuffle(Shuf, DAG))
39802       return V;
39803 
39804   // If we have legalized the vector types, look for blends of FADD and FSUB
39805   // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
39806   SDLoc dl(N);
39807   EVT VT = N->getValueType(0);
39808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39809   if (TLI.isTypeLegal(VT))
39810     if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
39811       return AddSub;
39812 
39813   // Attempt to combine into a vector load/broadcast.
39814   if (SDValue LD = combineToConsecutiveLoads(
39815           VT, SDValue(N, 0), dl, DAG, Subtarget, /*IsAfterLegalize*/ true))
39816     return LD;
39817 
39818   // For AVX2, we sometimes want to combine
39819   // (vector_shuffle <mask> (concat_vectors t1, undef)
39820   //                        (concat_vectors t2, undef))
39821   // Into:
39822   // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
39823   // Since the latter can be efficiently lowered with VPERMD/VPERMQ
39824   if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
39825     return ShufConcat;
39826 
39827   if (isTargetShuffle(N->getOpcode())) {
39828     SDValue Op(N, 0);
39829     if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
39830       return Shuffle;
39831 
39832     // Try recursively combining arbitrary sequences of x86 shuffle
39833     // instructions into higher-order shuffles. We do this after combining
39834     // specific PSHUF instruction sequences into their minimal form so that we
39835     // can evaluate how many specialized shuffle instructions are involved in
39836     // a particular chain.
39837     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
39838       return Res;
39839 
39840     // Simplify source operands based on shuffle mask.
39841     // TODO - merge this into combineX86ShufflesRecursively.
39842     APInt KnownUndef, KnownZero;
39843     APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
39844     if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
39845                                        DCI))
39846       return SDValue(N, 0);
39847   }
39848 
39849   return SDValue();
39850 }
39851 
39852 // Simplify variable target shuffle masks based on the demanded elements.
39853 // TODO: Handle DemandedBits in mask indices as well?
39854 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetShuffle(
39855     SDValue Op, const APInt &DemandedElts, unsigned MaskIndex,
39856     TargetLowering::TargetLoweringOpt &TLO, unsigned Depth) const {
39857   // If we're demanding all elements don't bother trying to simplify the mask.
39858   unsigned NumElts = DemandedElts.getBitWidth();
39859   if (DemandedElts.isAllOnes())
39860     return false;
39861 
39862   SDValue Mask = Op.getOperand(MaskIndex);
39863   if (!Mask.hasOneUse())
39864     return false;
39865 
39866   // Attempt to generically simplify the variable shuffle mask.
39867   APInt MaskUndef, MaskZero;
39868   if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
39869                                  Depth + 1))
39870     return true;
39871 
39872   // Attempt to extract+simplify a (constant pool load) shuffle mask.
39873   // TODO: Support other types from getTargetShuffleMaskIndices?
39874   SDValue BC = peekThroughOneUseBitcasts(Mask);
39875   EVT BCVT = BC.getValueType();
39876   auto *Load = dyn_cast<LoadSDNode>(BC);
39877   if (!Load)
39878     return false;
39879 
39880   const Constant *C = getTargetConstantFromNode(Load);
39881   if (!C)
39882     return false;
39883 
39884   Type *CTy = C->getType();
39885   if (!CTy->isVectorTy() ||
39886       CTy->getPrimitiveSizeInBits() != Mask.getValueSizeInBits())
39887     return false;
39888 
39889   // Handle scaling for i64 elements on 32-bit targets.
39890   unsigned NumCstElts = cast<FixedVectorType>(CTy)->getNumElements();
39891   if (NumCstElts != NumElts && NumCstElts != (NumElts * 2))
39892     return false;
39893   unsigned Scale = NumCstElts / NumElts;
39894 
39895   // Simplify mask if we have an undemanded element that is not undef.
39896   bool Simplified = false;
39897   SmallVector<Constant *, 32> ConstVecOps;
39898   for (unsigned i = 0; i != NumCstElts; ++i) {
39899     Constant *Elt = C->getAggregateElement(i);
39900     if (!DemandedElts[i / Scale] && !isa<UndefValue>(Elt)) {
39901       ConstVecOps.push_back(UndefValue::get(Elt->getType()));
39902       Simplified = true;
39903       continue;
39904     }
39905     ConstVecOps.push_back(Elt);
39906   }
39907   if (!Simplified)
39908     return false;
39909 
39910   // Generate new constant pool entry + legalize immediately for the load.
39911   SDLoc DL(Op);
39912   SDValue CV = TLO.DAG.getConstantPool(ConstantVector::get(ConstVecOps), BCVT);
39913   SDValue LegalCV = LowerConstantPool(CV, TLO.DAG);
39914   SDValue NewMask = TLO.DAG.getLoad(
39915       BCVT, DL, TLO.DAG.getEntryNode(), LegalCV,
39916       MachinePointerInfo::getConstantPool(TLO.DAG.getMachineFunction()),
39917       Load->getAlign());
39918   return TLO.CombineTo(Mask, TLO.DAG.getBitcast(Mask.getValueType(), NewMask));
39919 }
39920 
39921 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
39922     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
39923     TargetLoweringOpt &TLO, unsigned Depth) const {
39924   int NumElts = DemandedElts.getBitWidth();
39925   unsigned Opc = Op.getOpcode();
39926   EVT VT = Op.getValueType();
39927 
39928   // Handle special case opcodes.
39929   switch (Opc) {
39930   case X86ISD::PMULDQ:
39931   case X86ISD::PMULUDQ: {
39932     APInt LHSUndef, LHSZero;
39933     APInt RHSUndef, RHSZero;
39934     SDValue LHS = Op.getOperand(0);
39935     SDValue RHS = Op.getOperand(1);
39936     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
39937                                    Depth + 1))
39938       return true;
39939     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
39940                                    Depth + 1))
39941       return true;
39942     // Multiply by zero.
39943     KnownZero = LHSZero | RHSZero;
39944     break;
39945   }
39946   case X86ISD::VPMADDWD: {
39947     APInt LHSUndef, LHSZero;
39948     APInt RHSUndef, RHSZero;
39949     SDValue LHS = Op.getOperand(0);
39950     SDValue RHS = Op.getOperand(1);
39951     APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, 2 * NumElts);
39952 
39953     if (SimplifyDemandedVectorElts(LHS, DemandedSrcElts, LHSUndef, LHSZero, TLO,
39954                                    Depth + 1))
39955       return true;
39956     if (SimplifyDemandedVectorElts(RHS, DemandedSrcElts, RHSUndef, RHSZero, TLO,
39957                                    Depth + 1))
39958       return true;
39959 
39960     // TODO: Multiply by zero.
39961 
39962     // If RHS/LHS elements are known zero then we don't need the LHS/RHS equivalent.
39963     APInt DemandedLHSElts = DemandedSrcElts & ~RHSZero;
39964     if (SimplifyDemandedVectorElts(LHS, DemandedLHSElts, LHSUndef, LHSZero, TLO,
39965                                    Depth + 1))
39966       return true;
39967     APInt DemandedRHSElts = DemandedSrcElts & ~LHSZero;
39968     if (SimplifyDemandedVectorElts(RHS, DemandedRHSElts, RHSUndef, RHSZero, TLO,
39969                                    Depth + 1))
39970       return true;
39971     break;
39972   }
39973   case X86ISD::PSADBW: {
39974     SDValue LHS = Op.getOperand(0);
39975     SDValue RHS = Op.getOperand(1);
39976     assert(VT.getScalarType() == MVT::i64 &&
39977            LHS.getValueType() == RHS.getValueType() &&
39978            LHS.getValueType().getScalarType() == MVT::i8 &&
39979            "Unexpected PSADBW types");
39980 
39981     // Aggressively peek through ops to get at the demanded elts.
39982     if (!DemandedElts.isAllOnes()) {
39983       unsigned NumSrcElts = LHS.getValueType().getVectorNumElements();
39984       APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
39985       SDValue NewLHS = SimplifyMultipleUseDemandedVectorElts(
39986           LHS, DemandedSrcElts, TLO.DAG, Depth + 1);
39987       SDValue NewRHS = SimplifyMultipleUseDemandedVectorElts(
39988           RHS, DemandedSrcElts, TLO.DAG, Depth + 1);
39989       if (NewLHS || NewRHS) {
39990         NewLHS = NewLHS ? NewLHS : LHS;
39991         NewRHS = NewRHS ? NewRHS : RHS;
39992         return TLO.CombineTo(
39993             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
39994       }
39995     }
39996     break;
39997   }
39998   case X86ISD::VSHL:
39999   case X86ISD::VSRL:
40000   case X86ISD::VSRA: {
40001     // We only need the bottom 64-bits of the (128-bit) shift amount.
40002     SDValue Amt = Op.getOperand(1);
40003     MVT AmtVT = Amt.getSimpleValueType();
40004     assert(AmtVT.is128BitVector() && "Unexpected value type");
40005 
40006     // If we reuse the shift amount just for sse shift amounts then we know that
40007     // only the bottom 64-bits are only ever used.
40008     bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
40009       unsigned UseOpc = Use->getOpcode();
40010       return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
40011               UseOpc == X86ISD::VSRA) &&
40012              Use->getOperand(0) != Amt;
40013     });
40014 
40015     APInt AmtUndef, AmtZero;
40016     unsigned NumAmtElts = AmtVT.getVectorNumElements();
40017     APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
40018     if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
40019                                    Depth + 1, AssumeSingleUse))
40020       return true;
40021     LLVM_FALLTHROUGH;
40022   }
40023   case X86ISD::VSHLI:
40024   case X86ISD::VSRLI:
40025   case X86ISD::VSRAI: {
40026     SDValue Src = Op.getOperand(0);
40027     APInt SrcUndef;
40028     if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
40029                                    Depth + 1))
40030       return true;
40031 
40032     // Aggressively peek through ops to get at the demanded elts.
40033     if (!DemandedElts.isAllOnes())
40034       if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
40035               Src, DemandedElts, TLO.DAG, Depth + 1))
40036         return TLO.CombineTo(
40037             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc, Op.getOperand(1)));
40038     break;
40039   }
40040   case X86ISD::KSHIFTL: {
40041     SDValue Src = Op.getOperand(0);
40042     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
40043     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
40044     unsigned ShiftAmt = Amt->getZExtValue();
40045 
40046     if (ShiftAmt == 0)
40047       return TLO.CombineTo(Op, Src);
40048 
40049     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
40050     // single shift.  We can do this if the bottom bits (which are shifted
40051     // out) are never demanded.
40052     if (Src.getOpcode() == X86ISD::KSHIFTR) {
40053       if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
40054         unsigned C1 = Src.getConstantOperandVal(1);
40055         unsigned NewOpc = X86ISD::KSHIFTL;
40056         int Diff = ShiftAmt - C1;
40057         if (Diff < 0) {
40058           Diff = -Diff;
40059           NewOpc = X86ISD::KSHIFTR;
40060         }
40061 
40062         SDLoc dl(Op);
40063         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
40064         return TLO.CombineTo(
40065             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
40066       }
40067     }
40068 
40069     APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
40070     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
40071                                    Depth + 1))
40072       return true;
40073 
40074     KnownUndef <<= ShiftAmt;
40075     KnownZero <<= ShiftAmt;
40076     KnownZero.setLowBits(ShiftAmt);
40077     break;
40078   }
40079   case X86ISD::KSHIFTR: {
40080     SDValue Src = Op.getOperand(0);
40081     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
40082     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
40083     unsigned ShiftAmt = Amt->getZExtValue();
40084 
40085     if (ShiftAmt == 0)
40086       return TLO.CombineTo(Op, Src);
40087 
40088     // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
40089     // single shift.  We can do this if the top bits (which are shifted
40090     // out) are never demanded.
40091     if (Src.getOpcode() == X86ISD::KSHIFTL) {
40092       if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
40093         unsigned C1 = Src.getConstantOperandVal(1);
40094         unsigned NewOpc = X86ISD::KSHIFTR;
40095         int Diff = ShiftAmt - C1;
40096         if (Diff < 0) {
40097           Diff = -Diff;
40098           NewOpc = X86ISD::KSHIFTL;
40099         }
40100 
40101         SDLoc dl(Op);
40102         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
40103         return TLO.CombineTo(
40104             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
40105       }
40106     }
40107 
40108     APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
40109     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
40110                                    Depth + 1))
40111       return true;
40112 
40113     KnownUndef.lshrInPlace(ShiftAmt);
40114     KnownZero.lshrInPlace(ShiftAmt);
40115     KnownZero.setHighBits(ShiftAmt);
40116     break;
40117   }
40118   case X86ISD::CVTSI2P:
40119   case X86ISD::CVTUI2P: {
40120     SDValue Src = Op.getOperand(0);
40121     MVT SrcVT = Src.getSimpleValueType();
40122     APInt SrcUndef, SrcZero;
40123     APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
40124     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
40125                                    Depth + 1))
40126       return true;
40127     break;
40128   }
40129   case X86ISD::PACKSS:
40130   case X86ISD::PACKUS: {
40131     SDValue N0 = Op.getOperand(0);
40132     SDValue N1 = Op.getOperand(1);
40133 
40134     APInt DemandedLHS, DemandedRHS;
40135     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
40136 
40137     APInt LHSUndef, LHSZero;
40138     if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
40139                                    Depth + 1))
40140       return true;
40141     APInt RHSUndef, RHSZero;
40142     if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
40143                                    Depth + 1))
40144       return true;
40145 
40146     // TODO - pass on known zero/undef.
40147 
40148     // Aggressively peek through ops to get at the demanded elts.
40149     // TODO - we should do this for all target/faux shuffles ops.
40150     if (!DemandedElts.isAllOnes()) {
40151       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
40152                                                             TLO.DAG, Depth + 1);
40153       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
40154                                                             TLO.DAG, Depth + 1);
40155       if (NewN0 || NewN1) {
40156         NewN0 = NewN0 ? NewN0 : N0;
40157         NewN1 = NewN1 ? NewN1 : N1;
40158         return TLO.CombineTo(Op,
40159                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
40160       }
40161     }
40162     break;
40163   }
40164   case X86ISD::HADD:
40165   case X86ISD::HSUB:
40166   case X86ISD::FHADD:
40167   case X86ISD::FHSUB: {
40168     SDValue N0 = Op.getOperand(0);
40169     SDValue N1 = Op.getOperand(1);
40170 
40171     APInt DemandedLHS, DemandedRHS;
40172     getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
40173 
40174     APInt LHSUndef, LHSZero;
40175     if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
40176                                    Depth + 1))
40177       return true;
40178     APInt RHSUndef, RHSZero;
40179     if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
40180                                    Depth + 1))
40181       return true;
40182 
40183     // TODO - pass on known zero/undef.
40184 
40185     // Aggressively peek through ops to get at the demanded elts.
40186     // TODO: Handle repeated operands.
40187     if (N0 != N1 && !DemandedElts.isAllOnes()) {
40188       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
40189                                                             TLO.DAG, Depth + 1);
40190       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
40191                                                             TLO.DAG, Depth + 1);
40192       if (NewN0 || NewN1) {
40193         NewN0 = NewN0 ? NewN0 : N0;
40194         NewN1 = NewN1 ? NewN1 : N1;
40195         return TLO.CombineTo(Op,
40196                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
40197       }
40198     }
40199     break;
40200   }
40201   case X86ISD::VTRUNC:
40202   case X86ISD::VTRUNCS:
40203   case X86ISD::VTRUNCUS: {
40204     SDValue Src = Op.getOperand(0);
40205     MVT SrcVT = Src.getSimpleValueType();
40206     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
40207     APInt SrcUndef, SrcZero;
40208     if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
40209                                    Depth + 1))
40210       return true;
40211     KnownZero = SrcZero.zextOrTrunc(NumElts);
40212     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
40213     break;
40214   }
40215   case X86ISD::BLENDV: {
40216     APInt SelUndef, SelZero;
40217     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
40218                                    SelZero, TLO, Depth + 1))
40219       return true;
40220 
40221     // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
40222     APInt LHSUndef, LHSZero;
40223     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
40224                                    LHSZero, TLO, Depth + 1))
40225       return true;
40226 
40227     APInt RHSUndef, RHSZero;
40228     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
40229                                    RHSZero, TLO, Depth + 1))
40230       return true;
40231 
40232     KnownZero = LHSZero & RHSZero;
40233     KnownUndef = LHSUndef & RHSUndef;
40234     break;
40235   }
40236   case X86ISD::VZEXT_MOVL: {
40237     // If upper demanded elements are already zero then we have nothing to do.
40238     SDValue Src = Op.getOperand(0);
40239     APInt DemandedUpperElts = DemandedElts;
40240     DemandedUpperElts.clearLowBits(1);
40241     if (TLO.DAG.computeKnownBits(Src, DemandedUpperElts, Depth + 1).isZero())
40242       return TLO.CombineTo(Op, Src);
40243     break;
40244   }
40245   case X86ISD::VBROADCAST: {
40246     SDValue Src = Op.getOperand(0);
40247     MVT SrcVT = Src.getSimpleValueType();
40248     if (!SrcVT.isVector())
40249       break;
40250     // Don't bother broadcasting if we just need the 0'th element.
40251     if (DemandedElts == 1) {
40252       if (Src.getValueType() != VT)
40253         Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
40254                              SDLoc(Op));
40255       return TLO.CombineTo(Op, Src);
40256     }
40257     APInt SrcUndef, SrcZero;
40258     APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
40259     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
40260                                    Depth + 1))
40261       return true;
40262     // Aggressively peek through src to get at the demanded elt.
40263     // TODO - we should do this for all target/faux shuffles ops.
40264     if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
40265             Src, SrcElts, TLO.DAG, Depth + 1))
40266       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
40267     break;
40268   }
40269   case X86ISD::VPERMV:
40270     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 0, TLO,
40271                                                    Depth))
40272       return true;
40273     break;
40274   case X86ISD::PSHUFB:
40275   case X86ISD::VPERMV3:
40276   case X86ISD::VPERMILPV:
40277     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 1, TLO,
40278                                                    Depth))
40279       return true;
40280     break;
40281   case X86ISD::VPPERM:
40282   case X86ISD::VPERMIL2:
40283     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 2, TLO,
40284                                                    Depth))
40285       return true;
40286     break;
40287   }
40288 
40289   // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
40290   // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
40291   // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
40292   if ((VT.is256BitVector() || VT.is512BitVector()) &&
40293       DemandedElts.lshr(NumElts / 2) == 0) {
40294     unsigned SizeInBits = VT.getSizeInBits();
40295     unsigned ExtSizeInBits = SizeInBits / 2;
40296 
40297     // See if 512-bit ops only use the bottom 128-bits.
40298     if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
40299       ExtSizeInBits = SizeInBits / 4;
40300 
40301     switch (Opc) {
40302       // Scalar broadcast.
40303     case X86ISD::VBROADCAST: {
40304       SDLoc DL(Op);
40305       SDValue Src = Op.getOperand(0);
40306       if (Src.getValueSizeInBits() > ExtSizeInBits)
40307         Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
40308       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
40309                                     ExtSizeInBits / VT.getScalarSizeInBits());
40310       SDValue Bcst = TLO.DAG.getNode(X86ISD::VBROADCAST, DL, BcstVT, Src);
40311       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
40312                                                TLO.DAG, DL, ExtSizeInBits));
40313     }
40314     case X86ISD::VBROADCAST_LOAD: {
40315       SDLoc DL(Op);
40316       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
40317       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
40318                                     ExtSizeInBits / VT.getScalarSizeInBits());
40319       SDVTList Tys = TLO.DAG.getVTList(BcstVT, MVT::Other);
40320       SDValue Ops[] = {MemIntr->getOperand(0), MemIntr->getOperand(1)};
40321       SDValue Bcst = TLO.DAG.getMemIntrinsicNode(
40322           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MemIntr->getMemoryVT(),
40323           MemIntr->getMemOperand());
40324       TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
40325                                            Bcst.getValue(1));
40326       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
40327                                                TLO.DAG, DL, ExtSizeInBits));
40328     }
40329       // Subvector broadcast.
40330     case X86ISD::SUBV_BROADCAST_LOAD: {
40331       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
40332       EVT MemVT = MemIntr->getMemoryVT();
40333       if (ExtSizeInBits == MemVT.getStoreSizeInBits()) {
40334         SDLoc DL(Op);
40335         SDValue Ld =
40336             TLO.DAG.getLoad(MemVT, DL, MemIntr->getChain(),
40337                             MemIntr->getBasePtr(), MemIntr->getMemOperand());
40338         TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
40339                                              Ld.getValue(1));
40340         return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Ld, 0,
40341                                                  TLO.DAG, DL, ExtSizeInBits));
40342       } else if ((ExtSizeInBits % MemVT.getStoreSizeInBits()) == 0) {
40343         SDLoc DL(Op);
40344         EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
40345                                       ExtSizeInBits / VT.getScalarSizeInBits());
40346         if (SDValue BcstLd =
40347                 getBROADCAST_LOAD(Opc, DL, BcstVT, MemVT, MemIntr, 0, TLO.DAG))
40348           return TLO.CombineTo(Op,
40349                                insertSubVector(TLO.DAG.getUNDEF(VT), BcstLd, 0,
40350                                                TLO.DAG, DL, ExtSizeInBits));
40351       }
40352       break;
40353     }
40354       // Byte shifts by immediate.
40355     case X86ISD::VSHLDQ:
40356     case X86ISD::VSRLDQ:
40357       // Shift by uniform.
40358     case X86ISD::VSHL:
40359     case X86ISD::VSRL:
40360     case X86ISD::VSRA:
40361       // Shift by immediate.
40362     case X86ISD::VSHLI:
40363     case X86ISD::VSRLI:
40364     case X86ISD::VSRAI: {
40365       SDLoc DL(Op);
40366       SDValue Ext0 =
40367           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
40368       SDValue ExtOp =
40369           TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
40370       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
40371       SDValue Insert =
40372           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
40373       return TLO.CombineTo(Op, Insert);
40374     }
40375     case X86ISD::VPERMI: {
40376       // Simplify PERMPD/PERMQ to extract_subvector.
40377       // TODO: This should be done in shuffle combining.
40378       if (VT == MVT::v4f64 || VT == MVT::v4i64) {
40379         SmallVector<int, 4> Mask;
40380         DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
40381         if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
40382           SDLoc DL(Op);
40383           SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
40384           SDValue UndefVec = TLO.DAG.getUNDEF(VT);
40385           SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
40386           return TLO.CombineTo(Op, Insert);
40387         }
40388       }
40389       break;
40390     }
40391     case X86ISD::VPERM2X128: {
40392       // Simplify VPERM2F128/VPERM2I128 to extract_subvector.
40393       SDLoc DL(Op);
40394       unsigned LoMask = Op.getConstantOperandVal(2) & 0xF;
40395       if (LoMask & 0x8)
40396         return TLO.CombineTo(
40397             Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, DL));
40398       unsigned EltIdx = (LoMask & 0x1) * (NumElts / 2);
40399       unsigned SrcIdx = (LoMask & 0x2) >> 1;
40400       SDValue ExtOp =
40401           extractSubVector(Op.getOperand(SrcIdx), EltIdx, TLO.DAG, DL, 128);
40402       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
40403       SDValue Insert =
40404           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
40405       return TLO.CombineTo(Op, Insert);
40406     }
40407       // Zero upper elements.
40408     case X86ISD::VZEXT_MOVL:
40409       // Target unary shuffles by immediate:
40410     case X86ISD::PSHUFD:
40411     case X86ISD::PSHUFLW:
40412     case X86ISD::PSHUFHW:
40413     case X86ISD::VPERMILPI:
40414       // (Non-Lane Crossing) Target Shuffles.
40415     case X86ISD::VPERMILPV:
40416     case X86ISD::VPERMIL2:
40417     case X86ISD::PSHUFB:
40418     case X86ISD::UNPCKL:
40419     case X86ISD::UNPCKH:
40420     case X86ISD::BLENDI:
40421       // Integer ops.
40422     case X86ISD::AVG:
40423     case X86ISD::PACKSS:
40424     case X86ISD::PACKUS:
40425       // Horizontal Ops.
40426     case X86ISD::HADD:
40427     case X86ISD::HSUB:
40428     case X86ISD::FHADD:
40429     case X86ISD::FHSUB: {
40430       SDLoc DL(Op);
40431       SmallVector<SDValue, 4> Ops;
40432       for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
40433         SDValue SrcOp = Op.getOperand(i);
40434         EVT SrcVT = SrcOp.getValueType();
40435         assert((!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) &&
40436                "Unsupported vector size");
40437         Ops.push_back(SrcVT.isVector() ? extractSubVector(SrcOp, 0, TLO.DAG, DL,
40438                                                           ExtSizeInBits)
40439                                        : SrcOp);
40440       }
40441       MVT ExtVT = VT.getSimpleVT();
40442       ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
40443                                ExtSizeInBits / ExtVT.getScalarSizeInBits());
40444       SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ops);
40445       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
40446       SDValue Insert =
40447           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
40448       return TLO.CombineTo(Op, Insert);
40449     }
40450     }
40451   }
40452 
40453   // For broadcasts, unless we *only* demand the 0'th element,
40454   // stop attempts at simplification here, we aren't going to improve things,
40455   // this is better than any potential shuffle.
40456   if (isTargetShuffleSplat(Op) && !DemandedElts.isOne())
40457     return false;
40458 
40459   // Get target/faux shuffle mask.
40460   APInt OpUndef, OpZero;
40461   SmallVector<int, 64> OpMask;
40462   SmallVector<SDValue, 2> OpInputs;
40463   if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
40464                               OpZero, TLO.DAG, Depth, false))
40465     return false;
40466 
40467   // Shuffle inputs must be the same size as the result.
40468   if (OpMask.size() != (unsigned)NumElts ||
40469       llvm::any_of(OpInputs, [VT](SDValue V) {
40470         return VT.getSizeInBits() != V.getValueSizeInBits() ||
40471                !V.getValueType().isVector();
40472       }))
40473     return false;
40474 
40475   KnownZero = OpZero;
40476   KnownUndef = OpUndef;
40477 
40478   // Check if shuffle mask can be simplified to undef/zero/identity.
40479   int NumSrcs = OpInputs.size();
40480   for (int i = 0; i != NumElts; ++i)
40481     if (!DemandedElts[i])
40482       OpMask[i] = SM_SentinelUndef;
40483 
40484   if (isUndefInRange(OpMask, 0, NumElts)) {
40485     KnownUndef.setAllBits();
40486     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
40487   }
40488   if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
40489     KnownZero.setAllBits();
40490     return TLO.CombineTo(
40491         Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
40492   }
40493   for (int Src = 0; Src != NumSrcs; ++Src)
40494     if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
40495       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
40496 
40497   // Attempt to simplify inputs.
40498   for (int Src = 0; Src != NumSrcs; ++Src) {
40499     // TODO: Support inputs of different types.
40500     if (OpInputs[Src].getValueType() != VT)
40501       continue;
40502 
40503     int Lo = Src * NumElts;
40504     APInt SrcElts = APInt::getZero(NumElts);
40505     for (int i = 0; i != NumElts; ++i)
40506       if (DemandedElts[i]) {
40507         int M = OpMask[i] - Lo;
40508         if (0 <= M && M < NumElts)
40509           SrcElts.setBit(M);
40510       }
40511 
40512     // TODO - Propagate input undef/zero elts.
40513     APInt SrcUndef, SrcZero;
40514     if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
40515                                    TLO, Depth + 1))
40516       return true;
40517   }
40518 
40519   // If we don't demand all elements, then attempt to combine to a simpler
40520   // shuffle.
40521   // We need to convert the depth to something combineX86ShufflesRecursively
40522   // can handle - so pretend its Depth == 0 again, and reduce the max depth
40523   // to match. This prevents combineX86ShuffleChain from returning a
40524   // combined shuffle that's the same as the original root, causing an
40525   // infinite loop.
40526   if (!DemandedElts.isAllOnes()) {
40527     assert(Depth < X86::MaxShuffleCombineDepth && "Depth out of range");
40528 
40529     SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
40530     for (int i = 0; i != NumElts; ++i)
40531       if (DemandedElts[i])
40532         DemandedMask[i] = i;
40533 
40534     SDValue NewShuffle = combineX86ShufflesRecursively(
40535         {Op}, 0, Op, DemandedMask, {}, 0, X86::MaxShuffleCombineDepth - Depth,
40536         /*HasVarMask*/ false,
40537         /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, TLO.DAG,
40538         Subtarget);
40539     if (NewShuffle)
40540       return TLO.CombineTo(Op, NewShuffle);
40541   }
40542 
40543   return false;
40544 }
40545 
40546 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
40547     SDValue Op, const APInt &OriginalDemandedBits,
40548     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
40549     unsigned Depth) const {
40550   EVT VT = Op.getValueType();
40551   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
40552   unsigned Opc = Op.getOpcode();
40553   switch(Opc) {
40554   case X86ISD::VTRUNC: {
40555     KnownBits KnownOp;
40556     SDValue Src = Op.getOperand(0);
40557     MVT SrcVT = Src.getSimpleValueType();
40558 
40559     // Simplify the input, using demanded bit information.
40560     APInt TruncMask = OriginalDemandedBits.zext(SrcVT.getScalarSizeInBits());
40561     APInt DemandedElts = OriginalDemandedElts.trunc(SrcVT.getVectorNumElements());
40562     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, KnownOp, TLO, Depth + 1))
40563       return true;
40564     break;
40565   }
40566   case X86ISD::PMULDQ:
40567   case X86ISD::PMULUDQ: {
40568     // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
40569     KnownBits KnownOp;
40570     SDValue LHS = Op.getOperand(0);
40571     SDValue RHS = Op.getOperand(1);
40572     // FIXME: Can we bound this better?
40573     APInt DemandedMask = APInt::getLowBitsSet(64, 32);
40574     if (SimplifyDemandedBits(LHS, DemandedMask, OriginalDemandedElts, KnownOp,
40575                              TLO, Depth + 1))
40576       return true;
40577     if (SimplifyDemandedBits(RHS, DemandedMask, OriginalDemandedElts, KnownOp,
40578                              TLO, Depth + 1))
40579       return true;
40580 
40581     // Aggressively peek through ops to get at the demanded low bits.
40582     SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
40583         LHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
40584     SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
40585         RHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
40586     if (DemandedLHS || DemandedRHS) {
40587       DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
40588       DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
40589       return TLO.CombineTo(
40590           Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
40591     }
40592     break;
40593   }
40594   case X86ISD::VSHLI: {
40595     SDValue Op0 = Op.getOperand(0);
40596 
40597     unsigned ShAmt = Op.getConstantOperandVal(1);
40598     if (ShAmt >= BitWidth)
40599       break;
40600 
40601     APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
40602 
40603     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
40604     // single shift.  We can do this if the bottom bits (which are shifted
40605     // out) are never demanded.
40606     if (Op0.getOpcode() == X86ISD::VSRLI &&
40607         OriginalDemandedBits.countTrailingZeros() >= ShAmt) {
40608       unsigned Shift2Amt = Op0.getConstantOperandVal(1);
40609       if (Shift2Amt < BitWidth) {
40610         int Diff = ShAmt - Shift2Amt;
40611         if (Diff == 0)
40612           return TLO.CombineTo(Op, Op0.getOperand(0));
40613 
40614         unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
40615         SDValue NewShift = TLO.DAG.getNode(
40616             NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
40617             TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
40618         return TLO.CombineTo(Op, NewShift);
40619       }
40620     }
40621 
40622     // If we are only demanding sign bits then we can use the shift source directly.
40623     unsigned NumSignBits =
40624         TLO.DAG.ComputeNumSignBits(Op0, OriginalDemandedElts, Depth + 1);
40625     unsigned UpperDemandedBits =
40626         BitWidth - OriginalDemandedBits.countTrailingZeros();
40627     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
40628       return TLO.CombineTo(Op, Op0);
40629 
40630     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
40631                              TLO, Depth + 1))
40632       return true;
40633 
40634     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
40635     Known.Zero <<= ShAmt;
40636     Known.One <<= ShAmt;
40637 
40638     // Low bits known zero.
40639     Known.Zero.setLowBits(ShAmt);
40640     return false;
40641   }
40642   case X86ISD::VSRLI: {
40643     unsigned ShAmt = Op.getConstantOperandVal(1);
40644     if (ShAmt >= BitWidth)
40645       break;
40646 
40647     APInt DemandedMask = OriginalDemandedBits << ShAmt;
40648 
40649     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
40650                              OriginalDemandedElts, Known, TLO, Depth + 1))
40651       return true;
40652 
40653     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
40654     Known.Zero.lshrInPlace(ShAmt);
40655     Known.One.lshrInPlace(ShAmt);
40656 
40657     // High bits known zero.
40658     Known.Zero.setHighBits(ShAmt);
40659     return false;
40660   }
40661   case X86ISD::VSRAI: {
40662     SDValue Op0 = Op.getOperand(0);
40663     SDValue Op1 = Op.getOperand(1);
40664 
40665     unsigned ShAmt = cast<ConstantSDNode>(Op1)->getZExtValue();
40666     if (ShAmt >= BitWidth)
40667       break;
40668 
40669     APInt DemandedMask = OriginalDemandedBits << ShAmt;
40670 
40671     // If we just want the sign bit then we don't need to shift it.
40672     if (OriginalDemandedBits.isSignMask())
40673       return TLO.CombineTo(Op, Op0);
40674 
40675     // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
40676     if (Op0.getOpcode() == X86ISD::VSHLI &&
40677         Op.getOperand(1) == Op0.getOperand(1)) {
40678       SDValue Op00 = Op0.getOperand(0);
40679       unsigned NumSignBits =
40680           TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
40681       if (ShAmt < NumSignBits)
40682         return TLO.CombineTo(Op, Op00);
40683     }
40684 
40685     // If any of the demanded bits are produced by the sign extension, we also
40686     // demand the input sign bit.
40687     if (OriginalDemandedBits.countLeadingZeros() < ShAmt)
40688       DemandedMask.setSignBit();
40689 
40690     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
40691                              TLO, Depth + 1))
40692       return true;
40693 
40694     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
40695     Known.Zero.lshrInPlace(ShAmt);
40696     Known.One.lshrInPlace(ShAmt);
40697 
40698     // If the input sign bit is known to be zero, or if none of the top bits
40699     // are demanded, turn this into an unsigned shift right.
40700     if (Known.Zero[BitWidth - ShAmt - 1] ||
40701         OriginalDemandedBits.countLeadingZeros() >= ShAmt)
40702       return TLO.CombineTo(
40703           Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
40704 
40705     // High bits are known one.
40706     if (Known.One[BitWidth - ShAmt - 1])
40707       Known.One.setHighBits(ShAmt);
40708     return false;
40709   }
40710   case X86ISD::PEXTRB:
40711   case X86ISD::PEXTRW: {
40712     SDValue Vec = Op.getOperand(0);
40713     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
40714     MVT VecVT = Vec.getSimpleValueType();
40715     unsigned NumVecElts = VecVT.getVectorNumElements();
40716 
40717     if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
40718       unsigned Idx = CIdx->getZExtValue();
40719       unsigned VecBitWidth = VecVT.getScalarSizeInBits();
40720 
40721       // If we demand no bits from the vector then we must have demanded
40722       // bits from the implict zext - simplify to zero.
40723       APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
40724       if (DemandedVecBits == 0)
40725         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
40726 
40727       APInt KnownUndef, KnownZero;
40728       APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
40729       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
40730                                      KnownZero, TLO, Depth + 1))
40731         return true;
40732 
40733       KnownBits KnownVec;
40734       if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
40735                                KnownVec, TLO, Depth + 1))
40736         return true;
40737 
40738       if (SDValue V = SimplifyMultipleUseDemandedBits(
40739               Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
40740         return TLO.CombineTo(
40741             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
40742 
40743       Known = KnownVec.zext(BitWidth);
40744       return false;
40745     }
40746     break;
40747   }
40748   case X86ISD::PINSRB:
40749   case X86ISD::PINSRW: {
40750     SDValue Vec = Op.getOperand(0);
40751     SDValue Scl = Op.getOperand(1);
40752     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
40753     MVT VecVT = Vec.getSimpleValueType();
40754 
40755     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
40756       unsigned Idx = CIdx->getZExtValue();
40757       if (!OriginalDemandedElts[Idx])
40758         return TLO.CombineTo(Op, Vec);
40759 
40760       KnownBits KnownVec;
40761       APInt DemandedVecElts(OriginalDemandedElts);
40762       DemandedVecElts.clearBit(Idx);
40763       if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
40764                                KnownVec, TLO, Depth + 1))
40765         return true;
40766 
40767       KnownBits KnownScl;
40768       unsigned NumSclBits = Scl.getScalarValueSizeInBits();
40769       APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
40770       if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
40771         return true;
40772 
40773       KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
40774       Known = KnownBits::commonBits(KnownVec, KnownScl);
40775       return false;
40776     }
40777     break;
40778   }
40779   case X86ISD::PACKSS:
40780     // PACKSS saturates to MIN/MAX integer values. So if we just want the
40781     // sign bit then we can just ask for the source operands sign bit.
40782     // TODO - add known bits handling.
40783     if (OriginalDemandedBits.isSignMask()) {
40784       APInt DemandedLHS, DemandedRHS;
40785       getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
40786 
40787       KnownBits KnownLHS, KnownRHS;
40788       APInt SignMask = APInt::getSignMask(BitWidth * 2);
40789       if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
40790                                KnownLHS, TLO, Depth + 1))
40791         return true;
40792       if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
40793                                KnownRHS, TLO, Depth + 1))
40794         return true;
40795 
40796       // Attempt to avoid multi-use ops if we don't need anything from them.
40797       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
40798           Op.getOperand(0), SignMask, DemandedLHS, TLO.DAG, Depth + 1);
40799       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
40800           Op.getOperand(1), SignMask, DemandedRHS, TLO.DAG, Depth + 1);
40801       if (DemandedOp0 || DemandedOp1) {
40802         SDValue Op0 = DemandedOp0 ? DemandedOp0 : Op.getOperand(0);
40803         SDValue Op1 = DemandedOp1 ? DemandedOp1 : Op.getOperand(1);
40804         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, Op0, Op1));
40805       }
40806     }
40807     // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
40808     break;
40809   case X86ISD::VBROADCAST: {
40810     SDValue Src = Op.getOperand(0);
40811     MVT SrcVT = Src.getSimpleValueType();
40812     APInt DemandedElts = APInt::getOneBitSet(
40813         SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1, 0);
40814     if (SimplifyDemandedBits(Src, OriginalDemandedBits, DemandedElts, Known,
40815                              TLO, Depth + 1))
40816       return true;
40817     // If we don't need the upper bits, attempt to narrow the broadcast source.
40818     // Don't attempt this on AVX512 as it might affect broadcast folding.
40819     // TODO: Should we attempt this for i32/i16 splats? They tend to be slower.
40820     if ((BitWidth == 64) && SrcVT.isScalarInteger() && !Subtarget.hasAVX512() &&
40821         OriginalDemandedBits.countLeadingZeros() >= (BitWidth / 2) &&
40822         Src->hasOneUse()) {
40823       MVT NewSrcVT = MVT::getIntegerVT(BitWidth / 2);
40824       SDValue NewSrc =
40825           TLO.DAG.getNode(ISD::TRUNCATE, SDLoc(Src), NewSrcVT, Src);
40826       MVT NewVT = MVT::getVectorVT(NewSrcVT, VT.getVectorNumElements() * 2);
40827       SDValue NewBcst =
40828           TLO.DAG.getNode(X86ISD::VBROADCAST, SDLoc(Op), NewVT, NewSrc);
40829       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, NewBcst));
40830     }
40831     break;
40832   }
40833   case X86ISD::PCMPGT:
40834     // icmp sgt(0, R) == ashr(R, BitWidth-1).
40835     // iff we only need the sign bit then we can use R directly.
40836     if (OriginalDemandedBits.isSignMask() &&
40837         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
40838       return TLO.CombineTo(Op, Op.getOperand(1));
40839     break;
40840   case X86ISD::MOVMSK: {
40841     SDValue Src = Op.getOperand(0);
40842     MVT SrcVT = Src.getSimpleValueType();
40843     unsigned SrcBits = SrcVT.getScalarSizeInBits();
40844     unsigned NumElts = SrcVT.getVectorNumElements();
40845 
40846     // If we don't need the sign bits at all just return zero.
40847     if (OriginalDemandedBits.countTrailingZeros() >= NumElts)
40848       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
40849 
40850     // Only demand the vector elements of the sign bits we need.
40851     APInt KnownUndef, KnownZero;
40852     APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
40853     if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
40854                                    TLO, Depth + 1))
40855       return true;
40856 
40857     Known.Zero = KnownZero.zextOrSelf(BitWidth);
40858     Known.Zero.setHighBits(BitWidth - NumElts);
40859 
40860     // MOVMSK only uses the MSB from each vector element.
40861     KnownBits KnownSrc;
40862     APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
40863     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
40864                              Depth + 1))
40865       return true;
40866 
40867     if (KnownSrc.One[SrcBits - 1])
40868       Known.One.setLowBits(NumElts);
40869     else if (KnownSrc.Zero[SrcBits - 1])
40870       Known.Zero.setLowBits(NumElts);
40871 
40872     // Attempt to avoid multi-use os if we don't need anything from it.
40873     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
40874             Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
40875       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
40876     return false;
40877   }
40878   case X86ISD::BEXTR:
40879   case X86ISD::BEXTRI: {
40880     SDValue Op0 = Op.getOperand(0);
40881     SDValue Op1 = Op.getOperand(1);
40882 
40883     // Only bottom 16-bits of the control bits are required.
40884     if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
40885       // NOTE: SimplifyDemandedBits won't do this for constants.
40886       uint64_t Val1 = Cst1->getZExtValue();
40887       uint64_t MaskedVal1 = Val1 & 0xFFFF;
40888       if (Opc == X86ISD::BEXTR && MaskedVal1 != Val1) {
40889         SDLoc DL(Op);
40890         return TLO.CombineTo(
40891             Op, TLO.DAG.getNode(X86ISD::BEXTR, DL, VT, Op0,
40892                                 TLO.DAG.getConstant(MaskedVal1, DL, VT)));
40893       }
40894 
40895       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
40896       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
40897 
40898       // If the length is 0, the result is 0.
40899       if (Length == 0) {
40900         Known.setAllZero();
40901         return false;
40902       }
40903 
40904       if ((Shift + Length) <= BitWidth) {
40905         APInt DemandedMask = APInt::getBitsSet(BitWidth, Shift, Shift + Length);
40906         if (SimplifyDemandedBits(Op0, DemandedMask, Known, TLO, Depth + 1))
40907           return true;
40908 
40909         Known = Known.extractBits(Length, Shift);
40910         Known = Known.zextOrTrunc(BitWidth);
40911         return false;
40912       }
40913     } else {
40914       assert(Opc == X86ISD::BEXTR && "Unexpected opcode!");
40915       KnownBits Known1;
40916       APInt DemandedMask(APInt::getLowBitsSet(BitWidth, 16));
40917       if (SimplifyDemandedBits(Op1, DemandedMask, Known1, TLO, Depth + 1))
40918         return true;
40919 
40920       // If the length is 0, replace with 0.
40921       KnownBits LengthBits = Known1.extractBits(8, 8);
40922       if (LengthBits.isZero())
40923         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
40924     }
40925 
40926     break;
40927   }
40928   case X86ISD::PDEP: {
40929     SDValue Op0 = Op.getOperand(0);
40930     SDValue Op1 = Op.getOperand(1);
40931 
40932     unsigned DemandedBitsLZ = OriginalDemandedBits.countLeadingZeros();
40933     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
40934 
40935     // If the demanded bits has leading zeroes, we don't demand those from the
40936     // mask.
40937     if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
40938       return true;
40939 
40940     // The number of possible 1s in the mask determines the number of LSBs of
40941     // operand 0 used. Undemanded bits from the mask don't matter so filter
40942     // them before counting.
40943     KnownBits Known2;
40944     uint64_t Count = (~Known.Zero & LoMask).countPopulation();
40945     APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
40946     if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
40947       return true;
40948 
40949     // Zeroes are retained from the mask, but not ones.
40950     Known.One.clearAllBits();
40951     // The result will have at least as many trailing zeros as the non-mask
40952     // operand since bits can only map to the same or higher bit position.
40953     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
40954     return false;
40955   }
40956   }
40957 
40958   return TargetLowering::SimplifyDemandedBitsForTargetNode(
40959       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
40960 }
40961 
40962 SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
40963     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
40964     SelectionDAG &DAG, unsigned Depth) const {
40965   int NumElts = DemandedElts.getBitWidth();
40966   unsigned Opc = Op.getOpcode();
40967   EVT VT = Op.getValueType();
40968 
40969   switch (Opc) {
40970   case X86ISD::PINSRB:
40971   case X86ISD::PINSRW: {
40972     // If we don't demand the inserted element, return the base vector.
40973     SDValue Vec = Op.getOperand(0);
40974     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
40975     MVT VecVT = Vec.getSimpleValueType();
40976     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
40977         !DemandedElts[CIdx->getZExtValue()])
40978       return Vec;
40979     break;
40980   }
40981   case X86ISD::VSHLI: {
40982     // If we are only demanding sign bits then we can use the shift source
40983     // directly.
40984     SDValue Op0 = Op.getOperand(0);
40985     unsigned ShAmt = Op.getConstantOperandVal(1);
40986     unsigned BitWidth = DemandedBits.getBitWidth();
40987     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
40988     unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
40989     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
40990       return Op0;
40991     break;
40992   }
40993   case X86ISD::VSRAI:
40994     // iff we only need the sign bit then we can use the source directly.
40995     // TODO: generalize where we only demand extended signbits.
40996     if (DemandedBits.isSignMask())
40997       return Op.getOperand(0);
40998     break;
40999   case X86ISD::PCMPGT:
41000     // icmp sgt(0, R) == ashr(R, BitWidth-1).
41001     // iff we only need the sign bit then we can use R directly.
41002     if (DemandedBits.isSignMask() &&
41003         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
41004       return Op.getOperand(1);
41005     break;
41006   }
41007 
41008   APInt ShuffleUndef, ShuffleZero;
41009   SmallVector<int, 16> ShuffleMask;
41010   SmallVector<SDValue, 2> ShuffleOps;
41011   if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
41012                              ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
41013     // If all the demanded elts are from one operand and are inline,
41014     // then we can use the operand directly.
41015     int NumOps = ShuffleOps.size();
41016     if (ShuffleMask.size() == (unsigned)NumElts &&
41017         llvm::all_of(ShuffleOps, [VT](SDValue V) {
41018           return VT.getSizeInBits() == V.getValueSizeInBits();
41019         })) {
41020 
41021       if (DemandedElts.isSubsetOf(ShuffleUndef))
41022         return DAG.getUNDEF(VT);
41023       if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
41024         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
41025 
41026       // Bitmask that indicates which ops have only been accessed 'inline'.
41027       APInt IdentityOp = APInt::getAllOnes(NumOps);
41028       for (int i = 0; i != NumElts; ++i) {
41029         int M = ShuffleMask[i];
41030         if (!DemandedElts[i] || ShuffleUndef[i])
41031           continue;
41032         int OpIdx = M / NumElts;
41033         int EltIdx = M % NumElts;
41034         if (M < 0 || EltIdx != i) {
41035           IdentityOp.clearAllBits();
41036           break;
41037         }
41038         IdentityOp &= APInt::getOneBitSet(NumOps, OpIdx);
41039         if (IdentityOp == 0)
41040           break;
41041       }
41042       assert((IdentityOp == 0 || IdentityOp.countPopulation() == 1) &&
41043              "Multiple identity shuffles detected");
41044 
41045       if (IdentityOp != 0)
41046         return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countTrailingZeros()]);
41047     }
41048   }
41049 
41050   return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
41051       Op, DemandedBits, DemandedElts, DAG, Depth);
41052 }
41053 
41054 bool X86TargetLowering::isSplatValueForTargetNode(SDValue Op,
41055                                                   const APInt &DemandedElts,
41056                                                   APInt &UndefElts,
41057                                                   unsigned Depth) const {
41058   unsigned NumElts = DemandedElts.getBitWidth();
41059   unsigned Opc = Op.getOpcode();
41060 
41061   switch (Opc) {
41062   case X86ISD::VBROADCAST:
41063   case X86ISD::VBROADCAST_LOAD:
41064     // TODO: Permit vXi64 types on 32-bit targets.
41065     if (isTypeLegal(Op.getValueType().getVectorElementType())) {
41066       UndefElts = APInt::getNullValue(NumElts);
41067       return true;
41068     }
41069     return false;
41070   }
41071 
41072   return TargetLowering::isSplatValueForTargetNode(Op, DemandedElts, UndefElts,
41073                                                    Depth);
41074 }
41075 
41076 // Helper to peek through bitops/trunc/setcc to determine size of source vector.
41077 // Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
41078 static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size,
41079                                       bool AllowTruncate) {
41080   switch (Src.getOpcode()) {
41081   case ISD::TRUNCATE:
41082     if (!AllowTruncate)
41083       return false;
41084     LLVM_FALLTHROUGH;
41085   case ISD::SETCC:
41086     return Src.getOperand(0).getValueSizeInBits() == Size;
41087   case ISD::AND:
41088   case ISD::XOR:
41089   case ISD::OR:
41090     return checkBitcastSrcVectorSize(Src.getOperand(0), Size, AllowTruncate) &&
41091            checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate);
41092   }
41093   return false;
41094 }
41095 
41096 // Helper to flip between AND/OR/XOR opcodes and their X86ISD FP equivalents.
41097 static unsigned getAltBitOpcode(unsigned Opcode) {
41098   switch(Opcode) {
41099   case ISD::AND: return X86ISD::FAND;
41100   case ISD::OR: return X86ISD::FOR;
41101   case ISD::XOR: return X86ISD::FXOR;
41102   case X86ISD::ANDNP: return X86ISD::FANDN;
41103   }
41104   llvm_unreachable("Unknown bitwise opcode");
41105 }
41106 
41107 // Helper to adjust v4i32 MOVMSK expansion to work with SSE1-only targets.
41108 static SDValue adjustBitcastSrcVectorSSE1(SelectionDAG &DAG, SDValue Src,
41109                                           const SDLoc &DL) {
41110   EVT SrcVT = Src.getValueType();
41111   if (SrcVT != MVT::v4i1)
41112     return SDValue();
41113 
41114   switch (Src.getOpcode()) {
41115   case ISD::SETCC:
41116     if (Src.getOperand(0).getValueType() == MVT::v4i32 &&
41117         ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
41118         cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT) {
41119       SDValue Op0 = Src.getOperand(0);
41120       if (ISD::isNormalLoad(Op0.getNode()))
41121         return DAG.getBitcast(MVT::v4f32, Op0);
41122       if (Op0.getOpcode() == ISD::BITCAST &&
41123           Op0.getOperand(0).getValueType() == MVT::v4f32)
41124         return Op0.getOperand(0);
41125     }
41126     break;
41127   case ISD::AND:
41128   case ISD::XOR:
41129   case ISD::OR: {
41130     SDValue Op0 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(0), DL);
41131     SDValue Op1 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(1), DL);
41132     if (Op0 && Op1)
41133       return DAG.getNode(getAltBitOpcode(Src.getOpcode()), DL, MVT::v4f32, Op0,
41134                          Op1);
41135     break;
41136   }
41137   }
41138   return SDValue();
41139 }
41140 
41141 // Helper to push sign extension of vXi1 SETCC result through bitops.
41142 static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
41143                                           SDValue Src, const SDLoc &DL) {
41144   switch (Src.getOpcode()) {
41145   case ISD::SETCC:
41146   case ISD::TRUNCATE:
41147     return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
41148   case ISD::AND:
41149   case ISD::XOR:
41150   case ISD::OR:
41151     return DAG.getNode(
41152         Src.getOpcode(), DL, SExtVT,
41153         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
41154         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
41155   }
41156   llvm_unreachable("Unexpected node type for vXi1 sign extension");
41157 }
41158 
41159 // Try to match patterns such as
41160 // (i16 bitcast (v16i1 x))
41161 // ->
41162 // (i16 movmsk (16i8 sext (v16i1 x)))
41163 // before the illegal vector is scalarized on subtargets that don't have legal
41164 // vxi1 types.
41165 static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
41166                                   const SDLoc &DL,
41167                                   const X86Subtarget &Subtarget) {
41168   EVT SrcVT = Src.getValueType();
41169   if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
41170     return SDValue();
41171 
41172   // Recognize the IR pattern for the movmsk intrinsic under SSE1 before type
41173   // legalization destroys the v4i32 type.
41174   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2()) {
41175     if (SDValue V = adjustBitcastSrcVectorSSE1(DAG, Src, DL)) {
41176       V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32,
41177                       DAG.getBitcast(MVT::v4f32, V));
41178       return DAG.getZExtOrTrunc(V, DL, VT);
41179     }
41180   }
41181 
41182   // If the input is a truncate from v16i8 or v32i8 go ahead and use a
41183   // movmskb even with avx512. This will be better than truncating to vXi1 and
41184   // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
41185   // vpcmpeqb/vpcmpgtb.
41186   bool PreferMovMsk = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
41187                       (Src.getOperand(0).getValueType() == MVT::v16i8 ||
41188                        Src.getOperand(0).getValueType() == MVT::v32i8 ||
41189                        Src.getOperand(0).getValueType() == MVT::v64i8);
41190 
41191   // Prefer movmsk for AVX512 for (bitcast (setlt X, 0)) which can be handled
41192   // directly with vpmovmskb/vmovmskps/vmovmskpd.
41193   if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
41194       cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT &&
41195       ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
41196     EVT CmpVT = Src.getOperand(0).getValueType();
41197     EVT EltVT = CmpVT.getVectorElementType();
41198     if (CmpVT.getSizeInBits() <= 256 &&
41199         (EltVT == MVT::i8 || EltVT == MVT::i32 || EltVT == MVT::i64))
41200       PreferMovMsk = true;
41201   }
41202 
41203   // With AVX512 vxi1 types are legal and we prefer using k-regs.
41204   // MOVMSK is supported in SSE2 or later.
41205   if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !PreferMovMsk))
41206     return SDValue();
41207 
41208   // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
41209   // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
41210   // v8i16 and v16i16.
41211   // For these two cases, we can shuffle the upper element bytes to a
41212   // consecutive sequence at the start of the vector and treat the results as
41213   // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
41214   // for v16i16 this is not the case, because the shuffle is expensive, so we
41215   // avoid sign-extending to this type entirely.
41216   // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
41217   // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
41218   MVT SExtVT;
41219   bool PropagateSExt = false;
41220   switch (SrcVT.getSimpleVT().SimpleTy) {
41221   default:
41222     return SDValue();
41223   case MVT::v2i1:
41224     SExtVT = MVT::v2i64;
41225     break;
41226   case MVT::v4i1:
41227     SExtVT = MVT::v4i32;
41228     // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
41229     // sign-extend to a 256-bit operation to avoid truncation.
41230     if (Subtarget.hasAVX() &&
41231         checkBitcastSrcVectorSize(Src, 256, Subtarget.hasAVX2())) {
41232       SExtVT = MVT::v4i64;
41233       PropagateSExt = true;
41234     }
41235     break;
41236   case MVT::v8i1:
41237     SExtVT = MVT::v8i16;
41238     // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
41239     // sign-extend to a 256-bit operation to match the compare.
41240     // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
41241     // 256-bit because the shuffle is cheaper than sign extending the result of
41242     // the compare.
41243     if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256, true) ||
41244                                checkBitcastSrcVectorSize(Src, 512, true))) {
41245       SExtVT = MVT::v8i32;
41246       PropagateSExt = true;
41247     }
41248     break;
41249   case MVT::v16i1:
41250     SExtVT = MVT::v16i8;
41251     // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
41252     // it is not profitable to sign-extend to 256-bit because this will
41253     // require an extra cross-lane shuffle which is more expensive than
41254     // truncating the result of the compare to 128-bits.
41255     break;
41256   case MVT::v32i1:
41257     SExtVT = MVT::v32i8;
41258     break;
41259   case MVT::v64i1:
41260     // If we have AVX512F, but not AVX512BW and the input is truncated from
41261     // v64i8 checked earlier. Then split the input and make two pmovmskbs.
41262     if (Subtarget.hasAVX512()) {
41263       if (Subtarget.hasBWI())
41264         return SDValue();
41265       SExtVT = MVT::v64i8;
41266       break;
41267     }
41268     // Split if this is a <64 x i8> comparison result.
41269     if (checkBitcastSrcVectorSize(Src, 512, false)) {
41270       SExtVT = MVT::v64i8;
41271       break;
41272     }
41273     return SDValue();
41274   };
41275 
41276   SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
41277                             : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
41278 
41279   if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
41280     V = getPMOVMSKB(DL, V, DAG, Subtarget);
41281   } else {
41282     if (SExtVT == MVT::v8i16)
41283       V = DAG.getNode(X86ISD::PACKSS, DL, MVT::v16i8, V,
41284                       DAG.getUNDEF(MVT::v8i16));
41285     V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
41286   }
41287 
41288   EVT IntVT =
41289       EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
41290   V = DAG.getZExtOrTrunc(V, DL, IntVT);
41291   return DAG.getBitcast(VT, V);
41292 }
41293 
41294 // Convert a vXi1 constant build vector to the same width scalar integer.
41295 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
41296   EVT SrcVT = Op.getValueType();
41297   assert(SrcVT.getVectorElementType() == MVT::i1 &&
41298          "Expected a vXi1 vector");
41299   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
41300          "Expected a constant build vector");
41301 
41302   APInt Imm(SrcVT.getVectorNumElements(), 0);
41303   for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
41304     SDValue In = Op.getOperand(Idx);
41305     if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
41306       Imm.setBit(Idx);
41307   }
41308   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
41309   return DAG.getConstant(Imm, SDLoc(Op), IntVT);
41310 }
41311 
41312 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
41313                                            TargetLowering::DAGCombinerInfo &DCI,
41314                                            const X86Subtarget &Subtarget) {
41315   assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
41316 
41317   if (!DCI.isBeforeLegalizeOps())
41318     return SDValue();
41319 
41320   // Only do this if we have k-registers.
41321   if (!Subtarget.hasAVX512())
41322     return SDValue();
41323 
41324   EVT DstVT = N->getValueType(0);
41325   SDValue Op = N->getOperand(0);
41326   EVT SrcVT = Op.getValueType();
41327 
41328   if (!Op.hasOneUse())
41329     return SDValue();
41330 
41331   // Look for logic ops.
41332   if (Op.getOpcode() != ISD::AND &&
41333       Op.getOpcode() != ISD::OR &&
41334       Op.getOpcode() != ISD::XOR)
41335     return SDValue();
41336 
41337   // Make sure we have a bitcast between mask registers and a scalar type.
41338   if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
41339         DstVT.isScalarInteger()) &&
41340       !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
41341         SrcVT.isScalarInteger()))
41342     return SDValue();
41343 
41344   SDValue LHS = Op.getOperand(0);
41345   SDValue RHS = Op.getOperand(1);
41346 
41347   if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
41348       LHS.getOperand(0).getValueType() == DstVT)
41349     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
41350                        DAG.getBitcast(DstVT, RHS));
41351 
41352   if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
41353       RHS.getOperand(0).getValueType() == DstVT)
41354     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
41355                        DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
41356 
41357   // If the RHS is a vXi1 build vector, this is a good reason to flip too.
41358   // Most of these have to move a constant from the scalar domain anyway.
41359   if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
41360     RHS = combinevXi1ConstantToInteger(RHS, DAG);
41361     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
41362                        DAG.getBitcast(DstVT, LHS), RHS);
41363   }
41364 
41365   return SDValue();
41366 }
41367 
41368 static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
41369                                     const X86Subtarget &Subtarget) {
41370   SDLoc DL(BV);
41371   unsigned NumElts = BV->getNumOperands();
41372   SDValue Splat = BV->getSplatValue();
41373 
41374   // Build MMX element from integer GPR or SSE float values.
41375   auto CreateMMXElement = [&](SDValue V) {
41376     if (V.isUndef())
41377       return DAG.getUNDEF(MVT::x86mmx);
41378     if (V.getValueType().isFloatingPoint()) {
41379       if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
41380         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
41381         V = DAG.getBitcast(MVT::v2i64, V);
41382         return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
41383       }
41384       V = DAG.getBitcast(MVT::i32, V);
41385     } else {
41386       V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
41387     }
41388     return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
41389   };
41390 
41391   // Convert build vector ops to MMX data in the bottom elements.
41392   SmallVector<SDValue, 8> Ops;
41393 
41394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41395 
41396   // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
41397   if (Splat) {
41398     if (Splat.isUndef())
41399       return DAG.getUNDEF(MVT::x86mmx);
41400 
41401     Splat = CreateMMXElement(Splat);
41402 
41403     if (Subtarget.hasSSE1()) {
41404       // Unpack v8i8 to splat i8 elements to lowest 16-bits.
41405       if (NumElts == 8)
41406         Splat = DAG.getNode(
41407             ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
41408             DAG.getTargetConstant(Intrinsic::x86_mmx_punpcklbw, DL,
41409                                   TLI.getPointerTy(DAG.getDataLayout())),
41410             Splat, Splat);
41411 
41412       // Use PSHUFW to repeat 16-bit elements.
41413       unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
41414       return DAG.getNode(
41415           ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
41416           DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL,
41417                                 TLI.getPointerTy(DAG.getDataLayout())),
41418           Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
41419     }
41420     Ops.append(NumElts, Splat);
41421   } else {
41422     for (unsigned i = 0; i != NumElts; ++i)
41423       Ops.push_back(CreateMMXElement(BV->getOperand(i)));
41424   }
41425 
41426   // Use tree of PUNPCKLs to build up general MMX vector.
41427   while (Ops.size() > 1) {
41428     unsigned NumOps = Ops.size();
41429     unsigned IntrinOp =
41430         (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
41431                      : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
41432                                     : Intrinsic::x86_mmx_punpcklbw));
41433     SDValue Intrin = DAG.getTargetConstant(
41434         IntrinOp, DL, TLI.getPointerTy(DAG.getDataLayout()));
41435     for (unsigned i = 0; i != NumOps; i += 2)
41436       Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
41437                                Ops[i], Ops[i + 1]);
41438     Ops.resize(NumOps / 2);
41439   }
41440 
41441   return Ops[0];
41442 }
41443 
41444 // Recursive function that attempts to find if a bool vector node was originally
41445 // a vector/float/double that got truncated/extended/bitcast to/from a scalar
41446 // integer. If so, replace the scalar ops with bool vector equivalents back down
41447 // the chain.
41448 static SDValue combineBitcastToBoolVector(EVT VT, SDValue V, const SDLoc &DL,
41449                                           SelectionDAG &DAG,
41450                                           const X86Subtarget &Subtarget) {
41451   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41452   unsigned Opc = V.getOpcode();
41453   switch (Opc) {
41454   case ISD::BITCAST: {
41455     // Bitcast from a vector/float/double, we can cheaply bitcast to VT.
41456     SDValue Src = V.getOperand(0);
41457     EVT SrcVT = Src.getValueType();
41458     if (SrcVT.isVector() || SrcVT.isFloatingPoint())
41459       return DAG.getBitcast(VT, Src);
41460     break;
41461   }
41462   case ISD::TRUNCATE: {
41463     // If we find a suitable source, a truncated scalar becomes a subvector.
41464     SDValue Src = V.getOperand(0);
41465     EVT NewSrcVT =
41466         EVT::getVectorVT(*DAG.getContext(), MVT::i1, Src.getValueSizeInBits());
41467     if (TLI.isTypeLegal(NewSrcVT))
41468       if (SDValue N0 =
41469               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
41470         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N0,
41471                            DAG.getIntPtrConstant(0, DL));
41472     break;
41473   }
41474   case ISD::ANY_EXTEND:
41475   case ISD::ZERO_EXTEND: {
41476     // If we find a suitable source, an extended scalar becomes a subvector.
41477     SDValue Src = V.getOperand(0);
41478     EVT NewSrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
41479                                     Src.getScalarValueSizeInBits());
41480     if (TLI.isTypeLegal(NewSrcVT))
41481       if (SDValue N0 =
41482               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
41483         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
41484                            Opc == ISD::ANY_EXTEND ? DAG.getUNDEF(VT)
41485                                                   : DAG.getConstant(0, DL, VT),
41486                            N0, DAG.getIntPtrConstant(0, DL));
41487     break;
41488   }
41489   case ISD::OR: {
41490     // If we find suitable sources, we can just move an OR to the vector domain.
41491     SDValue Src0 = V.getOperand(0);
41492     SDValue Src1 = V.getOperand(1);
41493     if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
41494       if (SDValue N1 = combineBitcastToBoolVector(VT, Src1, DL, DAG, Subtarget))
41495         return DAG.getNode(Opc, DL, VT, N0, N1);
41496     break;
41497   }
41498   case ISD::SHL: {
41499     // If we find a suitable source, a SHL becomes a KSHIFTL.
41500     SDValue Src0 = V.getOperand(0);
41501     if ((VT == MVT::v8i1 && !Subtarget.hasDQI()) ||
41502         ((VT == MVT::v32i1 || VT == MVT::v64i1) && !Subtarget.hasBWI()))
41503       break;
41504 
41505     if (auto *Amt = dyn_cast<ConstantSDNode>(V.getOperand(1)))
41506       if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
41507         return DAG.getNode(
41508             X86ISD::KSHIFTL, DL, VT, N0,
41509             DAG.getTargetConstant(Amt->getZExtValue(), DL, MVT::i8));
41510     break;
41511   }
41512   }
41513   return SDValue();
41514 }
41515 
41516 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
41517                               TargetLowering::DAGCombinerInfo &DCI,
41518                               const X86Subtarget &Subtarget) {
41519   SDValue N0 = N->getOperand(0);
41520   EVT VT = N->getValueType(0);
41521   EVT SrcVT = N0.getValueType();
41522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41523 
41524   // Try to match patterns such as
41525   // (i16 bitcast (v16i1 x))
41526   // ->
41527   // (i16 movmsk (16i8 sext (v16i1 x)))
41528   // before the setcc result is scalarized on subtargets that don't have legal
41529   // vxi1 types.
41530   if (DCI.isBeforeLegalize()) {
41531     SDLoc dl(N);
41532     if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
41533       return V;
41534 
41535     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
41536     // type, widen both sides to avoid a trip through memory.
41537     if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
41538         Subtarget.hasAVX512()) {
41539       N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
41540       N0 = DAG.getBitcast(MVT::v8i1, N0);
41541       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
41542                          DAG.getIntPtrConstant(0, dl));
41543     }
41544 
41545     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
41546     // type, widen both sides to avoid a trip through memory.
41547     if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
41548         Subtarget.hasAVX512()) {
41549       // Use zeros for the widening if we already have some zeroes. This can
41550       // allow SimplifyDemandedBits to remove scalar ANDs that may be down
41551       // stream of this.
41552       // FIXME: It might make sense to detect a concat_vectors with a mix of
41553       // zeroes and undef and turn it into insert_subvector for i1 vectors as
41554       // a separate combine. What we can't do is canonicalize the operands of
41555       // such a concat or we'll get into a loop with SimplifyDemandedBits.
41556       if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
41557         SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
41558         if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
41559           SrcVT = LastOp.getValueType();
41560           unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
41561           SmallVector<SDValue, 4> Ops(N0->op_begin(), N0->op_end());
41562           Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
41563           N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
41564           N0 = DAG.getBitcast(MVT::i8, N0);
41565           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
41566         }
41567       }
41568 
41569       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
41570       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
41571       Ops[0] = N0;
41572       N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
41573       N0 = DAG.getBitcast(MVT::i8, N0);
41574       return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
41575     }
41576   } else {
41577     // If we're bitcasting from iX to vXi1, see if the integer originally
41578     // began as a vXi1 and whether we can remove the bitcast entirely.
41579     if (VT.isVector() && VT.getScalarType() == MVT::i1 &&
41580         SrcVT.isScalarInteger() && TLI.isTypeLegal(VT)) {
41581       if (SDValue V =
41582               combineBitcastToBoolVector(VT, N0, SDLoc(N), DAG, Subtarget))
41583         return V;
41584     }
41585   }
41586 
41587   // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
41588   // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
41589   // due to insert_subvector legalization on KNL. By promoting the copy to i16
41590   // we can help with known bits propagation from the vXi1 domain to the
41591   // scalar domain.
41592   if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
41593       !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41594       N0.getOperand(0).getValueType() == MVT::v16i1 &&
41595       isNullConstant(N0.getOperand(1)))
41596     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
41597                        DAG.getBitcast(MVT::i16, N0.getOperand(0)));
41598 
41599   // Canonicalize (bitcast (vbroadcast_load)) so that the output of the bitcast
41600   // and the vbroadcast_load are both integer or both fp. In some cases this
41601   // will remove the bitcast entirely.
41602   if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
41603        VT.isFloatingPoint() != SrcVT.isFloatingPoint() && VT.isVector()) {
41604     auto *BCast = cast<MemIntrinsicSDNode>(N0);
41605     unsigned SrcVTSize = SrcVT.getScalarSizeInBits();
41606     unsigned MemSize = BCast->getMemoryVT().getScalarSizeInBits();
41607     // Don't swap i8/i16 since don't have fp types that size.
41608     if (MemSize >= 32) {
41609       MVT MemVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(MemSize)
41610                                        : MVT::getIntegerVT(MemSize);
41611       MVT LoadVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(SrcVTSize)
41612                                         : MVT::getIntegerVT(SrcVTSize);
41613       LoadVT = MVT::getVectorVT(LoadVT, SrcVT.getVectorNumElements());
41614 
41615       SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
41616       SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
41617       SDValue ResNode =
41618           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
41619                                   MemVT, BCast->getMemOperand());
41620       DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
41621       return DAG.getBitcast(VT, ResNode);
41622     }
41623   }
41624 
41625   // Since MMX types are special and don't usually play with other vector types,
41626   // it's better to handle them early to be sure we emit efficient code by
41627   // avoiding store-load conversions.
41628   if (VT == MVT::x86mmx) {
41629     // Detect MMX constant vectors.
41630     APInt UndefElts;
41631     SmallVector<APInt, 1> EltBits;
41632     if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
41633       SDLoc DL(N0);
41634       // Handle zero-extension of i32 with MOVD.
41635       if (EltBits[0].countLeadingZeros() >= 32)
41636         return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
41637                            DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
41638       // Else, bitcast to a double.
41639       // TODO - investigate supporting sext 32-bit immediates on x86_64.
41640       APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
41641       return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
41642     }
41643 
41644     // Detect bitcasts to x86mmx low word.
41645     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
41646         (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
41647         N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
41648       bool LowUndef = true, AllUndefOrZero = true;
41649       for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
41650         SDValue Op = N0.getOperand(i);
41651         LowUndef &= Op.isUndef() || (i >= e/2);
41652         AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
41653       }
41654       if (AllUndefOrZero) {
41655         SDValue N00 = N0.getOperand(0);
41656         SDLoc dl(N00);
41657         N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
41658                        : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
41659         return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
41660       }
41661     }
41662 
41663     // Detect bitcasts of 64-bit build vectors and convert to a
41664     // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
41665     // lowest element.
41666     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
41667         (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
41668          SrcVT == MVT::v8i8))
41669       return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
41670 
41671     // Detect bitcasts between element or subvector extraction to x86mmx.
41672     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
41673          N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
41674         isNullConstant(N0.getOperand(1))) {
41675       SDValue N00 = N0.getOperand(0);
41676       if (N00.getValueType().is128BitVector())
41677         return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
41678                            DAG.getBitcast(MVT::v2i64, N00));
41679     }
41680 
41681     // Detect bitcasts from FP_TO_SINT to x86mmx.
41682     if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
41683       SDLoc DL(N0);
41684       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
41685                                 DAG.getUNDEF(MVT::v2i32));
41686       return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
41687                          DAG.getBitcast(MVT::v2i64, Res));
41688     }
41689   }
41690 
41691   // Try to remove a bitcast of constant vXi1 vector. We have to legalize
41692   // most of these to scalar anyway.
41693   if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
41694       SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
41695       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
41696     return combinevXi1ConstantToInteger(N0, DAG);
41697   }
41698 
41699   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
41700       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
41701       isa<ConstantSDNode>(N0)) {
41702     auto *C = cast<ConstantSDNode>(N0);
41703     if (C->isAllOnes())
41704       return DAG.getConstant(1, SDLoc(N0), VT);
41705     if (C->isZero())
41706       return DAG.getConstant(0, SDLoc(N0), VT);
41707   }
41708 
41709   // Look for MOVMSK that is maybe truncated and then bitcasted to vXi1.
41710   // Turn it into a sign bit compare that produces a k-register. This avoids
41711   // a trip through a GPR.
41712   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
41713       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
41714       isPowerOf2_32(VT.getVectorNumElements())) {
41715     unsigned NumElts = VT.getVectorNumElements();
41716     SDValue Src = N0;
41717 
41718     // Peek through truncate.
41719     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
41720       Src = N0.getOperand(0);
41721 
41722     if (Src.getOpcode() == X86ISD::MOVMSK && Src.hasOneUse()) {
41723       SDValue MovmskIn = Src.getOperand(0);
41724       MVT MovmskVT = MovmskIn.getSimpleValueType();
41725       unsigned MovMskElts = MovmskVT.getVectorNumElements();
41726 
41727       // We allow extra bits of the movmsk to be used since they are known zero.
41728       // We can't convert a VPMOVMSKB without avx512bw.
41729       if (MovMskElts <= NumElts &&
41730           (Subtarget.hasBWI() || MovmskVT.getVectorElementType() != MVT::i8)) {
41731         EVT IntVT = EVT(MovmskVT).changeVectorElementTypeToInteger();
41732         MovmskIn = DAG.getBitcast(IntVT, MovmskIn);
41733         SDLoc dl(N);
41734         MVT CmpVT = MVT::getVectorVT(MVT::i1, MovMskElts);
41735         SDValue Cmp = DAG.getSetCC(dl, CmpVT, MovmskIn,
41736                                    DAG.getConstant(0, dl, IntVT), ISD::SETLT);
41737         if (EVT(CmpVT) == VT)
41738           return Cmp;
41739 
41740         // Pad with zeroes up to original VT to replace the zeroes that were
41741         // being used from the MOVMSK.
41742         unsigned NumConcats = NumElts / MovMskElts;
41743         SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, CmpVT));
41744         Ops[0] = Cmp;
41745         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Ops);
41746       }
41747     }
41748   }
41749 
41750   // Try to remove bitcasts from input and output of mask arithmetic to
41751   // remove GPR<->K-register crossings.
41752   if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
41753     return V;
41754 
41755   // Convert a bitcasted integer logic operation that has one bitcasted
41756   // floating-point operand into a floating-point logic operation. This may
41757   // create a load of a constant, but that is cheaper than materializing the
41758   // constant in an integer register and transferring it to an SSE register or
41759   // transferring the SSE operand to integer register and back.
41760   unsigned FPOpcode;
41761   switch (N0.getOpcode()) {
41762     case ISD::AND: FPOpcode = X86ISD::FAND; break;
41763     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
41764     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
41765     default: return SDValue();
41766   }
41767 
41768   // Check if we have a bitcast from another integer type as well.
41769   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
41770         (Subtarget.hasSSE2() && VT == MVT::f64) ||
41771         (Subtarget.hasFP16() && VT == MVT::f16) ||
41772         (Subtarget.hasSSE2() && VT.isInteger() && VT.isVector() &&
41773          TLI.isTypeLegal(VT))))
41774     return SDValue();
41775 
41776   SDValue LogicOp0 = N0.getOperand(0);
41777   SDValue LogicOp1 = N0.getOperand(1);
41778   SDLoc DL0(N0);
41779 
41780   // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
41781   if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
41782       LogicOp0.hasOneUse() && LogicOp0.getOperand(0).hasOneUse() &&
41783       LogicOp0.getOperand(0).getValueType() == VT &&
41784       !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
41785     SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
41786     unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
41787     return DAG.getNode(Opcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
41788   }
41789   // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
41790   if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
41791       LogicOp1.hasOneUse() && LogicOp1.getOperand(0).hasOneUse() &&
41792       LogicOp1.getOperand(0).getValueType() == VT &&
41793       !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
41794     SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
41795     unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
41796     return DAG.getNode(Opcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
41797   }
41798 
41799   return SDValue();
41800 }
41801 
41802 // Given a ABS node, detect the following pattern:
41803 // (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
41804 // This is useful as it is the input into a SAD pattern.
41805 static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
41806   SDValue AbsOp1 = Abs->getOperand(0);
41807   if (AbsOp1.getOpcode() != ISD::SUB)
41808     return false;
41809 
41810   Op0 = AbsOp1.getOperand(0);
41811   Op1 = AbsOp1.getOperand(1);
41812 
41813   // Check if the operands of the sub are zero-extended from vectors of i8.
41814   if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
41815       Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
41816       Op1.getOpcode() != ISD::ZERO_EXTEND ||
41817       Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
41818     return false;
41819 
41820   return true;
41821 }
41822 
41823 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
41824 // to these zexts.
41825 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
41826                             const SDValue &Zext1, const SDLoc &DL,
41827                             const X86Subtarget &Subtarget) {
41828   // Find the appropriate width for the PSADBW.
41829   EVT InVT = Zext0.getOperand(0).getValueType();
41830   unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
41831 
41832   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
41833   // fill in the missing vector elements with 0.
41834   unsigned NumConcat = RegSize / InVT.getSizeInBits();
41835   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
41836   Ops[0] = Zext0.getOperand(0);
41837   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
41838   SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
41839   Ops[0] = Zext1.getOperand(0);
41840   SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
41841 
41842   // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
41843   auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
41844                           ArrayRef<SDValue> Ops) {
41845     MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
41846     return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
41847   };
41848   MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
41849   return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
41850                           PSADBWBuilder);
41851 }
41852 
41853 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
41854 // PHMINPOSUW.
41855 static SDValue combineMinMaxReduction(SDNode *Extract, SelectionDAG &DAG,
41856                                       const X86Subtarget &Subtarget) {
41857   // Bail without SSE41.
41858   if (!Subtarget.hasSSE41())
41859     return SDValue();
41860 
41861   EVT ExtractVT = Extract->getValueType(0);
41862   if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
41863     return SDValue();
41864 
41865   // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
41866   ISD::NodeType BinOp;
41867   SDValue Src = DAG.matchBinOpReduction(
41868       Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
41869   if (!Src)
41870     return SDValue();
41871 
41872   EVT SrcVT = Src.getValueType();
41873   EVT SrcSVT = SrcVT.getScalarType();
41874   if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
41875     return SDValue();
41876 
41877   SDLoc DL(Extract);
41878   SDValue MinPos = Src;
41879 
41880   // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
41881   while (SrcVT.getSizeInBits() > 128) {
41882     SDValue Lo, Hi;
41883     std::tie(Lo, Hi) = splitVector(MinPos, DAG, DL);
41884     SrcVT = Lo.getValueType();
41885     MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
41886   }
41887   assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
41888           (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
41889          "Unexpected value type");
41890 
41891   // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
41892   // to flip the value accordingly.
41893   SDValue Mask;
41894   unsigned MaskEltsBits = ExtractVT.getSizeInBits();
41895   if (BinOp == ISD::SMAX)
41896     Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
41897   else if (BinOp == ISD::SMIN)
41898     Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
41899   else if (BinOp == ISD::UMAX)
41900     Mask = DAG.getAllOnesConstant(DL, SrcVT);
41901 
41902   if (Mask)
41903     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
41904 
41905   // For v16i8 cases we need to perform UMIN on pairs of byte elements,
41906   // shuffling each upper element down and insert zeros. This means that the
41907   // v16i8 UMIN will leave the upper element as zero, performing zero-extension
41908   // ready for the PHMINPOS.
41909   if (ExtractVT == MVT::i8) {
41910     SDValue Upper = DAG.getVectorShuffle(
41911         SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
41912         {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
41913     MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
41914   }
41915 
41916   // Perform the PHMINPOS on a v8i16 vector,
41917   MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
41918   MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
41919   MinPos = DAG.getBitcast(SrcVT, MinPos);
41920 
41921   if (Mask)
41922     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
41923 
41924   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
41925                      DAG.getIntPtrConstant(0, DL));
41926 }
41927 
41928 // Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
41929 static SDValue combinePredicateReduction(SDNode *Extract, SelectionDAG &DAG,
41930                                          const X86Subtarget &Subtarget) {
41931   // Bail without SSE2.
41932   if (!Subtarget.hasSSE2())
41933     return SDValue();
41934 
41935   EVT ExtractVT = Extract->getValueType(0);
41936   unsigned BitWidth = ExtractVT.getSizeInBits();
41937   if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
41938       ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
41939     return SDValue();
41940 
41941   // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
41942   ISD::NodeType BinOp;
41943   SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
41944   if (!Match && ExtractVT == MVT::i1)
41945     Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
41946   if (!Match)
41947     return SDValue();
41948 
41949   // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
41950   // which we can't support here for now.
41951   if (Match.getScalarValueSizeInBits() != BitWidth)
41952     return SDValue();
41953 
41954   SDValue Movmsk;
41955   SDLoc DL(Extract);
41956   EVT MatchVT = Match.getValueType();
41957   unsigned NumElts = MatchVT.getVectorNumElements();
41958   unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
41959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41960 
41961   if (ExtractVT == MVT::i1) {
41962     // Special case for (pre-legalization) vXi1 reductions.
41963     if (NumElts > 64 || !isPowerOf2_32(NumElts))
41964       return SDValue();
41965     if (TLI.isTypeLegal(MatchVT)) {
41966       // If this is a legal AVX512 predicate type then we can just bitcast.
41967       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
41968       Movmsk = DAG.getBitcast(MovmskVT, Match);
41969     } else {
41970       // For all_of(setcc(vec,0,eq)) - avoid vXi64 comparisons if we don't have
41971       // PCMPEQQ (SSE41+), use PCMPEQD instead.
41972       if (BinOp == ISD::AND && !Subtarget.hasSSE41() &&
41973           Match.getOpcode() == ISD::SETCC &&
41974           ISD::isBuildVectorAllZeros(Match.getOperand(1).getNode()) &&
41975           cast<CondCodeSDNode>(Match.getOperand(2))->get() ==
41976               ISD::CondCode::SETEQ) {
41977         SDValue Vec = Match.getOperand(0);
41978         if (Vec.getValueType().getScalarType() == MVT::i64 &&
41979             (2 * NumElts) <= MaxElts) {
41980           NumElts *= 2;
41981           EVT CmpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
41982           MatchVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
41983           Match = DAG.getSetCC(
41984               DL, MatchVT, DAG.getBitcast(CmpVT, Match.getOperand(0)),
41985               DAG.getBitcast(CmpVT, Match.getOperand(1)), ISD::CondCode::SETEQ);
41986         }
41987       }
41988 
41989       // Use combineBitcastvxi1 to create the MOVMSK.
41990       while (NumElts > MaxElts) {
41991         SDValue Lo, Hi;
41992         std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
41993         Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
41994         NumElts /= 2;
41995       }
41996       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
41997       Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
41998     }
41999     if (!Movmsk)
42000       return SDValue();
42001     Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
42002   } else {
42003     // FIXME: Better handling of k-registers or 512-bit vectors?
42004     unsigned MatchSizeInBits = Match.getValueSizeInBits();
42005     if (!(MatchSizeInBits == 128 ||
42006           (MatchSizeInBits == 256 && Subtarget.hasAVX())))
42007       return SDValue();
42008 
42009     // Make sure this isn't a vector of 1 element. The perf win from using
42010     // MOVMSK diminishes with less elements in the reduction, but it is
42011     // generally better to get the comparison over to the GPRs as soon as
42012     // possible to reduce the number of vector ops.
42013     if (Match.getValueType().getVectorNumElements() < 2)
42014       return SDValue();
42015 
42016     // Check that we are extracting a reduction of all sign bits.
42017     if (DAG.ComputeNumSignBits(Match) != BitWidth)
42018       return SDValue();
42019 
42020     if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
42021       SDValue Lo, Hi;
42022       std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
42023       Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
42024       MatchSizeInBits = Match.getValueSizeInBits();
42025     }
42026 
42027     // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
42028     MVT MaskSrcVT;
42029     if (64 == BitWidth || 32 == BitWidth)
42030       MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
42031                                    MatchSizeInBits / BitWidth);
42032     else
42033       MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
42034 
42035     SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
42036     Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
42037     NumElts = MaskSrcVT.getVectorNumElements();
42038   }
42039   assert((NumElts <= 32 || NumElts == 64) &&
42040          "Not expecting more than 64 elements");
42041 
42042   MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
42043   if (BinOp == ISD::XOR) {
42044     // parity -> (PARITY(MOVMSK X))
42045     SDValue Result = DAG.getNode(ISD::PARITY, DL, CmpVT, Movmsk);
42046     return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
42047   }
42048 
42049   SDValue CmpC;
42050   ISD::CondCode CondCode;
42051   if (BinOp == ISD::OR) {
42052     // any_of -> MOVMSK != 0
42053     CmpC = DAG.getConstant(0, DL, CmpVT);
42054     CondCode = ISD::CondCode::SETNE;
42055   } else {
42056     // all_of -> MOVMSK == ((1 << NumElts) - 1)
42057     CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
42058                            DL, CmpVT);
42059     CondCode = ISD::CondCode::SETEQ;
42060   }
42061 
42062   // The setcc produces an i8 of 0/1, so extend that to the result width and
42063   // negate to get the final 0/-1 mask value.
42064   EVT SetccVT =
42065       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
42066   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
42067   SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
42068   SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
42069   return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
42070 }
42071 
42072 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
42073                                       const X86Subtarget &Subtarget) {
42074   // PSADBW is only supported on SSE2 and up.
42075   if (!Subtarget.hasSSE2())
42076     return SDValue();
42077 
42078   EVT ExtractVT = Extract->getValueType(0);
42079   // Verify the type we're extracting is either i32 or i64.
42080   // FIXME: Could support other types, but this is what we have coverage for.
42081   if (ExtractVT != MVT::i32 && ExtractVT != MVT::i64)
42082     return SDValue();
42083 
42084   EVT VT = Extract->getOperand(0).getValueType();
42085   if (!isPowerOf2_32(VT.getVectorNumElements()))
42086     return SDValue();
42087 
42088   // Match shuffle + add pyramid.
42089   ISD::NodeType BinOp;
42090   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
42091 
42092   // The operand is expected to be zero extended from i8
42093   // (verified in detectZextAbsDiff).
42094   // In order to convert to i64 and above, additional any/zero/sign
42095   // extend is expected.
42096   // The zero extend from 32 bit has no mathematical effect on the result.
42097   // Also the sign extend is basically zero extend
42098   // (extends the sign bit which is zero).
42099   // So it is correct to skip the sign/zero extend instruction.
42100   if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
42101                Root.getOpcode() == ISD::ZERO_EXTEND ||
42102                Root.getOpcode() == ISD::ANY_EXTEND))
42103     Root = Root.getOperand(0);
42104 
42105   // If there was a match, we want Root to be a select that is the root of an
42106   // abs-diff pattern.
42107   if (!Root || Root.getOpcode() != ISD::ABS)
42108     return SDValue();
42109 
42110   // Check whether we have an abs-diff pattern feeding into the select.
42111   SDValue Zext0, Zext1;
42112   if (!detectZextAbsDiff(Root, Zext0, Zext1))
42113     return SDValue();
42114 
42115   // Create the SAD instruction.
42116   SDLoc DL(Extract);
42117   SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
42118 
42119   // If the original vector was wider than 8 elements, sum over the results
42120   // in the SAD vector.
42121   unsigned Stages = Log2_32(VT.getVectorNumElements());
42122   EVT SadVT = SAD.getValueType();
42123   if (Stages > 3) {
42124     unsigned SadElems = SadVT.getVectorNumElements();
42125 
42126     for(unsigned i = Stages - 3; i > 0; --i) {
42127       SmallVector<int, 16> Mask(SadElems, -1);
42128       for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
42129         Mask[j] = MaskEnd + j;
42130 
42131       SDValue Shuffle =
42132           DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
42133       SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
42134     }
42135   }
42136 
42137   unsigned ExtractSizeInBits = ExtractVT.getSizeInBits();
42138   // Return the lowest ExtractSizeInBits bits.
42139   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), ExtractVT,
42140                                SadVT.getSizeInBits() / ExtractSizeInBits);
42141   SAD = DAG.getBitcast(ResVT, SAD);
42142   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, SAD,
42143                      Extract->getOperand(1));
42144 }
42145 
42146 // Attempt to peek through a target shuffle and extract the scalar from the
42147 // source.
42148 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
42149                                          TargetLowering::DAGCombinerInfo &DCI,
42150                                          const X86Subtarget &Subtarget) {
42151   if (DCI.isBeforeLegalizeOps())
42152     return SDValue();
42153 
42154   SDLoc dl(N);
42155   SDValue Src = N->getOperand(0);
42156   SDValue Idx = N->getOperand(1);
42157 
42158   EVT VT = N->getValueType(0);
42159   EVT SrcVT = Src.getValueType();
42160   EVT SrcSVT = SrcVT.getVectorElementType();
42161   unsigned SrcEltBits = SrcSVT.getSizeInBits();
42162   unsigned NumSrcElts = SrcVT.getVectorNumElements();
42163 
42164   // Don't attempt this for boolean mask vectors or unknown extraction indices.
42165   if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
42166     return SDValue();
42167 
42168   const APInt &IdxC = N->getConstantOperandAPInt(1);
42169   if (IdxC.uge(NumSrcElts))
42170     return SDValue();
42171 
42172   SDValue SrcBC = peekThroughBitcasts(Src);
42173 
42174   // Handle extract(bitcast(broadcast(scalar_value))).
42175   if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
42176     SDValue SrcOp = SrcBC.getOperand(0);
42177     EVT SrcOpVT = SrcOp.getValueType();
42178     if (SrcOpVT.isScalarInteger() && VT.isInteger() &&
42179         (SrcOpVT.getSizeInBits() % SrcEltBits) == 0) {
42180       unsigned Scale = SrcOpVT.getSizeInBits() / SrcEltBits;
42181       unsigned Offset = IdxC.urem(Scale) * SrcEltBits;
42182       // TODO support non-zero offsets.
42183       if (Offset == 0) {
42184         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, SrcVT.getScalarType());
42185         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, VT);
42186         return SrcOp;
42187       }
42188     }
42189   }
42190 
42191   // If we're extracting a single element from a broadcast load and there are
42192   // no other users, just create a single load.
42193   if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
42194     auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
42195     unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
42196     if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
42197         VT.getSizeInBits() == SrcBCWidth && SrcEltBits == SrcBCWidth) {
42198       SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
42199                                  MemIntr->getBasePtr(),
42200                                  MemIntr->getPointerInfo(),
42201                                  MemIntr->getOriginalAlign(),
42202                                  MemIntr->getMemOperand()->getFlags());
42203       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
42204       return Load;
42205     }
42206   }
42207 
42208   // Handle extract(bitcast(scalar_to_vector(scalar_value))) for integers.
42209   // TODO: Move to DAGCombine?
42210   if (SrcBC.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isInteger() &&
42211       SrcBC.getValueType().isInteger() &&
42212       (SrcBC.getScalarValueSizeInBits() % SrcEltBits) == 0 &&
42213       SrcBC.getScalarValueSizeInBits() ==
42214           SrcBC.getOperand(0).getValueSizeInBits()) {
42215     unsigned Scale = SrcBC.getScalarValueSizeInBits() / SrcEltBits;
42216     if (IdxC.ult(Scale)) {
42217       unsigned Offset = IdxC.getZExtValue() * SrcVT.getScalarSizeInBits();
42218       SDValue Scl = SrcBC.getOperand(0);
42219       EVT SclVT = Scl.getValueType();
42220       if (Offset) {
42221         Scl = DAG.getNode(ISD::SRL, dl, SclVT, Scl,
42222                           DAG.getShiftAmountConstant(Offset, SclVT, dl));
42223       }
42224       Scl = DAG.getZExtOrTrunc(Scl, dl, SrcVT.getScalarType());
42225       Scl = DAG.getZExtOrTrunc(Scl, dl, VT);
42226       return Scl;
42227     }
42228   }
42229 
42230   // Handle extract(truncate(x)) for 0'th index.
42231   // TODO: Treat this as a faux shuffle?
42232   // TODO: When can we use this for general indices?
42233   if (ISD::TRUNCATE == Src.getOpcode() && IdxC == 0 &&
42234       (SrcVT.getSizeInBits() % 128) == 0) {
42235     Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
42236     MVT ExtractVT = MVT::getVectorVT(SrcSVT.getSimpleVT(), 128 / SrcEltBits);
42237     return DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(ExtractVT, Src),
42238                        Idx);
42239   }
42240 
42241   // We can only legally extract other elements from 128-bit vectors and in
42242   // certain circumstances, depending on SSE-level.
42243   // TODO: Investigate float/double extraction if it will be just stored.
42244   auto GetLegalExtract = [&Subtarget, &DAG, &dl](SDValue Vec, EVT VecVT,
42245                                                  unsigned Idx) {
42246     EVT VecSVT = VecVT.getScalarType();
42247     if ((VecVT.is256BitVector() || VecVT.is512BitVector()) &&
42248         (VecSVT == MVT::i8 || VecSVT == MVT::i16 || VecSVT == MVT::i32 ||
42249          VecSVT == MVT::i64)) {
42250       unsigned EltSizeInBits = VecSVT.getSizeInBits();
42251       unsigned NumEltsPerLane = 128 / EltSizeInBits;
42252       unsigned LaneOffset = (Idx & ~(NumEltsPerLane - 1)) * EltSizeInBits;
42253       unsigned LaneIdx = LaneOffset / Vec.getScalarValueSizeInBits();
42254       VecVT = EVT::getVectorVT(*DAG.getContext(), VecSVT, NumEltsPerLane);
42255       Vec = extract128BitVector(Vec, LaneIdx, DAG, dl);
42256       Idx &= (NumEltsPerLane - 1);
42257     }
42258     if ((VecVT == MVT::v4i32 || VecVT == MVT::v2i64) &&
42259         ((Idx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
42260       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VecVT.getScalarType(),
42261                          DAG.getBitcast(VecVT, Vec),
42262                          DAG.getIntPtrConstant(Idx, dl));
42263     }
42264     if ((VecVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
42265         (VecVT == MVT::v16i8 && Subtarget.hasSSE41())) {
42266       unsigned OpCode = (VecVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
42267       return DAG.getNode(OpCode, dl, MVT::i32, DAG.getBitcast(VecVT, Vec),
42268                          DAG.getTargetConstant(Idx, dl, MVT::i8));
42269     }
42270     return SDValue();
42271   };
42272 
42273   // Resolve the target shuffle inputs and mask.
42274   SmallVector<int, 16> Mask;
42275   SmallVector<SDValue, 2> Ops;
42276   if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
42277     return SDValue();
42278 
42279   // Shuffle inputs must be the same size as the result.
42280   if (llvm::any_of(Ops, [SrcVT](SDValue Op) {
42281         return SrcVT.getSizeInBits() != Op.getValueSizeInBits();
42282       }))
42283     return SDValue();
42284 
42285   // Attempt to narrow/widen the shuffle mask to the correct size.
42286   if (Mask.size() != NumSrcElts) {
42287     if ((NumSrcElts % Mask.size()) == 0) {
42288       SmallVector<int, 16> ScaledMask;
42289       int Scale = NumSrcElts / Mask.size();
42290       narrowShuffleMaskElts(Scale, Mask, ScaledMask);
42291       Mask = std::move(ScaledMask);
42292     } else if ((Mask.size() % NumSrcElts) == 0) {
42293       // Simplify Mask based on demanded element.
42294       int ExtractIdx = (int)IdxC.getZExtValue();
42295       int Scale = Mask.size() / NumSrcElts;
42296       int Lo = Scale * ExtractIdx;
42297       int Hi = Scale * (ExtractIdx + 1);
42298       for (int i = 0, e = (int)Mask.size(); i != e; ++i)
42299         if (i < Lo || Hi <= i)
42300           Mask[i] = SM_SentinelUndef;
42301 
42302       SmallVector<int, 16> WidenedMask;
42303       while (Mask.size() > NumSrcElts &&
42304              canWidenShuffleElements(Mask, WidenedMask))
42305         Mask = std::move(WidenedMask);
42306     }
42307   }
42308 
42309   // If narrowing/widening failed, see if we can extract+zero-extend.
42310   int ExtractIdx;
42311   EVT ExtractVT;
42312   if (Mask.size() == NumSrcElts) {
42313     ExtractIdx = Mask[IdxC.getZExtValue()];
42314     ExtractVT = SrcVT;
42315   } else {
42316     unsigned Scale = Mask.size() / NumSrcElts;
42317     if ((Mask.size() % NumSrcElts) != 0 || SrcVT.isFloatingPoint())
42318       return SDValue();
42319     unsigned ScaledIdx = Scale * IdxC.getZExtValue();
42320     if (!isUndefOrZeroInRange(Mask, ScaledIdx + 1, Scale - 1))
42321       return SDValue();
42322     ExtractIdx = Mask[ScaledIdx];
42323     EVT ExtractSVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltBits / Scale);
42324     ExtractVT = EVT::getVectorVT(*DAG.getContext(), ExtractSVT, Mask.size());
42325     assert(SrcVT.getSizeInBits() == ExtractVT.getSizeInBits() &&
42326            "Failed to widen vector type");
42327   }
42328 
42329   // If the shuffle source element is undef/zero then we can just accept it.
42330   if (ExtractIdx == SM_SentinelUndef)
42331     return DAG.getUNDEF(VT);
42332 
42333   if (ExtractIdx == SM_SentinelZero)
42334     return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
42335                                 : DAG.getConstant(0, dl, VT);
42336 
42337   SDValue SrcOp = Ops[ExtractIdx / Mask.size()];
42338   ExtractIdx = ExtractIdx % Mask.size();
42339   if (SDValue V = GetLegalExtract(SrcOp, ExtractVT, ExtractIdx))
42340     return DAG.getZExtOrTrunc(V, dl, VT);
42341 
42342   return SDValue();
42343 }
42344 
42345 /// Extracting a scalar FP value from vector element 0 is free, so extract each
42346 /// operand first, then perform the math as a scalar op.
42347 static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG,
42348                                  const X86Subtarget &Subtarget) {
42349   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract");
42350   SDValue Vec = ExtElt->getOperand(0);
42351   SDValue Index = ExtElt->getOperand(1);
42352   EVT VT = ExtElt->getValueType(0);
42353   EVT VecVT = Vec.getValueType();
42354 
42355   // TODO: If this is a unary/expensive/expand op, allow extraction from a
42356   // non-zero element because the shuffle+scalar op will be cheaper?
42357   if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
42358     return SDValue();
42359 
42360   // Vector FP compares don't fit the pattern of FP math ops (propagate, not
42361   // extract, the condition code), so deal with those as a special-case.
42362   if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
42363     EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
42364     if (OpVT != MVT::f32 && OpVT != MVT::f64)
42365       return SDValue();
42366 
42367     // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
42368     SDLoc DL(ExtElt);
42369     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
42370                                Vec.getOperand(0), Index);
42371     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
42372                                Vec.getOperand(1), Index);
42373     return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
42374   }
42375 
42376   if (!(VT == MVT::f16 && Subtarget.hasFP16()) && VT != MVT::f32 &&
42377       VT != MVT::f64)
42378     return SDValue();
42379 
42380   // Vector FP selects don't fit the pattern of FP math ops (because the
42381   // condition has a different type and we have to change the opcode), so deal
42382   // with those here.
42383   // FIXME: This is restricted to pre type legalization by ensuring the setcc
42384   // has i1 elements. If we loosen this we need to convert vector bool to a
42385   // scalar bool.
42386   if (Vec.getOpcode() == ISD::VSELECT &&
42387       Vec.getOperand(0).getOpcode() == ISD::SETCC &&
42388       Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
42389       Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
42390     // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
42391     SDLoc DL(ExtElt);
42392     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
42393                                Vec.getOperand(0).getValueType().getScalarType(),
42394                                Vec.getOperand(0), Index);
42395     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
42396                                Vec.getOperand(1), Index);
42397     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
42398                                Vec.getOperand(2), Index);
42399     return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
42400   }
42401 
42402   // TODO: This switch could include FNEG and the x86-specific FP logic ops
42403   // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
42404   // missed load folding and fma+fneg combining.
42405   switch (Vec.getOpcode()) {
42406   case ISD::FMA: // Begin 3 operands
42407   case ISD::FMAD:
42408   case ISD::FADD: // Begin 2 operands
42409   case ISD::FSUB:
42410   case ISD::FMUL:
42411   case ISD::FDIV:
42412   case ISD::FREM:
42413   case ISD::FCOPYSIGN:
42414   case ISD::FMINNUM:
42415   case ISD::FMAXNUM:
42416   case ISD::FMINNUM_IEEE:
42417   case ISD::FMAXNUM_IEEE:
42418   case ISD::FMAXIMUM:
42419   case ISD::FMINIMUM:
42420   case X86ISD::FMAX:
42421   case X86ISD::FMIN:
42422   case ISD::FABS: // Begin 1 operand
42423   case ISD::FSQRT:
42424   case ISD::FRINT:
42425   case ISD::FCEIL:
42426   case ISD::FTRUNC:
42427   case ISD::FNEARBYINT:
42428   case ISD::FROUND:
42429   case ISD::FFLOOR:
42430   case X86ISD::FRCP:
42431   case X86ISD::FRSQRT: {
42432     // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
42433     SDLoc DL(ExtElt);
42434     SmallVector<SDValue, 4> ExtOps;
42435     for (SDValue Op : Vec->ops())
42436       ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
42437     return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
42438   }
42439   default:
42440     return SDValue();
42441   }
42442   llvm_unreachable("All opcodes should return within switch");
42443 }
42444 
42445 /// Try to convert a vector reduction sequence composed of binops and shuffles
42446 /// into horizontal ops.
42447 static SDValue combineArithReduction(SDNode *ExtElt, SelectionDAG &DAG,
42448                                      const X86Subtarget &Subtarget) {
42449   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller");
42450 
42451   // We need at least SSE2 to anything here.
42452   if (!Subtarget.hasSSE2())
42453     return SDValue();
42454 
42455   ISD::NodeType Opc;
42456   SDValue Rdx = DAG.matchBinOpReduction(ExtElt, Opc,
42457                                         {ISD::ADD, ISD::MUL, ISD::FADD}, true);
42458   if (!Rdx)
42459     return SDValue();
42460 
42461   SDValue Index = ExtElt->getOperand(1);
42462   assert(isNullConstant(Index) &&
42463          "Reduction doesn't end in an extract from index 0");
42464 
42465   EVT VT = ExtElt->getValueType(0);
42466   EVT VecVT = Rdx.getValueType();
42467   if (VecVT.getScalarType() != VT)
42468     return SDValue();
42469 
42470   SDLoc DL(ExtElt);
42471 
42472   // vXi8 mul reduction - promote to vXi16 mul reduction.
42473   if (Opc == ISD::MUL) {
42474     unsigned NumElts = VecVT.getVectorNumElements();
42475     if (VT != MVT::i8 || NumElts < 4 || !isPowerOf2_32(NumElts))
42476       return SDValue();
42477     if (VecVT.getSizeInBits() >= 128) {
42478       EVT WideVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts / 2);
42479       SDValue Lo = getUnpackl(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
42480       SDValue Hi = getUnpackh(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
42481       Lo = DAG.getBitcast(WideVT, Lo);
42482       Hi = DAG.getBitcast(WideVT, Hi);
42483       Rdx = DAG.getNode(Opc, DL, WideVT, Lo, Hi);
42484       while (Rdx.getValueSizeInBits() > 128) {
42485         std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
42486         Rdx = DAG.getNode(Opc, DL, Lo.getValueType(), Lo, Hi);
42487       }
42488     } else {
42489       if (VecVT == MVT::v4i8)
42490         Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rdx,
42491                           DAG.getUNDEF(MVT::v4i8));
42492       Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Rdx,
42493                         DAG.getUNDEF(MVT::v8i8));
42494       Rdx = getUnpackl(DAG, DL, MVT::v16i8, Rdx, DAG.getUNDEF(MVT::v16i8));
42495       Rdx = DAG.getBitcast(MVT::v8i16, Rdx);
42496     }
42497     if (NumElts >= 8)
42498       Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
42499                         DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
42500                                              {4, 5, 6, 7, -1, -1, -1, -1}));
42501     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
42502                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
42503                                            {2, 3, -1, -1, -1, -1, -1, -1}));
42504     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
42505                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
42506                                            {1, -1, -1, -1, -1, -1, -1, -1}));
42507     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
42508     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
42509   }
42510 
42511   // vXi8 add reduction - sub 128-bit vector.
42512   if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
42513     if (VecVT == MVT::v4i8) {
42514       // Pad with zero.
42515       if (Subtarget.hasSSE41()) {
42516         Rdx = DAG.getBitcast(MVT::i32, Rdx);
42517         Rdx = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
42518                           DAG.getConstant(0, DL, MVT::v4i32), Rdx,
42519                           DAG.getIntPtrConstant(0, DL));
42520         Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
42521       } else {
42522         Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rdx,
42523                           DAG.getConstant(0, DL, VecVT));
42524       }
42525     }
42526     if (Rdx.getValueType() == MVT::v8i8) {
42527       // Pad with undef.
42528       Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Rdx,
42529                         DAG.getUNDEF(MVT::v8i8));
42530     }
42531     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
42532                       DAG.getConstant(0, DL, MVT::v16i8));
42533     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
42534     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
42535   }
42536 
42537   // Must be a >=128-bit vector with pow2 elements.
42538   if ((VecVT.getSizeInBits() % 128) != 0 ||
42539       !isPowerOf2_32(VecVT.getVectorNumElements()))
42540     return SDValue();
42541 
42542   // vXi8 add reduction - sum lo/hi halves then use PSADBW.
42543   if (VT == MVT::i8) {
42544     while (Rdx.getValueSizeInBits() > 128) {
42545       SDValue Lo, Hi;
42546       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
42547       VecVT = Lo.getValueType();
42548       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
42549     }
42550     assert(VecVT == MVT::v16i8 && "v16i8 reduction expected");
42551 
42552     SDValue Hi = DAG.getVectorShuffle(
42553         MVT::v16i8, DL, Rdx, Rdx,
42554         {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
42555     Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
42556     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
42557                       getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
42558     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
42559     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
42560   }
42561 
42562   // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
42563   if (!shouldUseHorizontalOp(true, DAG, Subtarget))
42564     return SDValue();
42565 
42566   unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
42567 
42568   // 256-bit horizontal instructions operate on 128-bit chunks rather than
42569   // across the whole vector, so we need an extract + hop preliminary stage.
42570   // This is the only step where the operands of the hop are not the same value.
42571   // TODO: We could extend this to handle 512-bit or even longer vectors.
42572   if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
42573       ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
42574     unsigned NumElts = VecVT.getVectorNumElements();
42575     SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
42576     SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
42577     Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
42578     VecVT = Rdx.getValueType();
42579   }
42580   if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
42581       !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
42582     return SDValue();
42583 
42584   // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
42585   unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
42586   for (unsigned i = 0; i != ReductionSteps; ++i)
42587     Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
42588 
42589   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
42590 }
42591 
42592 /// Detect vector gather/scatter index generation and convert it from being a
42593 /// bunch of shuffles and extracts into a somewhat faster sequence.
42594 /// For i686, the best sequence is apparently storing the value and loading
42595 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
42596 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
42597                                        TargetLowering::DAGCombinerInfo &DCI,
42598                                        const X86Subtarget &Subtarget) {
42599   if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
42600     return NewOp;
42601 
42602   SDValue InputVector = N->getOperand(0);
42603   SDValue EltIdx = N->getOperand(1);
42604   auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
42605 
42606   EVT SrcVT = InputVector.getValueType();
42607   EVT VT = N->getValueType(0);
42608   SDLoc dl(InputVector);
42609   bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
42610   unsigned NumSrcElts = SrcVT.getVectorNumElements();
42611 
42612   if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
42613     return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
42614 
42615   // Integer Constant Folding.
42616   if (CIdx && VT.isInteger()) {
42617     APInt UndefVecElts;
42618     SmallVector<APInt, 16> EltBits;
42619     unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
42620     if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
42621                                       EltBits, true, false)) {
42622       uint64_t Idx = CIdx->getZExtValue();
42623       if (UndefVecElts[Idx])
42624         return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
42625       return DAG.getConstant(EltBits[Idx].zextOrSelf(VT.getScalarSizeInBits()),
42626                              dl, VT);
42627     }
42628   }
42629 
42630   if (IsPextr) {
42631     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42632     if (TLI.SimplifyDemandedBits(SDValue(N, 0),
42633                                  APInt::getAllOnes(VT.getSizeInBits()), DCI))
42634       return SDValue(N, 0);
42635 
42636     // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
42637     if ((InputVector.getOpcode() == X86ISD::PINSRB ||
42638          InputVector.getOpcode() == X86ISD::PINSRW) &&
42639         InputVector.getOperand(2) == EltIdx) {
42640       assert(SrcVT == InputVector.getOperand(0).getValueType() &&
42641              "Vector type mismatch");
42642       SDValue Scl = InputVector.getOperand(1);
42643       Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
42644       return DAG.getZExtOrTrunc(Scl, dl, VT);
42645     }
42646 
42647     // TODO - Remove this once we can handle the implicit zero-extension of
42648     // X86ISD::PEXTRW/X86ISD::PEXTRB in combinePredicateReduction and
42649     // combineBasicSADPattern.
42650     return SDValue();
42651   }
42652 
42653   // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
42654   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
42655       VT == MVT::i64 && SrcVT == MVT::v1i64 && isNullConstant(EltIdx)) {
42656     SDValue MMXSrc = InputVector.getOperand(0);
42657 
42658     // The bitcast source is a direct mmx result.
42659     if (MMXSrc.getValueType() == MVT::x86mmx)
42660       return DAG.getBitcast(VT, InputVector);
42661   }
42662 
42663   // Detect mmx to i32 conversion through a v2i32 elt extract.
42664   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
42665       VT == MVT::i32 && SrcVT == MVT::v2i32 && isNullConstant(EltIdx)) {
42666     SDValue MMXSrc = InputVector.getOperand(0);
42667 
42668     // The bitcast source is a direct mmx result.
42669     if (MMXSrc.getValueType() == MVT::x86mmx)
42670       return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
42671   }
42672 
42673   // Check whether this extract is the root of a sum of absolute differences
42674   // pattern. This has to be done here because we really want it to happen
42675   // pre-legalization,
42676   if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
42677     return SAD;
42678 
42679   // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
42680   if (SDValue Cmp = combinePredicateReduction(N, DAG, Subtarget))
42681     return Cmp;
42682 
42683   // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
42684   if (SDValue MinMax = combineMinMaxReduction(N, DAG, Subtarget))
42685     return MinMax;
42686 
42687   // Attempt to optimize ADD/FADD/MUL reductions with HADD, promotion etc..
42688   if (SDValue V = combineArithReduction(N, DAG, Subtarget))
42689     return V;
42690 
42691   if (SDValue V = scalarizeExtEltFP(N, DAG, Subtarget))
42692     return V;
42693 
42694   // Attempt to extract a i1 element by using MOVMSK to extract the signbits
42695   // and then testing the relevant element.
42696   //
42697   // Note that we only combine extracts on the *same* result number, i.e.
42698   //   t0 = merge_values a0, a1, a2, a3
42699   //   i1 = extract_vector_elt t0, Constant:i64<2>
42700   //   i1 = extract_vector_elt t0, Constant:i64<3>
42701   // but not
42702   //   i1 = extract_vector_elt t0:1, Constant:i64<2>
42703   // since the latter would need its own MOVMSK.
42704   if (CIdx && SrcVT.getScalarType() == MVT::i1) {
42705     SmallVector<SDNode *, 16> BoolExtracts;
42706     unsigned ResNo = InputVector.getResNo();
42707     auto IsBoolExtract = [&BoolExtracts, &ResNo](SDNode *Use) {
42708       if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
42709           isa<ConstantSDNode>(Use->getOperand(1)) &&
42710           Use->getOperand(0).getResNo() == ResNo &&
42711           Use->getValueType(0) == MVT::i1) {
42712         BoolExtracts.push_back(Use);
42713         return true;
42714       }
42715       return false;
42716     };
42717     if (all_of(InputVector->uses(), IsBoolExtract) &&
42718         BoolExtracts.size() > 1) {
42719       EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
42720       if (SDValue BC =
42721               combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
42722         for (SDNode *Use : BoolExtracts) {
42723           // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
42724           unsigned MaskIdx = Use->getConstantOperandVal(1);
42725           APInt MaskBit = APInt::getOneBitSet(NumSrcElts, MaskIdx);
42726           SDValue Mask = DAG.getConstant(MaskBit, dl, BCVT);
42727           SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
42728           Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
42729           DCI.CombineTo(Use, Res);
42730         }
42731         return SDValue(N, 0);
42732       }
42733     }
42734   }
42735 
42736   return SDValue();
42737 }
42738 
42739 /// If a vector select has an operand that is -1 or 0, try to simplify the
42740 /// select to a bitwise logic operation.
42741 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
42742 static SDValue
42743 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
42744                                  TargetLowering::DAGCombinerInfo &DCI,
42745                                  const X86Subtarget &Subtarget) {
42746   SDValue Cond = N->getOperand(0);
42747   SDValue LHS = N->getOperand(1);
42748   SDValue RHS = N->getOperand(2);
42749   EVT VT = LHS.getValueType();
42750   EVT CondVT = Cond.getValueType();
42751   SDLoc DL(N);
42752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42753 
42754   if (N->getOpcode() != ISD::VSELECT)
42755     return SDValue();
42756 
42757   assert(CondVT.isVector() && "Vector select expects a vector selector!");
42758 
42759   // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
42760   // TODO: Can we assert that both operands are not zeros (because that should
42761   //       get simplified at node creation time)?
42762   bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
42763   bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
42764 
42765   // If both inputs are 0/undef, create a complete zero vector.
42766   // FIXME: As noted above this should be handled by DAGCombiner/getNode.
42767   if (TValIsAllZeros && FValIsAllZeros) {
42768     if (VT.isFloatingPoint())
42769       return DAG.getConstantFP(0.0, DL, VT);
42770     return DAG.getConstant(0, DL, VT);
42771   }
42772 
42773   // To use the condition operand as a bitwise mask, it must have elements that
42774   // are the same size as the select elements. Ie, the condition operand must
42775   // have already been promoted from the IR select condition type <N x i1>.
42776   // Don't check if the types themselves are equal because that excludes
42777   // vector floating-point selects.
42778   if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
42779     return SDValue();
42780 
42781   // Try to invert the condition if true value is not all 1s and false value is
42782   // not all 0s. Only do this if the condition has one use.
42783   bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
42784   if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
42785       // Check if the selector will be produced by CMPP*/PCMP*.
42786       Cond.getOpcode() == ISD::SETCC &&
42787       // Check if SETCC has already been promoted.
42788       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
42789           CondVT) {
42790     bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
42791 
42792     if (TValIsAllZeros || FValIsAllOnes) {
42793       SDValue CC = Cond.getOperand(2);
42794       ISD::CondCode NewCC = ISD::getSetCCInverse(
42795           cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
42796       Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
42797                           NewCC);
42798       std::swap(LHS, RHS);
42799       TValIsAllOnes = FValIsAllOnes;
42800       FValIsAllZeros = TValIsAllZeros;
42801     }
42802   }
42803 
42804   // Cond value must be 'sign splat' to be converted to a logical op.
42805   if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
42806     return SDValue();
42807 
42808   // vselect Cond, 111..., 000... -> Cond
42809   if (TValIsAllOnes && FValIsAllZeros)
42810     return DAG.getBitcast(VT, Cond);
42811 
42812   if (!TLI.isTypeLegal(CondVT))
42813     return SDValue();
42814 
42815   // vselect Cond, 111..., X -> or Cond, X
42816   if (TValIsAllOnes) {
42817     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
42818     SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
42819     return DAG.getBitcast(VT, Or);
42820   }
42821 
42822   // vselect Cond, X, 000... -> and Cond, X
42823   if (FValIsAllZeros) {
42824     SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
42825     SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
42826     return DAG.getBitcast(VT, And);
42827   }
42828 
42829   // vselect Cond, 000..., X -> andn Cond, X
42830   if (TValIsAllZeros) {
42831     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
42832     SDValue AndN;
42833     // The canonical form differs for i1 vectors - x86andnp is not used
42834     if (CondVT.getScalarType() == MVT::i1)
42835       AndN = DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT),
42836                          CastRHS);
42837     else
42838       AndN = DAG.getNode(X86ISD::ANDNP, DL, CondVT, Cond, CastRHS);
42839     return DAG.getBitcast(VT, AndN);
42840   }
42841 
42842   return SDValue();
42843 }
42844 
42845 /// If both arms of a vector select are concatenated vectors, split the select,
42846 /// and concatenate the result to eliminate a wide (256-bit) vector instruction:
42847 ///   vselect Cond, (concat T0, T1), (concat F0, F1) -->
42848 ///   concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
42849 static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG,
42850                                   const X86Subtarget &Subtarget) {
42851   unsigned Opcode = N->getOpcode();
42852   if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
42853     return SDValue();
42854 
42855   // TODO: Split 512-bit vectors too?
42856   EVT VT = N->getValueType(0);
42857   if (!VT.is256BitVector())
42858     return SDValue();
42859 
42860   // TODO: Split as long as any 2 of the 3 operands are concatenated?
42861   SDValue Cond = N->getOperand(0);
42862   SDValue TVal = N->getOperand(1);
42863   SDValue FVal = N->getOperand(2);
42864   SmallVector<SDValue, 4> CatOpsT, CatOpsF;
42865   if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
42866       !collectConcatOps(TVal.getNode(), CatOpsT) ||
42867       !collectConcatOps(FVal.getNode(), CatOpsF))
42868     return SDValue();
42869 
42870   auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
42871                             ArrayRef<SDValue> Ops) {
42872     return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
42873   };
42874   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { Cond, TVal, FVal },
42875                           makeBlend, /*CheckBWI*/ false);
42876 }
42877 
42878 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
42879   SDValue Cond = N->getOperand(0);
42880   SDValue LHS = N->getOperand(1);
42881   SDValue RHS = N->getOperand(2);
42882   SDLoc DL(N);
42883 
42884   auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
42885   auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
42886   if (!TrueC || !FalseC)
42887     return SDValue();
42888 
42889   // Don't do this for crazy integer types.
42890   EVT VT = N->getValueType(0);
42891   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
42892     return SDValue();
42893 
42894   // We're going to use the condition bit in math or logic ops. We could allow
42895   // this with a wider condition value (post-legalization it becomes an i8),
42896   // but if nothing is creating selects that late, it doesn't matter.
42897   if (Cond.getValueType() != MVT::i1)
42898     return SDValue();
42899 
42900   // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
42901   // 3, 5, or 9 with i32/i64, so those get transformed too.
42902   // TODO: For constants that overflow or do not differ by power-of-2 or small
42903   // multiplier, convert to 'and' + 'add'.
42904   const APInt &TrueVal = TrueC->getAPIntValue();
42905   const APInt &FalseVal = FalseC->getAPIntValue();
42906   bool OV;
42907   APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
42908   if (OV)
42909     return SDValue();
42910 
42911   APInt AbsDiff = Diff.abs();
42912   if (AbsDiff.isPowerOf2() ||
42913       ((VT == MVT::i32 || VT == MVT::i64) &&
42914        (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
42915 
42916     // We need a positive multiplier constant for shift/LEA codegen. The 'not'
42917     // of the condition can usually be folded into a compare predicate, but even
42918     // without that, the sequence should be cheaper than a CMOV alternative.
42919     if (TrueVal.slt(FalseVal)) {
42920       Cond = DAG.getNOT(DL, Cond, MVT::i1);
42921       std::swap(TrueC, FalseC);
42922     }
42923 
42924     // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
42925     SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
42926 
42927     // Multiply condition by the difference if non-one.
42928     if (!AbsDiff.isOne())
42929       R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
42930 
42931     // Add the base if non-zero.
42932     if (!FalseC->isZero())
42933       R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
42934 
42935     return R;
42936   }
42937 
42938   return SDValue();
42939 }
42940 
42941 /// If this is a *dynamic* select (non-constant condition) and we can match
42942 /// this node with one of the variable blend instructions, restructure the
42943 /// condition so that blends can use the high (sign) bit of each element.
42944 /// This function will also call SimplifyDemandedBits on already created
42945 /// BLENDV to perform additional simplifications.
42946 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
42947                                            TargetLowering::DAGCombinerInfo &DCI,
42948                                            const X86Subtarget &Subtarget) {
42949   SDValue Cond = N->getOperand(0);
42950   if ((N->getOpcode() != ISD::VSELECT &&
42951        N->getOpcode() != X86ISD::BLENDV) ||
42952       ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
42953     return SDValue();
42954 
42955   // Don't optimize before the condition has been transformed to a legal type
42956   // and don't ever optimize vector selects that map to AVX512 mask-registers.
42957   unsigned BitWidth = Cond.getScalarValueSizeInBits();
42958   if (BitWidth < 8 || BitWidth > 64)
42959     return SDValue();
42960 
42961   // We can only handle the cases where VSELECT is directly legal on the
42962   // subtarget. We custom lower VSELECT nodes with constant conditions and
42963   // this makes it hard to see whether a dynamic VSELECT will correctly
42964   // lower, so we both check the operation's status and explicitly handle the
42965   // cases where a *dynamic* blend will fail even though a constant-condition
42966   // blend could be custom lowered.
42967   // FIXME: We should find a better way to handle this class of problems.
42968   // Potentially, we should combine constant-condition vselect nodes
42969   // pre-legalization into shuffles and not mark as many types as custom
42970   // lowered.
42971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42972   EVT VT = N->getValueType(0);
42973   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
42974     return SDValue();
42975   // FIXME: We don't support i16-element blends currently. We could and
42976   // should support them by making *all* the bits in the condition be set
42977   // rather than just the high bit and using an i8-element blend.
42978   if (VT.getVectorElementType() == MVT::i16)
42979     return SDValue();
42980   // Dynamic blending was only available from SSE4.1 onward.
42981   if (VT.is128BitVector() && !Subtarget.hasSSE41())
42982     return SDValue();
42983   // Byte blends are only available in AVX2
42984   if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
42985     return SDValue();
42986   // There are no 512-bit blend instructions that use sign bits.
42987   if (VT.is512BitVector())
42988     return SDValue();
42989 
42990   auto OnlyUsedAsSelectCond = [](SDValue Cond) {
42991     for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
42992          UI != UE; ++UI)
42993       if ((UI->getOpcode() != ISD::VSELECT &&
42994            UI->getOpcode() != X86ISD::BLENDV) ||
42995           UI.getOperandNo() != 0)
42996         return false;
42997 
42998     return true;
42999   };
43000 
43001   APInt DemandedBits(APInt::getSignMask(BitWidth));
43002 
43003   if (OnlyUsedAsSelectCond(Cond)) {
43004     KnownBits Known;
43005     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
43006                                           !DCI.isBeforeLegalizeOps());
43007     if (!TLI.SimplifyDemandedBits(Cond, DemandedBits, Known, TLO, 0, true))
43008       return SDValue();
43009 
43010     // If we changed the computation somewhere in the DAG, this change will
43011     // affect all users of Cond. Update all the nodes so that we do not use
43012     // the generic VSELECT anymore. Otherwise, we may perform wrong
43013     // optimizations as we messed with the actual expectation for the vector
43014     // boolean values.
43015     for (SDNode *U : Cond->uses()) {
43016       if (U->getOpcode() == X86ISD::BLENDV)
43017         continue;
43018 
43019       SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
43020                                Cond, U->getOperand(1), U->getOperand(2));
43021       DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
43022       DCI.AddToWorklist(U);
43023     }
43024     DCI.CommitTargetLoweringOpt(TLO);
43025     return SDValue(N, 0);
43026   }
43027 
43028   // Otherwise we can still at least try to simplify multiple use bits.
43029   if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedBits, DAG))
43030       return DAG.getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0), V,
43031                          N->getOperand(1), N->getOperand(2));
43032 
43033   return SDValue();
43034 }
43035 
43036 // Try to match:
43037 //   (or (and (M, (sub 0, X)), (pandn M, X)))
43038 // which is a special case of:
43039 //   (select M, (sub 0, X), X)
43040 // Per:
43041 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
43042 // We know that, if fNegate is 0 or 1:
43043 //   (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
43044 //
43045 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
43046 //   ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
43047 //   ( M      ? -X : X) == ((X ^   M     ) + (M & 1))
43048 // This lets us transform our vselect to:
43049 //   (add (xor X, M), (and M, 1))
43050 // And further to:
43051 //   (sub (xor X, M), M)
43052 static SDValue combineLogicBlendIntoConditionalNegate(
43053     EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
43054     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
43055   EVT MaskVT = Mask.getValueType();
43056   assert(MaskVT.isInteger() &&
43057          DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
43058          "Mask must be zero/all-bits");
43059 
43060   if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
43061     return SDValue();
43062   if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
43063     return SDValue();
43064 
43065   auto IsNegV = [](SDNode *N, SDValue V) {
43066     return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
43067            ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
43068   };
43069 
43070   SDValue V;
43071   if (IsNegV(Y.getNode(), X))
43072     V = X;
43073   else if (IsNegV(X.getNode(), Y))
43074     V = Y;
43075   else
43076     return SDValue();
43077 
43078   SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
43079   SDValue SubOp2 = Mask;
43080 
43081   // If the negate was on the false side of the select, then
43082   // the operands of the SUB need to be swapped. PR 27251.
43083   // This is because the pattern being matched above is
43084   // (vselect M, (sub (0, X), X)  -> (sub (xor X, M), M)
43085   // but if the pattern matched was
43086   // (vselect M, X, (sub (0, X))), that is really negation of the pattern
43087   // above, -(vselect M, (sub 0, X), X), and therefore the replacement
43088   // pattern also needs to be a negation of the replacement pattern above.
43089   // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
43090   // sub accomplishes the negation of the replacement pattern.
43091   if (V == Y)
43092     std::swap(SubOp1, SubOp2);
43093 
43094   SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
43095   return DAG.getBitcast(VT, Res);
43096 }
43097 
43098 /// Do target-specific dag combines on SELECT and VSELECT nodes.
43099 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
43100                              TargetLowering::DAGCombinerInfo &DCI,
43101                              const X86Subtarget &Subtarget) {
43102   SDLoc DL(N);
43103   SDValue Cond = N->getOperand(0);
43104   SDValue LHS = N->getOperand(1);
43105   SDValue RHS = N->getOperand(2);
43106 
43107   // Try simplification again because we use this function to optimize
43108   // BLENDV nodes that are not handled by the generic combiner.
43109   if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
43110     return V;
43111 
43112   EVT VT = LHS.getValueType();
43113   EVT CondVT = Cond.getValueType();
43114   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43115   bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
43116 
43117   // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
43118   // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
43119   // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
43120   if (CondVT.isVector() && CondVT.isInteger() &&
43121       CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
43122       (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
43123       DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
43124     if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
43125                                                            DL, DAG, Subtarget))
43126       return V;
43127 
43128   // Convert vselects with constant condition into shuffles.
43129   if (CondConstantVector && DCI.isBeforeLegalizeOps()) {
43130     SmallVector<int, 64> Mask;
43131     if (createShuffleMaskFromVSELECT(Mask, Cond))
43132       return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
43133   }
43134 
43135   // fold vselect(cond, pshufb(x), pshufb(y)) -> or (pshufb(x), pshufb(y))
43136   // by forcing the unselected elements to zero.
43137   // TODO: Can we handle more shuffles with this?
43138   if (N->getOpcode() == ISD::VSELECT && CondVT.isVector() &&
43139       LHS.getOpcode() == X86ISD::PSHUFB && RHS.getOpcode() == X86ISD::PSHUFB &&
43140       LHS.hasOneUse() && RHS.hasOneUse()) {
43141     MVT SimpleVT = VT.getSimpleVT();
43142     SmallVector<SDValue, 1> LHSOps, RHSOps;
43143     SmallVector<int, 64> LHSMask, RHSMask, CondMask;
43144     if (createShuffleMaskFromVSELECT(CondMask, Cond) &&
43145         getTargetShuffleMask(LHS.getNode(), SimpleVT, true, LHSOps, LHSMask) &&
43146         getTargetShuffleMask(RHS.getNode(), SimpleVT, true, RHSOps, RHSMask)) {
43147       int NumElts = VT.getVectorNumElements();
43148       for (int i = 0; i != NumElts; ++i) {
43149         // getConstVector sets negative shuffle mask values as undef, so ensure
43150         // we hardcode SM_SentinelZero values to zero (0x80).
43151         if (CondMask[i] < NumElts) {
43152           LHSMask[i] = (LHSMask[i] == SM_SentinelZero) ? 0x80 : LHSMask[i];
43153           RHSMask[i] = 0x80;
43154         } else {
43155           LHSMask[i] = 0x80;
43156           RHSMask[i] = (RHSMask[i] == SM_SentinelZero) ? 0x80 : RHSMask[i];
43157         }
43158       }
43159       LHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, LHS.getOperand(0),
43160                         getConstVector(LHSMask, SimpleVT, DAG, DL, true));
43161       RHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, RHS.getOperand(0),
43162                         getConstVector(RHSMask, SimpleVT, DAG, DL, true));
43163       return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
43164     }
43165   }
43166 
43167   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
43168   // instructions match the semantics of the common C idiom x<y?x:y but not
43169   // x<=y?x:y, because of how they handle negative zero (which can be
43170   // ignored in unsafe-math mode).
43171   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
43172   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
43173       VT != MVT::f80 && VT != MVT::f128 &&
43174       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
43175       (Subtarget.hasSSE2() ||
43176        (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
43177     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
43178 
43179     unsigned Opcode = 0;
43180     // Check for x CC y ? x : y.
43181     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
43182         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
43183       switch (CC) {
43184       default: break;
43185       case ISD::SETULT:
43186         // Converting this to a min would handle NaNs incorrectly, and swapping
43187         // the operands would cause it to handle comparisons between positive
43188         // and negative zero incorrectly.
43189         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
43190           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
43191               !(DAG.isKnownNeverZeroFloat(LHS) ||
43192                 DAG.isKnownNeverZeroFloat(RHS)))
43193             break;
43194           std::swap(LHS, RHS);
43195         }
43196         Opcode = X86ISD::FMIN;
43197         break;
43198       case ISD::SETOLE:
43199         // Converting this to a min would handle comparisons between positive
43200         // and negative zero incorrectly.
43201         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
43202             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
43203           break;
43204         Opcode = X86ISD::FMIN;
43205         break;
43206       case ISD::SETULE:
43207         // Converting this to a min would handle both negative zeros and NaNs
43208         // incorrectly, but we can swap the operands to fix both.
43209         std::swap(LHS, RHS);
43210         LLVM_FALLTHROUGH;
43211       case ISD::SETOLT:
43212       case ISD::SETLT:
43213       case ISD::SETLE:
43214         Opcode = X86ISD::FMIN;
43215         break;
43216 
43217       case ISD::SETOGE:
43218         // Converting this to a max would handle comparisons between positive
43219         // and negative zero incorrectly.
43220         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
43221             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
43222           break;
43223         Opcode = X86ISD::FMAX;
43224         break;
43225       case ISD::SETUGT:
43226         // Converting this to a max would handle NaNs incorrectly, and swapping
43227         // the operands would cause it to handle comparisons between positive
43228         // and negative zero incorrectly.
43229         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
43230           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
43231               !(DAG.isKnownNeverZeroFloat(LHS) ||
43232                 DAG.isKnownNeverZeroFloat(RHS)))
43233             break;
43234           std::swap(LHS, RHS);
43235         }
43236         Opcode = X86ISD::FMAX;
43237         break;
43238       case ISD::SETUGE:
43239         // Converting this to a max would handle both negative zeros and NaNs
43240         // incorrectly, but we can swap the operands to fix both.
43241         std::swap(LHS, RHS);
43242         LLVM_FALLTHROUGH;
43243       case ISD::SETOGT:
43244       case ISD::SETGT:
43245       case ISD::SETGE:
43246         Opcode = X86ISD::FMAX;
43247         break;
43248       }
43249     // Check for x CC y ? y : x -- a min/max with reversed arms.
43250     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
43251                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
43252       switch (CC) {
43253       default: break;
43254       case ISD::SETOGE:
43255         // Converting this to a min would handle comparisons between positive
43256         // and negative zero incorrectly, and swapping the operands would
43257         // cause it to handle NaNs incorrectly.
43258         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
43259             !(DAG.isKnownNeverZeroFloat(LHS) ||
43260               DAG.isKnownNeverZeroFloat(RHS))) {
43261           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
43262             break;
43263           std::swap(LHS, RHS);
43264         }
43265         Opcode = X86ISD::FMIN;
43266         break;
43267       case ISD::SETUGT:
43268         // Converting this to a min would handle NaNs incorrectly.
43269         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
43270           break;
43271         Opcode = X86ISD::FMIN;
43272         break;
43273       case ISD::SETUGE:
43274         // Converting this to a min would handle both negative zeros and NaNs
43275         // incorrectly, but we can swap the operands to fix both.
43276         std::swap(LHS, RHS);
43277         LLVM_FALLTHROUGH;
43278       case ISD::SETOGT:
43279       case ISD::SETGT:
43280       case ISD::SETGE:
43281         Opcode = X86ISD::FMIN;
43282         break;
43283 
43284       case ISD::SETULT:
43285         // Converting this to a max would handle NaNs incorrectly.
43286         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
43287           break;
43288         Opcode = X86ISD::FMAX;
43289         break;
43290       case ISD::SETOLE:
43291         // Converting this to a max would handle comparisons between positive
43292         // and negative zero incorrectly, and swapping the operands would
43293         // cause it to handle NaNs incorrectly.
43294         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
43295             !DAG.isKnownNeverZeroFloat(LHS) &&
43296             !DAG.isKnownNeverZeroFloat(RHS)) {
43297           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
43298             break;
43299           std::swap(LHS, RHS);
43300         }
43301         Opcode = X86ISD::FMAX;
43302         break;
43303       case ISD::SETULE:
43304         // Converting this to a max would handle both negative zeros and NaNs
43305         // incorrectly, but we can swap the operands to fix both.
43306         std::swap(LHS, RHS);
43307         LLVM_FALLTHROUGH;
43308       case ISD::SETOLT:
43309       case ISD::SETLT:
43310       case ISD::SETLE:
43311         Opcode = X86ISD::FMAX;
43312         break;
43313       }
43314     }
43315 
43316     if (Opcode)
43317       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
43318   }
43319 
43320   // Some mask scalar intrinsics rely on checking if only one bit is set
43321   // and implement it in C code like this:
43322   // A[0] = (U & 1) ? A[0] : W[0];
43323   // This creates some redundant instructions that break pattern matching.
43324   // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
43325   if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
43326       Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
43327     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
43328     SDValue AndNode = Cond.getOperand(0);
43329     if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
43330         isNullConstant(Cond.getOperand(1)) &&
43331         isOneConstant(AndNode.getOperand(1))) {
43332       // LHS and RHS swapped due to
43333       // setcc outputting 1 when AND resulted in 0 and vice versa.
43334       AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
43335       return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
43336     }
43337   }
43338 
43339   // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
43340   // lowering on KNL. In this case we convert it to
43341   // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
43342   // The same situation all vectors of i8 and i16 without BWI.
43343   // Make sure we extend these even before type legalization gets a chance to
43344   // split wide vectors.
43345   // Since SKX these selects have a proper lowering.
43346   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
43347       CondVT.getVectorElementType() == MVT::i1 &&
43348       (VT.getVectorElementType() == MVT::i8 ||
43349        VT.getVectorElementType() == MVT::i16)) {
43350     Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
43351     return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
43352   }
43353 
43354   // AVX512 - Extend select with zero to merge with target shuffle.
43355   // select(mask, extract_subvector(shuffle(x)), zero) -->
43356   // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
43357   // TODO - support non target shuffles as well.
43358   if (Subtarget.hasAVX512() && CondVT.isVector() &&
43359       CondVT.getVectorElementType() == MVT::i1) {
43360     auto SelectableOp = [&TLI](SDValue Op) {
43361       return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
43362              isTargetShuffle(Op.getOperand(0).getOpcode()) &&
43363              isNullConstant(Op.getOperand(1)) &&
43364              TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
43365              Op.hasOneUse() && Op.getOperand(0).hasOneUse();
43366     };
43367 
43368     bool SelectableLHS = SelectableOp(LHS);
43369     bool SelectableRHS = SelectableOp(RHS);
43370     bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
43371     bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
43372 
43373     if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
43374       EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
43375                                 : RHS.getOperand(0).getValueType();
43376       EVT SrcCondVT = SrcVT.changeVectorElementType(MVT::i1);
43377       LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
43378                             VT.getSizeInBits());
43379       RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
43380                             VT.getSizeInBits());
43381       Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
43382                          DAG.getUNDEF(SrcCondVT), Cond,
43383                          DAG.getIntPtrConstant(0, DL));
43384       SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
43385       return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
43386     }
43387   }
43388 
43389   if (SDValue V = combineSelectOfTwoConstants(N, DAG))
43390     return V;
43391 
43392   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
43393       Cond.hasOneUse()) {
43394     EVT CondVT = Cond.getValueType();
43395     SDValue Cond0 = Cond.getOperand(0);
43396     SDValue Cond1 = Cond.getOperand(1);
43397     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
43398 
43399     // Canonicalize min/max:
43400     // (x > 0) ? x : 0 -> (x >= 0) ? x : 0
43401     // (x < -1) ? x : -1 -> (x <= -1) ? x : -1
43402     // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
43403     // the need for an extra compare against zero. e.g.
43404     // (a - b) > 0 : (a - b) ? 0 -> (a - b) >= 0 : (a - b) ? 0
43405     // subl   %esi, %edi
43406     // testl  %edi, %edi
43407     // movl   $0, %eax
43408     // cmovgl %edi, %eax
43409     // =>
43410     // xorl   %eax, %eax
43411     // subl   %esi, $edi
43412     // cmovsl %eax, %edi
43413     //
43414     // We can also canonicalize
43415     //  (x s> 1) ? x : 1 -> (x s>= 1) ? x : 1 -> (x s> 0) ? x : 1
43416     //  (x u> 1) ? x : 1 -> (x u>= 1) ? x : 1 -> (x != 0) ? x : 1
43417     // This allows the use of a test instruction for the compare.
43418     if (LHS == Cond0 && RHS == Cond1) {
43419       if ((CC == ISD::SETGT && (isNullConstant(RHS) || isOneConstant(RHS))) ||
43420           (CC == ISD::SETLT && isAllOnesConstant(RHS))) {
43421         ISD::CondCode NewCC = CC == ISD::SETGT ? ISD::SETGE : ISD::SETLE;
43422         Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
43423         return DAG.getSelect(DL, VT, Cond, LHS, RHS);
43424       }
43425       if (CC == ISD::SETUGT && isOneConstant(RHS)) {
43426         ISD::CondCode NewCC = ISD::SETUGE;
43427         Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
43428         return DAG.getSelect(DL, VT, Cond, LHS, RHS);
43429       }
43430     }
43431 
43432     // Similar to DAGCombine's select(or(CC0,CC1),X,Y) fold but for legal types.
43433     // fold eq + gt/lt nested selects into ge/le selects
43434     // select (cmpeq Cond0, Cond1), LHS, (select (cmpugt Cond0, Cond1), LHS, Y)
43435     // --> (select (cmpuge Cond0, Cond1), LHS, Y)
43436     // select (cmpslt Cond0, Cond1), LHS, (select (cmpeq Cond0, Cond1), LHS, Y)
43437     // --> (select (cmpsle Cond0, Cond1), LHS, Y)
43438     // .. etc ..
43439     if (RHS.getOpcode() == ISD::SELECT && RHS.getOperand(1) == LHS &&
43440         RHS.getOperand(0).getOpcode() == ISD::SETCC) {
43441       SDValue InnerSetCC = RHS.getOperand(0);
43442       ISD::CondCode InnerCC =
43443           cast<CondCodeSDNode>(InnerSetCC.getOperand(2))->get();
43444       if ((CC == ISD::SETEQ || InnerCC == ISD::SETEQ) &&
43445           Cond0 == InnerSetCC.getOperand(0) &&
43446           Cond1 == InnerSetCC.getOperand(1)) {
43447         ISD::CondCode NewCC;
43448         switch (CC == ISD::SETEQ ? InnerCC : CC) {
43449         case ISD::SETGT:  NewCC = ISD::SETGE; break;
43450         case ISD::SETLT:  NewCC = ISD::SETLE; break;
43451         case ISD::SETUGT: NewCC = ISD::SETUGE; break;
43452         case ISD::SETULT: NewCC = ISD::SETULE; break;
43453         default: NewCC = ISD::SETCC_INVALID; break;
43454         }
43455         if (NewCC != ISD::SETCC_INVALID) {
43456           Cond = DAG.getSetCC(DL, CondVT, Cond0, Cond1, NewCC);
43457           return DAG.getSelect(DL, VT, Cond, LHS, RHS.getOperand(2));
43458         }
43459       }
43460     }
43461   }
43462 
43463   // Check if the first operand is all zeros and Cond type is vXi1.
43464   // If this an avx512 target we can improve the use of zero masking by
43465   // swapping the operands and inverting the condition.
43466   if (N->getOpcode() == ISD::VSELECT && Cond.hasOneUse() &&
43467        Subtarget.hasAVX512() && CondVT.getVectorElementType() == MVT::i1 &&
43468       ISD::isBuildVectorAllZeros(LHS.getNode()) &&
43469       !ISD::isBuildVectorAllZeros(RHS.getNode())) {
43470     // Invert the cond to not(cond) : xor(op,allones)=not(op)
43471     SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
43472     // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
43473     return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
43474   }
43475 
43476   // Early exit check
43477   if (!TLI.isTypeLegal(VT))
43478     return SDValue();
43479 
43480   if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
43481     return V;
43482 
43483   if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
43484     return V;
43485 
43486   if (SDValue V = narrowVectorSelect(N, DAG, Subtarget))
43487     return V;
43488 
43489   // select(~Cond, X, Y) -> select(Cond, Y, X)
43490   if (CondVT.getScalarType() != MVT::i1) {
43491     if (SDValue CondNot = IsNOT(Cond, DAG))
43492       return DAG.getNode(N->getOpcode(), DL, VT,
43493                          DAG.getBitcast(CondVT, CondNot), RHS, LHS);
43494     // pcmpgt(X, -1) -> pcmpgt(0, X) to help select/blendv just use the signbit.
43495     if (Cond.getOpcode() == X86ISD::PCMPGT && Cond.hasOneUse() &&
43496         ISD::isBuildVectorAllOnes(Cond.getOperand(1).getNode())) {
43497       Cond = DAG.getNode(X86ISD::PCMPGT, DL, CondVT,
43498                          DAG.getConstant(0, DL, CondVT), Cond.getOperand(0));
43499       return DAG.getNode(N->getOpcode(), DL, VT, Cond, RHS, LHS);
43500     }
43501   }
43502 
43503   // Try to optimize vXi1 selects if both operands are either all constants or
43504   // bitcasts from scalar integer type. In that case we can convert the operands
43505   // to integer and use an integer select which will be converted to a CMOV.
43506   // We need to take a little bit of care to avoid creating an i64 type after
43507   // type legalization.
43508   if (N->getOpcode() == ISD::SELECT && VT.isVector() &&
43509       VT.getVectorElementType() == MVT::i1 &&
43510       (DCI.isBeforeLegalize() || (VT != MVT::v64i1 || Subtarget.is64Bit()))) {
43511     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
43512     bool LHSIsConst = ISD::isBuildVectorOfConstantSDNodes(LHS.getNode());
43513     bool RHSIsConst = ISD::isBuildVectorOfConstantSDNodes(RHS.getNode());
43514 
43515     if ((LHSIsConst ||
43516          (LHS.getOpcode() == ISD::BITCAST &&
43517           LHS.getOperand(0).getValueType() == IntVT)) &&
43518         (RHSIsConst ||
43519          (RHS.getOpcode() == ISD::BITCAST &&
43520           RHS.getOperand(0).getValueType() == IntVT))) {
43521       if (LHSIsConst)
43522         LHS = combinevXi1ConstantToInteger(LHS, DAG);
43523       else
43524         LHS = LHS.getOperand(0);
43525 
43526       if (RHSIsConst)
43527         RHS = combinevXi1ConstantToInteger(RHS, DAG);
43528       else
43529         RHS = RHS.getOperand(0);
43530 
43531       SDValue Select = DAG.getSelect(DL, IntVT, Cond, LHS, RHS);
43532       return DAG.getBitcast(VT, Select);
43533     }
43534   }
43535 
43536   // If this is "((X & C) == 0) ? Y : Z" and C is a constant mask vector of
43537   // single bits, then invert the predicate and swap the select operands.
43538   // This can lower using a vector shift bit-hack rather than mask and compare.
43539   if (DCI.isBeforeLegalize() && !Subtarget.hasAVX512() &&
43540       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
43541       Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1 &&
43542       Cond.getOperand(0).getOpcode() == ISD::AND &&
43543       isNullOrNullSplat(Cond.getOperand(1)) &&
43544       cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
43545       Cond.getOperand(0).getValueType() == VT) {
43546     // The 'and' mask must be composed of power-of-2 constants.
43547     SDValue And = Cond.getOperand(0);
43548     auto *C = isConstOrConstSplat(And.getOperand(1));
43549     if (C && C->getAPIntValue().isPowerOf2()) {
43550       // vselect (X & C == 0), LHS, RHS --> vselect (X & C != 0), RHS, LHS
43551       SDValue NotCond =
43552           DAG.getSetCC(DL, CondVT, And, Cond.getOperand(1), ISD::SETNE);
43553       return DAG.getSelect(DL, VT, NotCond, RHS, LHS);
43554     }
43555 
43556     // If we have a non-splat but still powers-of-2 mask, AVX1 can use pmulld
43557     // and AVX2 can use vpsllv{dq}. 8-bit lacks a proper shift or multiply.
43558     // 16-bit lacks a proper blendv.
43559     unsigned EltBitWidth = VT.getScalarSizeInBits();
43560     bool CanShiftBlend =
43561         TLI.isTypeLegal(VT) && ((Subtarget.hasAVX() && EltBitWidth == 32) ||
43562                                 (Subtarget.hasAVX2() && EltBitWidth == 64) ||
43563                                 (Subtarget.hasXOP()));
43564     if (CanShiftBlend &&
43565         ISD::matchUnaryPredicate(And.getOperand(1), [](ConstantSDNode *C) {
43566           return C->getAPIntValue().isPowerOf2();
43567         })) {
43568       // Create a left-shift constant to get the mask bits over to the sign-bit.
43569       SDValue Mask = And.getOperand(1);
43570       SmallVector<int, 32> ShlVals;
43571       for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
43572         auto *MaskVal = cast<ConstantSDNode>(Mask.getOperand(i));
43573         ShlVals.push_back(EltBitWidth - 1 -
43574                           MaskVal->getAPIntValue().exactLogBase2());
43575       }
43576       // vsel ((X & C) == 0), LHS, RHS --> vsel ((shl X, C') < 0), RHS, LHS
43577       SDValue ShlAmt = getConstVector(ShlVals, VT.getSimpleVT(), DAG, DL);
43578       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And.getOperand(0), ShlAmt);
43579       SDValue NewCond =
43580           DAG.getSetCC(DL, CondVT, Shl, Cond.getOperand(1), ISD::SETLT);
43581       return DAG.getSelect(DL, VT, NewCond, RHS, LHS);
43582     }
43583   }
43584 
43585   return SDValue();
43586 }
43587 
43588 /// Combine:
43589 ///   (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
43590 /// to:
43591 ///   (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
43592 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
43593 /// Note that this is only legal for some op/cc combinations.
43594 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
43595                                        SelectionDAG &DAG,
43596                                        const X86Subtarget &Subtarget) {
43597   // This combine only operates on CMP-like nodes.
43598   if (!(Cmp.getOpcode() == X86ISD::CMP ||
43599         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
43600     return SDValue();
43601 
43602   // Can't replace the cmp if it has more uses than the one we're looking at.
43603   // FIXME: We would like to be able to handle this, but would need to make sure
43604   // all uses were updated.
43605   if (!Cmp.hasOneUse())
43606     return SDValue();
43607 
43608   // This only applies to variations of the common case:
43609   //   (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
43610   //   (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
43611   //   (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
43612   //   (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
43613   // Using the proper condcodes (see below), overflow is checked for.
43614 
43615   // FIXME: We can generalize both constraints:
43616   // - XOR/OR/AND (if they were made to survive AtomicExpand)
43617   // - LHS != 1
43618   // if the result is compared.
43619 
43620   SDValue CmpLHS = Cmp.getOperand(0);
43621   SDValue CmpRHS = Cmp.getOperand(1);
43622   EVT CmpVT = CmpLHS.getValueType();
43623 
43624   if (!CmpLHS.hasOneUse())
43625     return SDValue();
43626 
43627   unsigned Opc = CmpLHS.getOpcode();
43628   if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
43629     return SDValue();
43630 
43631   SDValue OpRHS = CmpLHS.getOperand(2);
43632   auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
43633   if (!OpRHSC)
43634     return SDValue();
43635 
43636   APInt Addend = OpRHSC->getAPIntValue();
43637   if (Opc == ISD::ATOMIC_LOAD_SUB)
43638     Addend = -Addend;
43639 
43640   auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
43641   if (!CmpRHSC)
43642     return SDValue();
43643 
43644   APInt Comparison = CmpRHSC->getAPIntValue();
43645   APInt NegAddend = -Addend;
43646 
43647   // See if we can adjust the CC to make the comparison match the negated
43648   // addend.
43649   if (Comparison != NegAddend) {
43650     APInt IncComparison = Comparison + 1;
43651     if (IncComparison == NegAddend) {
43652       if (CC == X86::COND_A && !Comparison.isMaxValue()) {
43653         Comparison = IncComparison;
43654         CC = X86::COND_AE;
43655       } else if (CC == X86::COND_LE && !Comparison.isMaxSignedValue()) {
43656         Comparison = IncComparison;
43657         CC = X86::COND_L;
43658       }
43659     }
43660     APInt DecComparison = Comparison - 1;
43661     if (DecComparison == NegAddend) {
43662       if (CC == X86::COND_AE && !Comparison.isMinValue()) {
43663         Comparison = DecComparison;
43664         CC = X86::COND_A;
43665       } else if (CC == X86::COND_L && !Comparison.isMinSignedValue()) {
43666         Comparison = DecComparison;
43667         CC = X86::COND_LE;
43668       }
43669     }
43670   }
43671 
43672   // If the addend is the negation of the comparison value, then we can do
43673   // a full comparison by emitting the atomic arithmetic as a locked sub.
43674   if (Comparison == NegAddend) {
43675     // The CC is fine, but we need to rewrite the LHS of the comparison as an
43676     // atomic sub.
43677     auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
43678     auto AtomicSub = DAG.getAtomic(
43679         ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpVT,
43680         /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
43681         /*RHS*/ DAG.getConstant(NegAddend, SDLoc(CmpRHS), CmpVT),
43682         AN->getMemOperand());
43683     auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
43684     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
43685     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
43686     return LockOp;
43687   }
43688 
43689   // We can handle comparisons with zero in a number of cases by manipulating
43690   // the CC used.
43691   if (!Comparison.isZero())
43692     return SDValue();
43693 
43694   if (CC == X86::COND_S && Addend == 1)
43695     CC = X86::COND_LE;
43696   else if (CC == X86::COND_NS && Addend == 1)
43697     CC = X86::COND_G;
43698   else if (CC == X86::COND_G && Addend == -1)
43699     CC = X86::COND_GE;
43700   else if (CC == X86::COND_LE && Addend == -1)
43701     CC = X86::COND_L;
43702   else
43703     return SDValue();
43704 
43705   SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
43706   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
43707   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
43708   return LockOp;
43709 }
43710 
43711 // Check whether a boolean test is testing a boolean value generated by
43712 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
43713 // code.
43714 //
43715 // Simplify the following patterns:
43716 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
43717 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
43718 // to (Op EFLAGS Cond)
43719 //
43720 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
43721 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
43722 // to (Op EFLAGS !Cond)
43723 //
43724 // where Op could be BRCOND or CMOV.
43725 //
43726 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
43727   // This combine only operates on CMP-like nodes.
43728   if (!(Cmp.getOpcode() == X86ISD::CMP ||
43729         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
43730     return SDValue();
43731 
43732   // Quit if not used as a boolean value.
43733   if (CC != X86::COND_E && CC != X86::COND_NE)
43734     return SDValue();
43735 
43736   // Check CMP operands. One of them should be 0 or 1 and the other should be
43737   // an SetCC or extended from it.
43738   SDValue Op1 = Cmp.getOperand(0);
43739   SDValue Op2 = Cmp.getOperand(1);
43740 
43741   SDValue SetCC;
43742   const ConstantSDNode* C = nullptr;
43743   bool needOppositeCond = (CC == X86::COND_E);
43744   bool checkAgainstTrue = false; // Is it a comparison against 1?
43745 
43746   if ((C = dyn_cast<ConstantSDNode>(Op1)))
43747     SetCC = Op2;
43748   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
43749     SetCC = Op1;
43750   else // Quit if all operands are not constants.
43751     return SDValue();
43752 
43753   if (C->getZExtValue() == 1) {
43754     needOppositeCond = !needOppositeCond;
43755     checkAgainstTrue = true;
43756   } else if (C->getZExtValue() != 0)
43757     // Quit if the constant is neither 0 or 1.
43758     return SDValue();
43759 
43760   bool truncatedToBoolWithAnd = false;
43761   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
43762   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
43763          SetCC.getOpcode() == ISD::TRUNCATE ||
43764          SetCC.getOpcode() == ISD::AND) {
43765     if (SetCC.getOpcode() == ISD::AND) {
43766       int OpIdx = -1;
43767       if (isOneConstant(SetCC.getOperand(0)))
43768         OpIdx = 1;
43769       if (isOneConstant(SetCC.getOperand(1)))
43770         OpIdx = 0;
43771       if (OpIdx < 0)
43772         break;
43773       SetCC = SetCC.getOperand(OpIdx);
43774       truncatedToBoolWithAnd = true;
43775     } else
43776       SetCC = SetCC.getOperand(0);
43777   }
43778 
43779   switch (SetCC.getOpcode()) {
43780   case X86ISD::SETCC_CARRY:
43781     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
43782     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
43783     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
43784     // truncated to i1 using 'and'.
43785     if (checkAgainstTrue && !truncatedToBoolWithAnd)
43786       break;
43787     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
43788            "Invalid use of SETCC_CARRY!");
43789     LLVM_FALLTHROUGH;
43790   case X86ISD::SETCC:
43791     // Set the condition code or opposite one if necessary.
43792     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
43793     if (needOppositeCond)
43794       CC = X86::GetOppositeBranchCondition(CC);
43795     return SetCC.getOperand(1);
43796   case X86ISD::CMOV: {
43797     // Check whether false/true value has canonical one, i.e. 0 or 1.
43798     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
43799     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
43800     // Quit if true value is not a constant.
43801     if (!TVal)
43802       return SDValue();
43803     // Quit if false value is not a constant.
43804     if (!FVal) {
43805       SDValue Op = SetCC.getOperand(0);
43806       // Skip 'zext' or 'trunc' node.
43807       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
43808           Op.getOpcode() == ISD::TRUNCATE)
43809         Op = Op.getOperand(0);
43810       // A special case for rdrand/rdseed, where 0 is set if false cond is
43811       // found.
43812       if ((Op.getOpcode() != X86ISD::RDRAND &&
43813            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
43814         return SDValue();
43815     }
43816     // Quit if false value is not the constant 0 or 1.
43817     bool FValIsFalse = true;
43818     if (FVal && FVal->getZExtValue() != 0) {
43819       if (FVal->getZExtValue() != 1)
43820         return SDValue();
43821       // If FVal is 1, opposite cond is needed.
43822       needOppositeCond = !needOppositeCond;
43823       FValIsFalse = false;
43824     }
43825     // Quit if TVal is not the constant opposite of FVal.
43826     if (FValIsFalse && TVal->getZExtValue() != 1)
43827       return SDValue();
43828     if (!FValIsFalse && TVal->getZExtValue() != 0)
43829       return SDValue();
43830     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
43831     if (needOppositeCond)
43832       CC = X86::GetOppositeBranchCondition(CC);
43833     return SetCC.getOperand(3);
43834   }
43835   }
43836 
43837   return SDValue();
43838 }
43839 
43840 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
43841 /// Match:
43842 ///   (X86or (X86setcc) (X86setcc))
43843 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
43844 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
43845                                            X86::CondCode &CC1, SDValue &Flags,
43846                                            bool &isAnd) {
43847   if (Cond->getOpcode() == X86ISD::CMP) {
43848     if (!isNullConstant(Cond->getOperand(1)))
43849       return false;
43850 
43851     Cond = Cond->getOperand(0);
43852   }
43853 
43854   isAnd = false;
43855 
43856   SDValue SetCC0, SetCC1;
43857   switch (Cond->getOpcode()) {
43858   default: return false;
43859   case ISD::AND:
43860   case X86ISD::AND:
43861     isAnd = true;
43862     LLVM_FALLTHROUGH;
43863   case ISD::OR:
43864   case X86ISD::OR:
43865     SetCC0 = Cond->getOperand(0);
43866     SetCC1 = Cond->getOperand(1);
43867     break;
43868   };
43869 
43870   // Make sure we have SETCC nodes, using the same flags value.
43871   if (SetCC0.getOpcode() != X86ISD::SETCC ||
43872       SetCC1.getOpcode() != X86ISD::SETCC ||
43873       SetCC0->getOperand(1) != SetCC1->getOperand(1))
43874     return false;
43875 
43876   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
43877   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
43878   Flags = SetCC0->getOperand(1);
43879   return true;
43880 }
43881 
43882 // When legalizing carry, we create carries via add X, -1
43883 // If that comes from an actual carry, via setcc, we use the
43884 // carry directly.
43885 static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
43886   if (EFLAGS.getOpcode() == X86ISD::ADD) {
43887     if (isAllOnesConstant(EFLAGS.getOperand(1))) {
43888       SDValue Carry = EFLAGS.getOperand(0);
43889       while (Carry.getOpcode() == ISD::TRUNCATE ||
43890              Carry.getOpcode() == ISD::ZERO_EXTEND ||
43891              Carry.getOpcode() == ISD::SIGN_EXTEND ||
43892              Carry.getOpcode() == ISD::ANY_EXTEND ||
43893              (Carry.getOpcode() == ISD::AND &&
43894               isOneConstant(Carry.getOperand(1))))
43895         Carry = Carry.getOperand(0);
43896       if (Carry.getOpcode() == X86ISD::SETCC ||
43897           Carry.getOpcode() == X86ISD::SETCC_CARRY) {
43898         // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
43899         uint64_t CarryCC = Carry.getConstantOperandVal(0);
43900         SDValue CarryOp1 = Carry.getOperand(1);
43901         if (CarryCC == X86::COND_B)
43902           return CarryOp1;
43903         if (CarryCC == X86::COND_A) {
43904           // Try to convert COND_A into COND_B in an attempt to facilitate
43905           // materializing "setb reg".
43906           //
43907           // Do not flip "e > c", where "c" is a constant, because Cmp
43908           // instruction cannot take an immediate as its first operand.
43909           //
43910           if (CarryOp1.getOpcode() == X86ISD::SUB &&
43911               CarryOp1.getNode()->hasOneUse() &&
43912               CarryOp1.getValueType().isInteger() &&
43913               !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
43914             SDValue SubCommute =
43915                 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
43916                             CarryOp1.getOperand(1), CarryOp1.getOperand(0));
43917             return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
43918           }
43919         }
43920         // If this is a check of the z flag of an add with 1, switch to the
43921         // C flag.
43922         if (CarryCC == X86::COND_E &&
43923             CarryOp1.getOpcode() == X86ISD::ADD &&
43924             isOneConstant(CarryOp1.getOperand(1)))
43925           return CarryOp1;
43926       }
43927     }
43928   }
43929 
43930   return SDValue();
43931 }
43932 
43933 /// If we are inverting an PTEST/TESTP operand, attempt to adjust the CC
43934 /// to avoid the inversion.
43935 static SDValue combinePTESTCC(SDValue EFLAGS, X86::CondCode &CC,
43936                               SelectionDAG &DAG,
43937                               const X86Subtarget &Subtarget) {
43938   // TODO: Handle X86ISD::KTEST/X86ISD::KORTEST.
43939   if (EFLAGS.getOpcode() != X86ISD::PTEST &&
43940       EFLAGS.getOpcode() != X86ISD::TESTP)
43941     return SDValue();
43942 
43943   // PTEST/TESTP sets EFLAGS as:
43944   // TESTZ: ZF = (Op0 & Op1) == 0
43945   // TESTC: CF = (~Op0 & Op1) == 0
43946   // TESTNZC: ZF == 0 && CF == 0
43947   EVT VT = EFLAGS.getValueType();
43948   SDValue Op0 = EFLAGS.getOperand(0);
43949   SDValue Op1 = EFLAGS.getOperand(1);
43950   EVT OpVT = Op0.getValueType();
43951 
43952   // TEST*(~X,Y) == TEST*(X,Y)
43953   if (SDValue NotOp0 = IsNOT(Op0, DAG)) {
43954     X86::CondCode InvCC;
43955     switch (CC) {
43956     case X86::COND_B:
43957       // testc -> testz.
43958       InvCC = X86::COND_E;
43959       break;
43960     case X86::COND_AE:
43961       // !testc -> !testz.
43962       InvCC = X86::COND_NE;
43963       break;
43964     case X86::COND_E:
43965       // testz -> testc.
43966       InvCC = X86::COND_B;
43967       break;
43968     case X86::COND_NE:
43969       // !testz -> !testc.
43970       InvCC = X86::COND_AE;
43971       break;
43972     case X86::COND_A:
43973     case X86::COND_BE:
43974       // testnzc -> testnzc (no change).
43975       InvCC = CC;
43976       break;
43977     default:
43978       InvCC = X86::COND_INVALID;
43979       break;
43980     }
43981 
43982     if (InvCC != X86::COND_INVALID) {
43983       CC = InvCC;
43984       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
43985                          DAG.getBitcast(OpVT, NotOp0), Op1);
43986     }
43987   }
43988 
43989   if (CC == X86::COND_E || CC == X86::COND_NE) {
43990     // TESTZ(X,~Y) == TESTC(Y,X)
43991     if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
43992       CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
43993       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
43994                          DAG.getBitcast(OpVT, NotOp1), Op0);
43995     }
43996 
43997     if (Op0 == Op1) {
43998       SDValue BC = peekThroughBitcasts(Op0);
43999       EVT BCVT = BC.getValueType();
44000       assert(BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
44001              "Unexpected vector type");
44002 
44003       // TESTZ(AND(X,Y),AND(X,Y)) == TESTZ(X,Y)
44004       if (BC.getOpcode() == ISD::AND || BC.getOpcode() == X86ISD::FAND) {
44005         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
44006                            DAG.getBitcast(OpVT, BC.getOperand(0)),
44007                            DAG.getBitcast(OpVT, BC.getOperand(1)));
44008       }
44009 
44010       // TESTZ(AND(~X,Y),AND(~X,Y)) == TESTC(X,Y)
44011       if (BC.getOpcode() == X86ISD::ANDNP || BC.getOpcode() == X86ISD::FANDN) {
44012         CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
44013         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
44014                            DAG.getBitcast(OpVT, BC.getOperand(0)),
44015                            DAG.getBitcast(OpVT, BC.getOperand(1)));
44016       }
44017 
44018       // If every element is an all-sign value, see if we can use MOVMSK to
44019       // more efficiently extract the sign bits and compare that.
44020       // TODO: Handle TESTC with comparison inversion.
44021       // TODO: Can we remove SimplifyMultipleUseDemandedBits and rely on
44022       // MOVMSK combines to make sure its never worse than PTEST?
44023       unsigned EltBits = BCVT.getScalarSizeInBits();
44024       if (DAG.ComputeNumSignBits(BC) == EltBits) {
44025         assert(VT == MVT::i32 && "Expected i32 EFLAGS comparison result");
44026         APInt SignMask = APInt::getSignMask(EltBits);
44027         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44028         if (SDValue Res =
44029                 TLI.SimplifyMultipleUseDemandedBits(BC, SignMask, DAG)) {
44030           // For vXi16 cases we need to use pmovmksb and extract every other
44031           // sign bit.
44032           SDLoc DL(EFLAGS);
44033           if (EltBits == 16) {
44034             MVT MovmskVT = BCVT.is128BitVector() ? MVT::v16i8 : MVT::v32i8;
44035             Res = DAG.getBitcast(MovmskVT, Res);
44036             Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
44037             Res = DAG.getNode(ISD::AND, DL, MVT::i32, Res,
44038                               DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
44039           } else {
44040             Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
44041           }
44042           return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Res,
44043                              DAG.getConstant(0, DL, MVT::i32));
44044         }
44045       }
44046     }
44047 
44048     // TESTZ(-1,X) == TESTZ(X,X)
44049     if (ISD::isBuildVectorAllOnes(Op0.getNode()))
44050       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op1, Op1);
44051 
44052     // TESTZ(X,-1) == TESTZ(X,X)
44053     if (ISD::isBuildVectorAllOnes(Op1.getNode()))
44054       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op0, Op0);
44055   }
44056 
44057   return SDValue();
44058 }
44059 
44060 // Attempt to simplify the MOVMSK input based on the comparison type.
44061 static SDValue combineSetCCMOVMSK(SDValue EFLAGS, X86::CondCode &CC,
44062                                   SelectionDAG &DAG,
44063                                   const X86Subtarget &Subtarget) {
44064   // Handle eq/ne against zero (any_of).
44065   // Handle eq/ne against -1 (all_of).
44066   if (!(CC == X86::COND_E || CC == X86::COND_NE))
44067     return SDValue();
44068   if (EFLAGS.getValueType() != MVT::i32)
44069     return SDValue();
44070   unsigned CmpOpcode = EFLAGS.getOpcode();
44071   if (CmpOpcode != X86ISD::CMP && CmpOpcode != X86ISD::SUB)
44072     return SDValue();
44073   auto *CmpConstant = dyn_cast<ConstantSDNode>(EFLAGS.getOperand(1));
44074   if (!CmpConstant)
44075     return SDValue();
44076   const APInt &CmpVal = CmpConstant->getAPIntValue();
44077 
44078   SDValue CmpOp = EFLAGS.getOperand(0);
44079   unsigned CmpBits = CmpOp.getValueSizeInBits();
44080   assert(CmpBits == CmpVal.getBitWidth() && "Value size mismatch");
44081 
44082   // Peek through any truncate.
44083   if (CmpOp.getOpcode() == ISD::TRUNCATE)
44084     CmpOp = CmpOp.getOperand(0);
44085 
44086   // Bail if we don't find a MOVMSK.
44087   if (CmpOp.getOpcode() != X86ISD::MOVMSK)
44088     return SDValue();
44089 
44090   SDValue Vec = CmpOp.getOperand(0);
44091   MVT VecVT = Vec.getSimpleValueType();
44092   assert((VecVT.is128BitVector() || VecVT.is256BitVector()) &&
44093          "Unexpected MOVMSK operand");
44094   unsigned NumElts = VecVT.getVectorNumElements();
44095   unsigned NumEltBits = VecVT.getScalarSizeInBits();
44096 
44097   bool IsAnyOf = CmpOpcode == X86ISD::CMP && CmpVal.isZero();
44098   bool IsAllOf = CmpOpcode == X86ISD::SUB && NumElts <= CmpBits &&
44099                  CmpVal.isMask(NumElts);
44100   if (!IsAnyOf && !IsAllOf)
44101     return SDValue();
44102 
44103   // See if we can peek through to a vector with a wider element type, if the
44104   // signbits extend down to all the sub-elements as well.
44105   // Calling MOVMSK with the wider type, avoiding the bitcast, helps expose
44106   // potential SimplifyDemandedBits/Elts cases.
44107   // If we looked through a truncate that discard bits, we can't do this
44108   // transform.
44109   // FIXME: We could do this transform for truncates that discarded bits by
44110   // inserting an AND mask between the new MOVMSK and the CMP.
44111   if (Vec.getOpcode() == ISD::BITCAST && NumElts <= CmpBits) {
44112     SDValue BC = peekThroughBitcasts(Vec);
44113     MVT BCVT = BC.getSimpleValueType();
44114     unsigned BCNumElts = BCVT.getVectorNumElements();
44115     unsigned BCNumEltBits = BCVT.getScalarSizeInBits();
44116     if ((BCNumEltBits == 32 || BCNumEltBits == 64) &&
44117         BCNumEltBits > NumEltBits &&
44118         DAG.ComputeNumSignBits(BC) > (BCNumEltBits - NumEltBits)) {
44119       SDLoc DL(EFLAGS);
44120       unsigned CmpMask = IsAnyOf ? 0 : ((1 << BCNumElts) - 1);
44121       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
44122                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, BC),
44123                          DAG.getConstant(CmpMask, DL, MVT::i32));
44124     }
44125   }
44126 
44127   // MOVMSK(PCMPEQ(X,0)) == -1 -> PTESTZ(X,X).
44128   // MOVMSK(PCMPEQ(X,0)) != -1 -> !PTESTZ(X,X).
44129   if (IsAllOf && Subtarget.hasSSE41()) {
44130     SDValue BC = peekThroughBitcasts(Vec);
44131     if (BC.getOpcode() == X86ISD::PCMPEQ &&
44132         ISD::isBuildVectorAllZeros(BC.getOperand(1).getNode())) {
44133       MVT TestVT = VecVT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
44134       SDValue V = DAG.getBitcast(TestVT, BC.getOperand(0));
44135       return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
44136     }
44137   }
44138 
44139   // See if we can avoid a PACKSS by calling MOVMSK on the sources.
44140   // For vXi16 cases we can use a v2Xi8 PMOVMSKB. We must mask out
44141   // sign bits prior to the comparison with zero unless we know that
44142   // the vXi16 splats the sign bit down to the lower i8 half.
44143   // TODO: Handle all_of patterns.
44144   if (Vec.getOpcode() == X86ISD::PACKSS && VecVT == MVT::v16i8) {
44145     SDValue VecOp0 = Vec.getOperand(0);
44146     SDValue VecOp1 = Vec.getOperand(1);
44147     bool SignExt0 = DAG.ComputeNumSignBits(VecOp0) > 8;
44148     bool SignExt1 = DAG.ComputeNumSignBits(VecOp1) > 8;
44149     // PMOVMSKB(PACKSSBW(X, undef)) -> PMOVMSKB(BITCAST_v16i8(X)) & 0xAAAA.
44150     if (IsAnyOf && CmpBits == 8 && VecOp1.isUndef()) {
44151       SDLoc DL(EFLAGS);
44152       SDValue Result = DAG.getBitcast(MVT::v16i8, VecOp0);
44153       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
44154       Result = DAG.getZExtOrTrunc(Result, DL, MVT::i16);
44155       if (!SignExt0) {
44156         Result = DAG.getNode(ISD::AND, DL, MVT::i16, Result,
44157                              DAG.getConstant(0xAAAA, DL, MVT::i16));
44158       }
44159       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
44160                          DAG.getConstant(0, DL, MVT::i16));
44161     }
44162     // PMOVMSKB(PACKSSBW(LO(X), HI(X)))
44163     // -> PMOVMSKB(BITCAST_v32i8(X)) & 0xAAAAAAAA.
44164     if (CmpBits >= 16 && Subtarget.hasInt256() &&
44165         VecOp0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
44166         VecOp1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
44167         VecOp0.getOperand(0) == VecOp1.getOperand(0) &&
44168         VecOp0.getConstantOperandAPInt(1) == 0 &&
44169         VecOp1.getConstantOperandAPInt(1) == 8 &&
44170         (IsAnyOf || (SignExt0 && SignExt1))) {
44171       SDLoc DL(EFLAGS);
44172       SDValue Result = DAG.getBitcast(MVT::v32i8, VecOp0.getOperand(0));
44173       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
44174       unsigned CmpMask = IsAnyOf ? 0 : 0xFFFFFFFF;
44175       if (!SignExt0 || !SignExt1) {
44176         assert(IsAnyOf && "Only perform v16i16 signmasks for any_of patterns");
44177         Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
44178                              DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
44179       }
44180       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
44181                          DAG.getConstant(CmpMask, DL, MVT::i32));
44182     }
44183   }
44184 
44185   // MOVMSK(SHUFFLE(X,u)) -> MOVMSK(X) iff every element is referenced.
44186   SmallVector<int, 32> ShuffleMask;
44187   SmallVector<SDValue, 2> ShuffleInputs;
44188   if (NumElts <= CmpBits &&
44189       getTargetShuffleInputs(peekThroughBitcasts(Vec), ShuffleInputs,
44190                              ShuffleMask, DAG) &&
44191       ShuffleInputs.size() == 1 && !isAnyZeroOrUndef(ShuffleMask) &&
44192       ShuffleInputs[0].getValueSizeInBits() == VecVT.getSizeInBits()) {
44193     unsigned NumShuffleElts = ShuffleMask.size();
44194     APInt DemandedElts = APInt::getZero(NumShuffleElts);
44195     for (int M : ShuffleMask) {
44196       assert(0 <= M && M < (int)NumShuffleElts && "Bad unary shuffle index");
44197       DemandedElts.setBit(M);
44198     }
44199     if (DemandedElts.isAllOnes()) {
44200       SDLoc DL(EFLAGS);
44201       SDValue Result = DAG.getBitcast(VecVT, ShuffleInputs[0]);
44202       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
44203       Result =
44204           DAG.getZExtOrTrunc(Result, DL, EFLAGS.getOperand(0).getValueType());
44205       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
44206                          EFLAGS.getOperand(1));
44207     }
44208   }
44209 
44210   return SDValue();
44211 }
44212 
44213 /// Optimize an EFLAGS definition used according to the condition code \p CC
44214 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
44215 /// uses of chain values.
44216 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
44217                                   SelectionDAG &DAG,
44218                                   const X86Subtarget &Subtarget) {
44219   if (CC == X86::COND_B)
44220     if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
44221       return Flags;
44222 
44223   if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
44224     return R;
44225 
44226   if (SDValue R = combinePTESTCC(EFLAGS, CC, DAG, Subtarget))
44227     return R;
44228 
44229   if (SDValue R = combineSetCCMOVMSK(EFLAGS, CC, DAG, Subtarget))
44230     return R;
44231 
44232   return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
44233 }
44234 
44235 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
44236 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
44237                            TargetLowering::DAGCombinerInfo &DCI,
44238                            const X86Subtarget &Subtarget) {
44239   SDLoc DL(N);
44240 
44241   SDValue FalseOp = N->getOperand(0);
44242   SDValue TrueOp = N->getOperand(1);
44243   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
44244   SDValue Cond = N->getOperand(3);
44245 
44246   // cmov X, X, ?, ? --> X
44247   if (TrueOp == FalseOp)
44248     return TrueOp;
44249 
44250   // Try to simplify the EFLAGS and condition code operands.
44251   // We can't always do this as FCMOV only supports a subset of X86 cond.
44252   if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
44253     if (!(FalseOp.getValueType() == MVT::f80 ||
44254           (FalseOp.getValueType() == MVT::f64 && !Subtarget.hasSSE2()) ||
44255           (FalseOp.getValueType() == MVT::f32 && !Subtarget.hasSSE1())) ||
44256         !Subtarget.hasCMov() || hasFPCMov(CC)) {
44257       SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
44258                        Flags};
44259       return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
44260     }
44261   }
44262 
44263   // If this is a select between two integer constants, try to do some
44264   // optimizations.  Note that the operands are ordered the opposite of SELECT
44265   // operands.
44266   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
44267     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
44268       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
44269       // larger than FalseC (the false value).
44270       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
44271         CC = X86::GetOppositeBranchCondition(CC);
44272         std::swap(TrueC, FalseC);
44273         std::swap(TrueOp, FalseOp);
44274       }
44275 
44276       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
44277       // This is efficient for any integer data type (including i8/i16) and
44278       // shift amount.
44279       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
44280         Cond = getSETCC(CC, Cond, DL, DAG);
44281 
44282         // Zero extend the condition if needed.
44283         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
44284 
44285         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
44286         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
44287                            DAG.getConstant(ShAmt, DL, MVT::i8));
44288         return Cond;
44289       }
44290 
44291       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
44292       // for any integer data type, including i8/i16.
44293       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
44294         Cond = getSETCC(CC, Cond, DL, DAG);
44295 
44296         // Zero extend the condition if needed.
44297         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
44298                            FalseC->getValueType(0), Cond);
44299         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
44300                            SDValue(FalseC, 0));
44301         return Cond;
44302       }
44303 
44304       // Optimize cases that will turn into an LEA instruction.  This requires
44305       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
44306       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
44307         APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
44308         assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&
44309                "Implicit constant truncation");
44310 
44311         bool isFastMultiplier = false;
44312         if (Diff.ult(10)) {
44313           switch (Diff.getZExtValue()) {
44314           default: break;
44315           case 1:  // result = add base, cond
44316           case 2:  // result = lea base(    , cond*2)
44317           case 3:  // result = lea base(cond, cond*2)
44318           case 4:  // result = lea base(    , cond*4)
44319           case 5:  // result = lea base(cond, cond*4)
44320           case 8:  // result = lea base(    , cond*8)
44321           case 9:  // result = lea base(cond, cond*8)
44322             isFastMultiplier = true;
44323             break;
44324           }
44325         }
44326 
44327         if (isFastMultiplier) {
44328           Cond = getSETCC(CC, Cond, DL ,DAG);
44329           // Zero extend the condition if needed.
44330           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
44331                              Cond);
44332           // Scale the condition by the difference.
44333           if (Diff != 1)
44334             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
44335                                DAG.getConstant(Diff, DL, Cond.getValueType()));
44336 
44337           // Add the base if non-zero.
44338           if (FalseC->getAPIntValue() != 0)
44339             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
44340                                SDValue(FalseC, 0));
44341           return Cond;
44342         }
44343       }
44344     }
44345   }
44346 
44347   // Handle these cases:
44348   //   (select (x != c), e, c) -> select (x != c), e, x),
44349   //   (select (x == c), c, e) -> select (x == c), x, e)
44350   // where the c is an integer constant, and the "select" is the combination
44351   // of CMOV and CMP.
44352   //
44353   // The rationale for this change is that the conditional-move from a constant
44354   // needs two instructions, however, conditional-move from a register needs
44355   // only one instruction.
44356   //
44357   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
44358   //  some instruction-combining opportunities. This opt needs to be
44359   //  postponed as late as possible.
44360   //
44361   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
44362     // the DCI.xxxx conditions are provided to postpone the optimization as
44363     // late as possible.
44364 
44365     ConstantSDNode *CmpAgainst = nullptr;
44366     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
44367         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
44368         !isa<ConstantSDNode>(Cond.getOperand(0))) {
44369 
44370       if (CC == X86::COND_NE &&
44371           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
44372         CC = X86::GetOppositeBranchCondition(CC);
44373         std::swap(TrueOp, FalseOp);
44374       }
44375 
44376       if (CC == X86::COND_E &&
44377           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
44378         SDValue Ops[] = {FalseOp, Cond.getOperand(0),
44379                          DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
44380         return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
44381       }
44382     }
44383   }
44384 
44385   // Fold and/or of setcc's to double CMOV:
44386   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
44387   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
44388   //
44389   // This combine lets us generate:
44390   //   cmovcc1 (jcc1 if we don't have CMOV)
44391   //   cmovcc2 (same)
44392   // instead of:
44393   //   setcc1
44394   //   setcc2
44395   //   and/or
44396   //   cmovne (jne if we don't have CMOV)
44397   // When we can't use the CMOV instruction, it might increase branch
44398   // mispredicts.
44399   // When we can use CMOV, or when there is no mispredict, this improves
44400   // throughput and reduces register pressure.
44401   //
44402   if (CC == X86::COND_NE) {
44403     SDValue Flags;
44404     X86::CondCode CC0, CC1;
44405     bool isAndSetCC;
44406     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
44407       if (isAndSetCC) {
44408         std::swap(FalseOp, TrueOp);
44409         CC0 = X86::GetOppositeBranchCondition(CC0);
44410         CC1 = X86::GetOppositeBranchCondition(CC1);
44411       }
44412 
44413       SDValue LOps[] = {FalseOp, TrueOp,
44414                         DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
44415       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
44416       SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
44417                        Flags};
44418       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
44419       return CMOV;
44420     }
44421   }
44422 
44423   // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
44424   //      (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
44425   // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
44426   //    (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
44427   if ((CC == X86::COND_NE || CC == X86::COND_E) &&
44428       Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
44429     SDValue Add = TrueOp;
44430     SDValue Const = FalseOp;
44431     // Canonicalize the condition code for easier matching and output.
44432     if (CC == X86::COND_E)
44433       std::swap(Add, Const);
44434 
44435     // We might have replaced the constant in the cmov with the LHS of the
44436     // compare. If so change it to the RHS of the compare.
44437     if (Const == Cond.getOperand(0))
44438       Const = Cond.getOperand(1);
44439 
44440     // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
44441     if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
44442         Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
44443         (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
44444          Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
44445         Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
44446       EVT VT = N->getValueType(0);
44447       // This should constant fold.
44448       SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
44449       SDValue CMov =
44450           DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
44451                       DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
44452       return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
44453     }
44454   }
44455 
44456   return SDValue();
44457 }
44458 
44459 /// Different mul shrinking modes.
44460 enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
44461 
44462 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
44463   EVT VT = N->getOperand(0).getValueType();
44464   if (VT.getScalarSizeInBits() != 32)
44465     return false;
44466 
44467   assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
44468   unsigned SignBits[2] = {1, 1};
44469   bool IsPositive[2] = {false, false};
44470   for (unsigned i = 0; i < 2; i++) {
44471     SDValue Opd = N->getOperand(i);
44472 
44473     SignBits[i] = DAG.ComputeNumSignBits(Opd);
44474     IsPositive[i] = DAG.SignBitIsZero(Opd);
44475   }
44476 
44477   bool AllPositive = IsPositive[0] && IsPositive[1];
44478   unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
44479   // When ranges are from -128 ~ 127, use MULS8 mode.
44480   if (MinSignBits >= 25)
44481     Mode = ShrinkMode::MULS8;
44482   // When ranges are from 0 ~ 255, use MULU8 mode.
44483   else if (AllPositive && MinSignBits >= 24)
44484     Mode = ShrinkMode::MULU8;
44485   // When ranges are from -32768 ~ 32767, use MULS16 mode.
44486   else if (MinSignBits >= 17)
44487     Mode = ShrinkMode::MULS16;
44488   // When ranges are from 0 ~ 65535, use MULU16 mode.
44489   else if (AllPositive && MinSignBits >= 16)
44490     Mode = ShrinkMode::MULU16;
44491   else
44492     return false;
44493   return true;
44494 }
44495 
44496 /// When the operands of vector mul are extended from smaller size values,
44497 /// like i8 and i16, the type of mul may be shrinked to generate more
44498 /// efficient code. Two typical patterns are handled:
44499 /// Pattern1:
44500 ///     %2 = sext/zext <N x i8> %1 to <N x i32>
44501 ///     %4 = sext/zext <N x i8> %3 to <N x i32>
44502 //   or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
44503 ///     %5 = mul <N x i32> %2, %4
44504 ///
44505 /// Pattern2:
44506 ///     %2 = zext/sext <N x i16> %1 to <N x i32>
44507 ///     %4 = zext/sext <N x i16> %3 to <N x i32>
44508 ///  or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
44509 ///     %5 = mul <N x i32> %2, %4
44510 ///
44511 /// There are four mul shrinking modes:
44512 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
44513 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
44514 /// generate pmullw+sext32 for it (MULS8 mode).
44515 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
44516 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
44517 /// generate pmullw+zext32 for it (MULU8 mode).
44518 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
44519 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
44520 /// generate pmullw+pmulhw for it (MULS16 mode).
44521 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
44522 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
44523 /// generate pmullw+pmulhuw for it (MULU16 mode).
44524 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
44525                                const X86Subtarget &Subtarget) {
44526   // Check for legality
44527   // pmullw/pmulhw are not supported by SSE.
44528   if (!Subtarget.hasSSE2())
44529     return SDValue();
44530 
44531   // Check for profitability
44532   // pmulld is supported since SSE41. It is better to use pmulld
44533   // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
44534   // the expansion.
44535   bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
44536   if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
44537     return SDValue();
44538 
44539   ShrinkMode Mode;
44540   if (!canReduceVMulWidth(N, DAG, Mode))
44541     return SDValue();
44542 
44543   SDLoc DL(N);
44544   SDValue N0 = N->getOperand(0);
44545   SDValue N1 = N->getOperand(1);
44546   EVT VT = N->getOperand(0).getValueType();
44547   unsigned NumElts = VT.getVectorNumElements();
44548   if ((NumElts % 2) != 0)
44549     return SDValue();
44550 
44551   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
44552 
44553   // Shrink the operands of mul.
44554   SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
44555   SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
44556 
44557   // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
44558   // lower part is needed.
44559   SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
44560   if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
44561     return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
44562                                                    : ISD::SIGN_EXTEND,
44563                        DL, VT, MulLo);
44564 
44565   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts / 2);
44566   // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
44567   // the higher part is also needed.
44568   SDValue MulHi =
44569       DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
44570                   ReducedVT, NewN0, NewN1);
44571 
44572   // Repack the lower part and higher part result of mul into a wider
44573   // result.
44574   // Generate shuffle functioning as punpcklwd.
44575   SmallVector<int, 16> ShuffleMask(NumElts);
44576   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
44577     ShuffleMask[2 * i] = i;
44578     ShuffleMask[2 * i + 1] = i + NumElts;
44579   }
44580   SDValue ResLo =
44581       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
44582   ResLo = DAG.getBitcast(ResVT, ResLo);
44583   // Generate shuffle functioning as punpckhwd.
44584   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
44585     ShuffleMask[2 * i] = i + NumElts / 2;
44586     ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
44587   }
44588   SDValue ResHi =
44589       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
44590   ResHi = DAG.getBitcast(ResVT, ResHi);
44591   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
44592 }
44593 
44594 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
44595                                  EVT VT, const SDLoc &DL) {
44596 
44597   auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
44598     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
44599                                  DAG.getConstant(Mult, DL, VT));
44600     Result = DAG.getNode(ISD::SHL, DL, VT, Result,
44601                          DAG.getConstant(Shift, DL, MVT::i8));
44602     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
44603                          N->getOperand(0));
44604     return Result;
44605   };
44606 
44607   auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
44608     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
44609                                  DAG.getConstant(Mul1, DL, VT));
44610     Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
44611                          DAG.getConstant(Mul2, DL, VT));
44612     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
44613                          N->getOperand(0));
44614     return Result;
44615   };
44616 
44617   switch (MulAmt) {
44618   default:
44619     break;
44620   case 11:
44621     // mul x, 11 => add ((shl (mul x, 5), 1), x)
44622     return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
44623   case 21:
44624     // mul x, 21 => add ((shl (mul x, 5), 2), x)
44625     return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
44626   case 41:
44627     // mul x, 41 => add ((shl (mul x, 5), 3), x)
44628     return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
44629   case 22:
44630     // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
44631     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
44632                        combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
44633   case 19:
44634     // mul x, 19 => add ((shl (mul x, 9), 1), x)
44635     return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
44636   case 37:
44637     // mul x, 37 => add ((shl (mul x, 9), 2), x)
44638     return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
44639   case 73:
44640     // mul x, 73 => add ((shl (mul x, 9), 3), x)
44641     return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
44642   case 13:
44643     // mul x, 13 => add ((shl (mul x, 3), 2), x)
44644     return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
44645   case 23:
44646     // mul x, 23 => sub ((shl (mul x, 3), 3), x)
44647     return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
44648   case 26:
44649     // mul x, 26 => add ((mul (mul x, 5), 5), x)
44650     return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
44651   case 28:
44652     // mul x, 28 => add ((mul (mul x, 9), 3), x)
44653     return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
44654   case 29:
44655     // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
44656     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
44657                        combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
44658   }
44659 
44660   // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
44661   // by a single LEA.
44662   // First check if this a sum of two power of 2s because that's easy. Then
44663   // count how many zeros are up to the first bit.
44664   // TODO: We can do this even without LEA at a cost of two shifts and an add.
44665   if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
44666     unsigned ScaleShift = countTrailingZeros(MulAmt);
44667     if (ScaleShift >= 1 && ScaleShift < 4) {
44668       unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
44669       SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
44670                                    DAG.getConstant(ShiftAmt, DL, MVT::i8));
44671       SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
44672                                    DAG.getConstant(ScaleShift, DL, MVT::i8));
44673       return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
44674     }
44675   }
44676 
44677   return SDValue();
44678 }
44679 
44680 // If the upper 17 bits of either element are zero and the other element are
44681 // zero/sign bits then we can use PMADDWD, which is always at least as quick as
44682 // PMULLD, except on KNL.
44683 static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
44684                                    const X86Subtarget &Subtarget) {
44685   if (!Subtarget.hasSSE2())
44686     return SDValue();
44687 
44688   if (Subtarget.isPMADDWDSlow())
44689     return SDValue();
44690 
44691   EVT VT = N->getValueType(0);
44692 
44693   // Only support vXi32 vectors.
44694   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
44695     return SDValue();
44696 
44697   // Make sure the type is legal or can split/widen to a legal type.
44698   // With AVX512 but without BWI, we would need to split v32i16.
44699   unsigned NumElts = VT.getVectorNumElements();
44700   if (NumElts == 1 || !isPowerOf2_32(NumElts))
44701     return SDValue();
44702 
44703   EVT WVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, 2 * NumElts);
44704 
44705   // With AVX512 but without BWI, we would need to split v32i16.
44706   if (32 <= (2 * NumElts) && Subtarget.hasAVX512() && !Subtarget.hasBWI())
44707     return SDValue();
44708 
44709   SDValue N0 = N->getOperand(0);
44710   SDValue N1 = N->getOperand(1);
44711 
44712   // If we are zero/sign extending two steps without SSE4.1, its better to
44713   // reduce the vmul width instead.
44714   if (!Subtarget.hasSSE41() &&
44715       (((N0.getOpcode() == ISD::ZERO_EXTEND &&
44716          N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
44717         (N1.getOpcode() == ISD::ZERO_EXTEND &&
44718          N1.getOperand(0).getScalarValueSizeInBits() <= 8)) ||
44719        ((N0.getOpcode() == ISD::SIGN_EXTEND &&
44720          N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
44721         (N1.getOpcode() == ISD::SIGN_EXTEND &&
44722          N1.getOperand(0).getScalarValueSizeInBits() <= 8))))
44723     return SDValue();
44724 
44725   // If we are sign extending a wide vector without SSE4.1, its better to reduce
44726   // the vmul width instead.
44727   if (!Subtarget.hasSSE41() &&
44728       (N0.getOpcode() == ISD::SIGN_EXTEND &&
44729        N0.getOperand(0).getValueSizeInBits() > 128) &&
44730       (N1.getOpcode() == ISD::SIGN_EXTEND &&
44731        N1.getOperand(0).getValueSizeInBits() > 128))
44732     return SDValue();
44733 
44734   // Sign bits must extend down to the lowest i16.
44735   if (DAG.ComputeMinSignedBits(N1) > 16 || DAG.ComputeMinSignedBits(N0) > 16)
44736     return SDValue();
44737 
44738   // At least one of the elements must be zero in the upper 17 bits, or can be
44739   // safely made zero without altering the final result.
44740   auto GetZeroableOp = [&](SDValue Op) {
44741     APInt Mask17 = APInt::getHighBitsSet(32, 17);
44742     if (DAG.MaskedValueIsZero(Op, Mask17))
44743       return Op;
44744     // Mask off upper 16-bits of sign-extended constants.
44745     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()))
44746       return DAG.getNode(ISD::AND, SDLoc(N), VT, Op,
44747                          DAG.getConstant(0xFFFF, SDLoc(N), VT));
44748     if (Op.getOpcode() == ISD::SIGN_EXTEND && N->isOnlyUserOf(Op.getNode())) {
44749       SDValue Src = Op.getOperand(0);
44750       // Convert sext(vXi16) to zext(vXi16).
44751       if (Src.getScalarValueSizeInBits() == 16 && VT.getSizeInBits() <= 128)
44752         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Src);
44753       // Convert sext(vXi8) to zext(vXi16 sext(vXi8)) on pre-SSE41 targets
44754       // which will expand the extension.
44755       if (Src.getScalarValueSizeInBits() < 16 && !Subtarget.hasSSE41()) {
44756         EVT ExtVT = VT.changeVectorElementType(MVT::i16);
44757         Src = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), ExtVT, Src);
44758         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Src);
44759       }
44760     }
44761     // Convert SIGN_EXTEND_VECTOR_INREG to ZEXT_EXTEND_VECTOR_INREG.
44762     if (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG &&
44763         N->isOnlyUserOf(Op.getNode())) {
44764       SDValue Src = Op.getOperand(0);
44765       if (Src.getScalarValueSizeInBits() == 16)
44766         return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(N), VT, Src);
44767     }
44768     // Convert VSRAI(Op, 16) to VSRLI(Op, 16).
44769     if (Op.getOpcode() == X86ISD::VSRAI && Op.getConstantOperandVal(1) == 16 &&
44770         N->isOnlyUserOf(Op.getNode())) {
44771       return DAG.getNode(X86ISD::VSRLI, SDLoc(N), VT, Op.getOperand(0),
44772                          Op.getOperand(1));
44773     }
44774     return SDValue();
44775   };
44776   SDValue ZeroN0 = GetZeroableOp(N0);
44777   SDValue ZeroN1 = GetZeroableOp(N1);
44778   if (!ZeroN0 && !ZeroN1)
44779     return SDValue();
44780   N0 = ZeroN0 ? ZeroN0 : N0;
44781   N1 = ZeroN1 ? ZeroN1 : N1;
44782 
44783   // Use SplitOpsAndApply to handle AVX splitting.
44784   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
44785                            ArrayRef<SDValue> Ops) {
44786     MVT OpVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
44787     return DAG.getNode(X86ISD::VPMADDWD, DL, OpVT, Ops);
44788   };
44789   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
44790                           { DAG.getBitcast(WVT, N0), DAG.getBitcast(WVT, N1) },
44791                           PMADDWDBuilder);
44792 }
44793 
44794 static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
44795                                   const X86Subtarget &Subtarget) {
44796   if (!Subtarget.hasSSE2())
44797     return SDValue();
44798 
44799   EVT VT = N->getValueType(0);
44800 
44801   // Only support vXi64 vectors.
44802   if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
44803       VT.getVectorNumElements() < 2 ||
44804       !isPowerOf2_32(VT.getVectorNumElements()))
44805     return SDValue();
44806 
44807   SDValue N0 = N->getOperand(0);
44808   SDValue N1 = N->getOperand(1);
44809 
44810   // MULDQ returns the 64-bit result of the signed multiplication of the lower
44811   // 32-bits. We can lower with this if the sign bits stretch that far.
44812   if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
44813       DAG.ComputeNumSignBits(N1) > 32) {
44814     auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
44815                             ArrayRef<SDValue> Ops) {
44816       return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
44817     };
44818     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
44819                             PMULDQBuilder, /*CheckBWI*/false);
44820   }
44821 
44822   // If the upper bits are zero we can use a single pmuludq.
44823   APInt Mask = APInt::getHighBitsSet(64, 32);
44824   if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
44825     auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
44826                              ArrayRef<SDValue> Ops) {
44827       return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
44828     };
44829     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
44830                             PMULUDQBuilder, /*CheckBWI*/false);
44831   }
44832 
44833   return SDValue();
44834 }
44835 
44836 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
44837                           TargetLowering::DAGCombinerInfo &DCI,
44838                           const X86Subtarget &Subtarget) {
44839   EVT VT = N->getValueType(0);
44840 
44841   if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
44842     return V;
44843 
44844   if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
44845     return V;
44846 
44847   if (DCI.isBeforeLegalize() && VT.isVector())
44848     return reduceVMULWidth(N, DAG, Subtarget);
44849 
44850   // Optimize a single multiply with constant into two operations in order to
44851   // implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
44852   if (!MulConstantOptimization)
44853     return SDValue();
44854 
44855   // An imul is usually smaller than the alternative sequence.
44856   if (DAG.getMachineFunction().getFunction().hasMinSize())
44857     return SDValue();
44858 
44859   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
44860     return SDValue();
44861 
44862   if (VT != MVT::i64 && VT != MVT::i32)
44863     return SDValue();
44864 
44865   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
44866   if (!C)
44867     return SDValue();
44868   if (isPowerOf2_64(C->getZExtValue()))
44869     return SDValue();
44870 
44871   int64_t SignMulAmt = C->getSExtValue();
44872   assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
44873   uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
44874 
44875   SDLoc DL(N);
44876   if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
44877     SDValue NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
44878                                  DAG.getConstant(AbsMulAmt, DL, VT));
44879     if (SignMulAmt < 0)
44880       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
44881                            NewMul);
44882 
44883     return NewMul;
44884   }
44885 
44886   uint64_t MulAmt1 = 0;
44887   uint64_t MulAmt2 = 0;
44888   if ((AbsMulAmt % 9) == 0) {
44889     MulAmt1 = 9;
44890     MulAmt2 = AbsMulAmt / 9;
44891   } else if ((AbsMulAmt % 5) == 0) {
44892     MulAmt1 = 5;
44893     MulAmt2 = AbsMulAmt / 5;
44894   } else if ((AbsMulAmt % 3) == 0) {
44895     MulAmt1 = 3;
44896     MulAmt2 = AbsMulAmt / 3;
44897   }
44898 
44899   SDValue NewMul;
44900   // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
44901   if (MulAmt2 &&
44902       (isPowerOf2_64(MulAmt2) ||
44903        (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
44904 
44905     if (isPowerOf2_64(MulAmt2) &&
44906         !(SignMulAmt >= 0 && N->hasOneUse() &&
44907           N->use_begin()->getOpcode() == ISD::ADD))
44908       // If second multiplifer is pow2, issue it first. We want the multiply by
44909       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
44910       // is an add. Only do this for positive multiply amounts since the
44911       // negate would prevent it from being used as an address mode anyway.
44912       std::swap(MulAmt1, MulAmt2);
44913 
44914     if (isPowerOf2_64(MulAmt1))
44915       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
44916                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
44917     else
44918       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
44919                            DAG.getConstant(MulAmt1, DL, VT));
44920 
44921     if (isPowerOf2_64(MulAmt2))
44922       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
44923                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
44924     else
44925       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
44926                            DAG.getConstant(MulAmt2, DL, VT));
44927 
44928     // Negate the result.
44929     if (SignMulAmt < 0)
44930       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
44931                            NewMul);
44932   } else if (!Subtarget.slowLEA())
44933     NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
44934 
44935   if (!NewMul) {
44936     assert(C->getZExtValue() != 0 &&
44937            C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) &&
44938            "Both cases that could cause potential overflows should have "
44939            "already been handled.");
44940     if (isPowerOf2_64(AbsMulAmt - 1)) {
44941       // (mul x, 2^N + 1) => (add (shl x, N), x)
44942       NewMul = DAG.getNode(
44943           ISD::ADD, DL, VT, N->getOperand(0),
44944           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
44945                       DAG.getConstant(Log2_64(AbsMulAmt - 1), DL,
44946                                       MVT::i8)));
44947       // To negate, subtract the number from zero
44948       if (SignMulAmt < 0)
44949         NewMul = DAG.getNode(ISD::SUB, DL, VT,
44950                              DAG.getConstant(0, DL, VT), NewMul);
44951     } else if (isPowerOf2_64(AbsMulAmt + 1)) {
44952       // (mul x, 2^N - 1) => (sub (shl x, N), x)
44953       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
44954                            DAG.getConstant(Log2_64(AbsMulAmt + 1),
44955                                            DL, MVT::i8));
44956       // To negate, reverse the operands of the subtract.
44957       if (SignMulAmt < 0)
44958         NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
44959       else
44960         NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
44961     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2)) {
44962       // (mul x, 2^N + 2) => (add (add (shl x, N), x), x)
44963       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
44964                            DAG.getConstant(Log2_64(AbsMulAmt - 2),
44965                                            DL, MVT::i8));
44966       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
44967       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
44968     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2)) {
44969       // (mul x, 2^N - 2) => (sub (sub (shl x, N), x), x)
44970       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
44971                            DAG.getConstant(Log2_64(AbsMulAmt + 2),
44972                                            DL, MVT::i8));
44973       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
44974       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
44975     }
44976   }
44977 
44978   return NewMul;
44979 }
44980 
44981 // Try to form a MULHU or MULHS node by looking for
44982 // (srl (mul ext, ext), 16)
44983 // TODO: This is X86 specific because we want to be able to handle wide types
44984 // before type legalization. But we can only do it if the vector will be
44985 // legalized via widening/splitting. Type legalization can't handle promotion
44986 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
44987 // combiner.
44988 static SDValue combineShiftToPMULH(SDNode *N, SelectionDAG &DAG,
44989                                    const X86Subtarget &Subtarget) {
44990   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
44991            "SRL or SRA node is required here!");
44992   SDLoc DL(N);
44993 
44994   if (!Subtarget.hasSSE2())
44995     return SDValue();
44996 
44997   // The operation feeding into the shift must be a multiply.
44998   SDValue ShiftOperand = N->getOperand(0);
44999   if (ShiftOperand.getOpcode() != ISD::MUL || !ShiftOperand.hasOneUse())
45000     return SDValue();
45001 
45002   // Input type should be at least vXi32.
45003   EVT VT = N->getValueType(0);
45004   if (!VT.isVector() || VT.getVectorElementType().getSizeInBits() < 32)
45005     return SDValue();
45006 
45007   // Need a shift by 16.
45008   APInt ShiftAmt;
45009   if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), ShiftAmt) ||
45010       ShiftAmt != 16)
45011     return SDValue();
45012 
45013   SDValue LHS = ShiftOperand.getOperand(0);
45014   SDValue RHS = ShiftOperand.getOperand(1);
45015 
45016   unsigned ExtOpc = LHS.getOpcode();
45017   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
45018       RHS.getOpcode() != ExtOpc)
45019     return SDValue();
45020 
45021   // Peek through the extends.
45022   LHS = LHS.getOperand(0);
45023   RHS = RHS.getOperand(0);
45024 
45025   // Ensure the input types match.
45026   EVT MulVT = LHS.getValueType();
45027   if (MulVT.getVectorElementType() != MVT::i16 || RHS.getValueType() != MulVT)
45028     return SDValue();
45029 
45030   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
45031   SDValue Mulh = DAG.getNode(Opc, DL, MulVT, LHS, RHS);
45032 
45033   ExtOpc = N->getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
45034   return DAG.getNode(ExtOpc, DL, VT, Mulh);
45035 }
45036 
45037 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
45038   SDValue N0 = N->getOperand(0);
45039   SDValue N1 = N->getOperand(1);
45040   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
45041   EVT VT = N0.getValueType();
45042 
45043   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
45044   // since the result of setcc_c is all zero's or all ones.
45045   if (VT.isInteger() && !VT.isVector() &&
45046       N1C && N0.getOpcode() == ISD::AND &&
45047       N0.getOperand(1).getOpcode() == ISD::Constant) {
45048     SDValue N00 = N0.getOperand(0);
45049     APInt Mask = N0.getConstantOperandAPInt(1);
45050     Mask <<= N1C->getAPIntValue();
45051     bool MaskOK = false;
45052     // We can handle cases concerning bit-widening nodes containing setcc_c if
45053     // we carefully interrogate the mask to make sure we are semantics
45054     // preserving.
45055     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
45056     // of the underlying setcc_c operation if the setcc_c was zero extended.
45057     // Consider the following example:
45058     //   zext(setcc_c)                 -> i32 0x0000FFFF
45059     //   c1                            -> i32 0x0000FFFF
45060     //   c2                            -> i32 0x00000001
45061     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
45062     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
45063     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
45064       MaskOK = true;
45065     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
45066                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
45067       MaskOK = true;
45068     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
45069                 N00.getOpcode() == ISD::ANY_EXTEND) &&
45070                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
45071       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
45072     }
45073     if (MaskOK && Mask != 0) {
45074       SDLoc DL(N);
45075       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
45076     }
45077   }
45078 
45079   // Hardware support for vector shifts is sparse which makes us scalarize the
45080   // vector operations in many cases. Also, on sandybridge ADD is faster than
45081   // shl.
45082   // (shl V, 1) -> add V,V
45083   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
45084     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
45085       assert(N0.getValueType().isVector() && "Invalid vector shift type");
45086       // We shift all of the values by one. In many cases we do not have
45087       // hardware support for this operation. This is better expressed as an ADD
45088       // of two values.
45089       if (N1SplatC->isOne())
45090         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
45091     }
45092 
45093   return SDValue();
45094 }
45095 
45096 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG,
45097                                            const X86Subtarget &Subtarget) {
45098   SDValue N0 = N->getOperand(0);
45099   SDValue N1 = N->getOperand(1);
45100   EVT VT = N0.getValueType();
45101   unsigned Size = VT.getSizeInBits();
45102 
45103   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
45104     return V;
45105 
45106   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
45107   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
45108   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
45109   // depending on sign of (SarConst - [56,48,32,24,16])
45110 
45111   // sexts in X86 are MOVs. The MOVs have the same code size
45112   // as above SHIFTs (only SHIFT on 1 has lower code size).
45113   // However the MOVs have 2 advantages to a SHIFT:
45114   // 1. MOVs can write to a register that differs from source
45115   // 2. MOVs accept memory operands
45116 
45117   if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
45118       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
45119       N0.getOperand(1).getOpcode() != ISD::Constant)
45120     return SDValue();
45121 
45122   SDValue N00 = N0.getOperand(0);
45123   SDValue N01 = N0.getOperand(1);
45124   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
45125   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
45126   EVT CVT = N1.getValueType();
45127 
45128   if (SarConst.isNegative())
45129     return SDValue();
45130 
45131   for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
45132     unsigned ShiftSize = SVT.getSizeInBits();
45133     // skipping types without corresponding sext/zext and
45134     // ShlConst that is not one of [56,48,32,24,16]
45135     if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
45136       continue;
45137     SDLoc DL(N);
45138     SDValue NN =
45139         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
45140     SarConst = SarConst - (Size - ShiftSize);
45141     if (SarConst == 0)
45142       return NN;
45143     else if (SarConst.isNegative())
45144       return DAG.getNode(ISD::SHL, DL, VT, NN,
45145                          DAG.getConstant(-SarConst, DL, CVT));
45146     else
45147       return DAG.getNode(ISD::SRA, DL, VT, NN,
45148                          DAG.getConstant(SarConst, DL, CVT));
45149   }
45150   return SDValue();
45151 }
45152 
45153 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
45154                                         TargetLowering::DAGCombinerInfo &DCI,
45155                                         const X86Subtarget &Subtarget) {
45156   SDValue N0 = N->getOperand(0);
45157   SDValue N1 = N->getOperand(1);
45158   EVT VT = N0.getValueType();
45159 
45160   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
45161     return V;
45162 
45163   // Only do this on the last DAG combine as it can interfere with other
45164   // combines.
45165   if (!DCI.isAfterLegalizeDAG())
45166     return SDValue();
45167 
45168   // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
45169   // TODO: This is a generic DAG combine that became an x86-only combine to
45170   // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
45171   // and-not ('andn').
45172   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
45173     return SDValue();
45174 
45175   auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
45176   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
45177   if (!ShiftC || !AndC)
45178     return SDValue();
45179 
45180   // If we can shrink the constant mask below 8-bits or 32-bits, then this
45181   // transform should reduce code size. It may also enable secondary transforms
45182   // from improved known-bits analysis or instruction selection.
45183   APInt MaskVal = AndC->getAPIntValue();
45184 
45185   // If this can be matched by a zero extend, don't optimize.
45186   if (MaskVal.isMask()) {
45187     unsigned TO = MaskVal.countTrailingOnes();
45188     if (TO >= 8 && isPowerOf2_32(TO))
45189       return SDValue();
45190   }
45191 
45192   APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
45193   unsigned OldMaskSize = MaskVal.getMinSignedBits();
45194   unsigned NewMaskSize = NewMaskVal.getMinSignedBits();
45195   if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
45196       (OldMaskSize > 32 && NewMaskSize <= 32)) {
45197     // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
45198     SDLoc DL(N);
45199     SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
45200     SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
45201     return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
45202   }
45203   return SDValue();
45204 }
45205 
45206 static SDValue combineHorizOpWithShuffle(SDNode *N, SelectionDAG &DAG,
45207                                          const X86Subtarget &Subtarget) {
45208   unsigned Opcode = N->getOpcode();
45209   assert(isHorizOp(Opcode) && "Unexpected hadd/hsub/pack opcode");
45210 
45211   SDLoc DL(N);
45212   EVT VT = N->getValueType(0);
45213   SDValue N0 = N->getOperand(0);
45214   SDValue N1 = N->getOperand(1);
45215   EVT SrcVT = N0.getValueType();
45216 
45217   SDValue BC0 =
45218       N->isOnlyUserOf(N0.getNode()) ? peekThroughOneUseBitcasts(N0) : N0;
45219   SDValue BC1 =
45220       N->isOnlyUserOf(N1.getNode()) ? peekThroughOneUseBitcasts(N1) : N1;
45221 
45222   // Attempt to fold HOP(LOSUBVECTOR(SHUFFLE(X)),HISUBVECTOR(SHUFFLE(X)))
45223   // to SHUFFLE(HOP(LOSUBVECTOR(X),HISUBVECTOR(X))), this is mainly for
45224   // truncation trees that help us avoid lane crossing shuffles.
45225   // TODO: There's a lot more we can do for PACK/HADD style shuffle combines.
45226   // TODO: We don't handle vXf64 shuffles yet.
45227   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32 &&
45228       BC0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
45229       BC1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
45230       BC0.getOperand(0) == BC1.getOperand(0) &&
45231       BC0.getOperand(0).getValueType().is256BitVector() &&
45232       BC0.getConstantOperandAPInt(1) == 0 &&
45233       BC1.getConstantOperandAPInt(1) ==
45234           BC0.getValueType().getVectorNumElements()) {
45235     SmallVector<SDValue> ShuffleOps;
45236     SmallVector<int> ShuffleMask, ScaledMask;
45237     SDValue Vec = peekThroughBitcasts(BC0.getOperand(0));
45238     if (getTargetShuffleInputs(Vec, ShuffleOps, ShuffleMask, DAG)) {
45239       resolveTargetShuffleInputsAndMask(ShuffleOps, ShuffleMask);
45240       // To keep the HOP LHS/RHS coherency, we must be able to scale the unary
45241       // shuffle to a v4X64 width - we can probably relax this in the future.
45242       if (!isAnyZero(ShuffleMask) && ShuffleOps.size() == 1 &&
45243           ShuffleOps[0].getValueType().is256BitVector() &&
45244           scaleShuffleElements(ShuffleMask, 4, ScaledMask)) {
45245         SDValue Lo, Hi;
45246         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
45247         std::tie(Lo, Hi) = DAG.SplitVector(ShuffleOps[0], DL);
45248         Lo = DAG.getBitcast(SrcVT, Lo);
45249         Hi = DAG.getBitcast(SrcVT, Hi);
45250         SDValue Res = DAG.getNode(Opcode, DL, VT, Lo, Hi);
45251         Res = DAG.getBitcast(ShufVT, Res);
45252         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ScaledMask);
45253         return DAG.getBitcast(VT, Res);
45254       }
45255     }
45256   }
45257 
45258   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(Z,W)) -> SHUFFLE(HOP()).
45259   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
45260     // If either/both ops are a shuffle that can scale to v2x64,
45261     // then see if we can perform this as a v4x32 post shuffle.
45262     SmallVector<SDValue> Ops0, Ops1;
45263     SmallVector<int> Mask0, Mask1, ScaledMask0, ScaledMask1;
45264     bool IsShuf0 =
45265         getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
45266         scaleShuffleElements(Mask0, 2, ScaledMask0) &&
45267         all_of(Ops0, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
45268     bool IsShuf1 =
45269         getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
45270         scaleShuffleElements(Mask1, 2, ScaledMask1) &&
45271         all_of(Ops1, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
45272     if (IsShuf0 || IsShuf1) {
45273       if (!IsShuf0) {
45274         Ops0.assign({BC0});
45275         ScaledMask0.assign({0, 1});
45276       }
45277       if (!IsShuf1) {
45278         Ops1.assign({BC1});
45279         ScaledMask1.assign({0, 1});
45280       }
45281 
45282       SDValue LHS, RHS;
45283       int PostShuffle[4] = {-1, -1, -1, -1};
45284       auto FindShuffleOpAndIdx = [&](int M, int &Idx, ArrayRef<SDValue> Ops) {
45285         if (M < 0)
45286           return true;
45287         Idx = M % 2;
45288         SDValue Src = Ops[M / 2];
45289         if (!LHS || LHS == Src) {
45290           LHS = Src;
45291           return true;
45292         }
45293         if (!RHS || RHS == Src) {
45294           Idx += 2;
45295           RHS = Src;
45296           return true;
45297         }
45298         return false;
45299       };
45300       if (FindShuffleOpAndIdx(ScaledMask0[0], PostShuffle[0], Ops0) &&
45301           FindShuffleOpAndIdx(ScaledMask0[1], PostShuffle[1], Ops0) &&
45302           FindShuffleOpAndIdx(ScaledMask1[0], PostShuffle[2], Ops1) &&
45303           FindShuffleOpAndIdx(ScaledMask1[1], PostShuffle[3], Ops1)) {
45304         LHS = DAG.getBitcast(SrcVT, LHS);
45305         RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
45306         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
45307         SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
45308         Res = DAG.getBitcast(ShufVT, Res);
45309         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, PostShuffle);
45310         return DAG.getBitcast(VT, Res);
45311       }
45312     }
45313   }
45314 
45315   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(X,Y)) -> SHUFFLE(HOP(X,Y)).
45316   if (VT.is256BitVector() && Subtarget.hasInt256()) {
45317     SmallVector<int> Mask0, Mask1;
45318     SmallVector<SDValue> Ops0, Ops1;
45319     SmallVector<int, 2> ScaledMask0, ScaledMask1;
45320     if (getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
45321         getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
45322         !Ops0.empty() && !Ops1.empty() &&
45323         all_of(Ops0,
45324                [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
45325         all_of(Ops1,
45326                [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
45327         scaleShuffleElements(Mask0, 2, ScaledMask0) &&
45328         scaleShuffleElements(Mask1, 2, ScaledMask1)) {
45329       SDValue Op00 = peekThroughBitcasts(Ops0.front());
45330       SDValue Op10 = peekThroughBitcasts(Ops1.front());
45331       SDValue Op01 = peekThroughBitcasts(Ops0.back());
45332       SDValue Op11 = peekThroughBitcasts(Ops1.back());
45333       if ((Op00 == Op11) && (Op01 == Op10)) {
45334         std::swap(Op10, Op11);
45335         ShuffleVectorSDNode::commuteMask(ScaledMask1);
45336       }
45337       if ((Op00 == Op10) && (Op01 == Op11)) {
45338         const int Map[4] = {0, 2, 1, 3};
45339         SmallVector<int, 4> ShuffleMask(
45340             {Map[ScaledMask0[0]], Map[ScaledMask1[0]], Map[ScaledMask0[1]],
45341              Map[ScaledMask1[1]]});
45342         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
45343         SDValue Res = DAG.getNode(Opcode, DL, VT, DAG.getBitcast(SrcVT, Op00),
45344                                   DAG.getBitcast(SrcVT, Op01));
45345         Res = DAG.getBitcast(ShufVT, Res);
45346         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ShuffleMask);
45347         return DAG.getBitcast(VT, Res);
45348       }
45349     }
45350   }
45351 
45352   return SDValue();
45353 }
45354 
45355 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
45356                                  TargetLowering::DAGCombinerInfo &DCI,
45357                                  const X86Subtarget &Subtarget) {
45358   unsigned Opcode = N->getOpcode();
45359   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
45360          "Unexpected pack opcode");
45361 
45362   EVT VT = N->getValueType(0);
45363   SDValue N0 = N->getOperand(0);
45364   SDValue N1 = N->getOperand(1);
45365   unsigned NumDstElts = VT.getVectorNumElements();
45366   unsigned DstBitsPerElt = VT.getScalarSizeInBits();
45367   unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
45368   assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
45369          N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
45370          "Unexpected PACKSS/PACKUS input type");
45371 
45372   bool IsSigned = (X86ISD::PACKSS == Opcode);
45373 
45374   // Constant Folding.
45375   APInt UndefElts0, UndefElts1;
45376   SmallVector<APInt, 32> EltBits0, EltBits1;
45377   if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
45378       (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
45379       getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
45380       getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
45381     unsigned NumLanes = VT.getSizeInBits() / 128;
45382     unsigned NumSrcElts = NumDstElts / 2;
45383     unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
45384     unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
45385 
45386     APInt Undefs(NumDstElts, 0);
45387     SmallVector<APInt, 32> Bits(NumDstElts, APInt::getZero(DstBitsPerElt));
45388     for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
45389       for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
45390         unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
45391         auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
45392         auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
45393 
45394         if (UndefElts[SrcIdx]) {
45395           Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
45396           continue;
45397         }
45398 
45399         APInt &Val = EltBits[SrcIdx];
45400         if (IsSigned) {
45401           // PACKSS: Truncate signed value with signed saturation.
45402           // Source values less than dst minint are saturated to minint.
45403           // Source values greater than dst maxint are saturated to maxint.
45404           if (Val.isSignedIntN(DstBitsPerElt))
45405             Val = Val.trunc(DstBitsPerElt);
45406           else if (Val.isNegative())
45407             Val = APInt::getSignedMinValue(DstBitsPerElt);
45408           else
45409             Val = APInt::getSignedMaxValue(DstBitsPerElt);
45410         } else {
45411           // PACKUS: Truncate signed value with unsigned saturation.
45412           // Source values less than zero are saturated to zero.
45413           // Source values greater than dst maxuint are saturated to maxuint.
45414           if (Val.isIntN(DstBitsPerElt))
45415             Val = Val.trunc(DstBitsPerElt);
45416           else if (Val.isNegative())
45417             Val = APInt::getZero(DstBitsPerElt);
45418           else
45419             Val = APInt::getAllOnes(DstBitsPerElt);
45420         }
45421         Bits[Lane * NumDstEltsPerLane + Elt] = Val;
45422       }
45423     }
45424 
45425     return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
45426   }
45427 
45428   // Try to fold PACK(SHUFFLE(),SHUFFLE()) -> SHUFFLE(PACK()).
45429   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
45430     return V;
45431 
45432   // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
45433   // truncate to create a larger truncate.
45434   if (Subtarget.hasAVX512() &&
45435       N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
45436       N0.getOperand(0).getValueType() == MVT::v8i32) {
45437     if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
45438         (!IsSigned &&
45439          DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
45440       if (Subtarget.hasVLX())
45441         return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
45442 
45443       // Widen input to v16i32 so we can truncate that.
45444       SDLoc dl(N);
45445       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
45446                                    N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
45447       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
45448     }
45449   }
45450 
45451   // Try to fold PACK(EXTEND(X),EXTEND(Y)) -> CONCAT(X,Y) subvectors.
45452   if (VT.is128BitVector()) {
45453     unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
45454     SDValue Src0, Src1;
45455     if (N0.getOpcode() == ExtOpc &&
45456         N0.getOperand(0).getValueType().is64BitVector() &&
45457         N0.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
45458       Src0 = N0.getOperand(0);
45459     }
45460     if (N1.getOpcode() == ExtOpc &&
45461         N1.getOperand(0).getValueType().is64BitVector() &&
45462         N1.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
45463       Src1 = N1.getOperand(0);
45464     }
45465     if ((Src0 || N0.isUndef()) && (Src1 || N1.isUndef())) {
45466       assert((Src0 || Src1) && "Found PACK(UNDEF,UNDEF)");
45467       Src0 = Src0 ? Src0 : DAG.getUNDEF(Src1.getValueType());
45468       Src1 = Src1 ? Src1 : DAG.getUNDEF(Src0.getValueType());
45469       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Src0, Src1);
45470     }
45471 
45472     // Try again with pack(*_extend_vector_inreg, undef).
45473     unsigned VecInRegOpc = IsSigned ? ISD::SIGN_EXTEND_VECTOR_INREG
45474                                     : ISD::ZERO_EXTEND_VECTOR_INREG;
45475     if (N0.getOpcode() == VecInRegOpc && N1.isUndef() &&
45476         N0.getOperand(0).getScalarValueSizeInBits() < DstBitsPerElt)
45477       return getEXTEND_VECTOR_INREG(ExtOpc, SDLoc(N), VT, N0.getOperand(0),
45478                                     DAG);
45479   }
45480 
45481   // Attempt to combine as shuffle.
45482   SDValue Op(N, 0);
45483   if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
45484     return Res;
45485 
45486   return SDValue();
45487 }
45488 
45489 static SDValue combineVectorHADDSUB(SDNode *N, SelectionDAG &DAG,
45490                                     TargetLowering::DAGCombinerInfo &DCI,
45491                                     const X86Subtarget &Subtarget) {
45492   assert((X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() ||
45493           X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
45494          "Unexpected horizontal add/sub opcode");
45495 
45496   if (!shouldUseHorizontalOp(true, DAG, Subtarget)) {
45497     MVT VT = N->getSimpleValueType(0);
45498     SDValue LHS = N->getOperand(0);
45499     SDValue RHS = N->getOperand(1);
45500 
45501     // HOP(HOP'(X,X),HOP'(Y,Y)) -> HOP(PERMUTE(HOP'(X,Y)),PERMUTE(HOP'(X,Y)).
45502     if (LHS != RHS && LHS.getOpcode() == N->getOpcode() &&
45503         LHS.getOpcode() == RHS.getOpcode() &&
45504         LHS.getValueType() == RHS.getValueType() &&
45505         N->isOnlyUserOf(LHS.getNode()) && N->isOnlyUserOf(RHS.getNode())) {
45506       SDValue LHS0 = LHS.getOperand(0);
45507       SDValue LHS1 = LHS.getOperand(1);
45508       SDValue RHS0 = RHS.getOperand(0);
45509       SDValue RHS1 = RHS.getOperand(1);
45510       if ((LHS0 == LHS1 || LHS0.isUndef() || LHS1.isUndef()) &&
45511           (RHS0 == RHS1 || RHS0.isUndef() || RHS1.isUndef())) {
45512         SDLoc DL(N);
45513         SDValue Res = DAG.getNode(LHS.getOpcode(), DL, LHS.getValueType(),
45514                                   LHS0.isUndef() ? LHS1 : LHS0,
45515                                   RHS0.isUndef() ? RHS1 : RHS0);
45516         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
45517         Res = DAG.getBitcast(ShufVT, Res);
45518         SDValue NewLHS =
45519             DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
45520                         getV4X86ShuffleImm8ForMask({0, 1, 0, 1}, DL, DAG));
45521         SDValue NewRHS =
45522             DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
45523                         getV4X86ShuffleImm8ForMask({2, 3, 2, 3}, DL, DAG));
45524         return DAG.getNode(N->getOpcode(), DL, VT, DAG.getBitcast(VT, NewLHS),
45525                            DAG.getBitcast(VT, NewRHS));
45526       }
45527     }
45528   }
45529 
45530   // Try to fold HOP(SHUFFLE(),SHUFFLE()) -> SHUFFLE(HOP()).
45531   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
45532     return V;
45533 
45534   return SDValue();
45535 }
45536 
45537 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
45538                                      TargetLowering::DAGCombinerInfo &DCI,
45539                                      const X86Subtarget &Subtarget) {
45540   assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
45541           X86ISD::VSRL == N->getOpcode()) &&
45542          "Unexpected shift opcode");
45543   EVT VT = N->getValueType(0);
45544   SDValue N0 = N->getOperand(0);
45545   SDValue N1 = N->getOperand(1);
45546 
45547   // Shift zero -> zero.
45548   if (ISD::isBuildVectorAllZeros(N0.getNode()))
45549     return DAG.getConstant(0, SDLoc(N), VT);
45550 
45551   // Detect constant shift amounts.
45552   APInt UndefElts;
45553   SmallVector<APInt, 32> EltBits;
45554   if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
45555     unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
45556     return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
45557                                       EltBits[0].getZExtValue(), DAG);
45558   }
45559 
45560   APInt KnownUndef, KnownZero;
45561   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45562   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
45563   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
45564                                      KnownZero, DCI))
45565     return SDValue(N, 0);
45566 
45567   return SDValue();
45568 }
45569 
45570 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
45571                                      TargetLowering::DAGCombinerInfo &DCI,
45572                                      const X86Subtarget &Subtarget) {
45573   unsigned Opcode = N->getOpcode();
45574   assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
45575           X86ISD::VSRLI == Opcode) &&
45576          "Unexpected shift opcode");
45577   bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
45578   EVT VT = N->getValueType(0);
45579   SDValue N0 = N->getOperand(0);
45580   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
45581   assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
45582          "Unexpected value type");
45583   assert(N->getOperand(1).getValueType() == MVT::i8 &&
45584          "Unexpected shift amount type");
45585 
45586   // (shift undef, X) -> 0
45587   if (N0.isUndef())
45588     return DAG.getConstant(0, SDLoc(N), VT);
45589 
45590   // Out of range logical bit shifts are guaranteed to be zero.
45591   // Out of range arithmetic bit shifts splat the sign bit.
45592   unsigned ShiftVal = N->getConstantOperandVal(1);
45593   if (ShiftVal >= NumBitsPerElt) {
45594     if (LogicalShift)
45595       return DAG.getConstant(0, SDLoc(N), VT);
45596     ShiftVal = NumBitsPerElt - 1;
45597   }
45598 
45599   // (shift X, 0) -> X
45600   if (!ShiftVal)
45601     return N0;
45602 
45603   // (shift 0, C) -> 0
45604   if (ISD::isBuildVectorAllZeros(N0.getNode()))
45605     // N0 is all zeros or undef. We guarantee that the bits shifted into the
45606     // result are all zeros, not undef.
45607     return DAG.getConstant(0, SDLoc(N), VT);
45608 
45609   // (VSRAI -1, C) -> -1
45610   if (!LogicalShift && ISD::isBuildVectorAllOnes(N0.getNode()))
45611     // N0 is all ones or undef. We guarantee that the bits shifted into the
45612     // result are all ones, not undef.
45613     return DAG.getConstant(-1, SDLoc(N), VT);
45614 
45615   // (shift (shift X, C2), C1) -> (shift X, (C1 + C2))
45616   if (Opcode == N0.getOpcode()) {
45617     unsigned ShiftVal2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
45618     unsigned NewShiftVal = ShiftVal + ShiftVal2;
45619     if (NewShiftVal >= NumBitsPerElt) {
45620       // Out of range logical bit shifts are guaranteed to be zero.
45621       // Out of range arithmetic bit shifts splat the sign bit.
45622       if (LogicalShift)
45623         return DAG.getConstant(0, SDLoc(N), VT);
45624       NewShiftVal = NumBitsPerElt - 1;
45625     }
45626     return DAG.getNode(Opcode, SDLoc(N), VT, N0.getOperand(0),
45627                        DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
45628   }
45629 
45630   // We can decode 'whole byte' logical bit shifts as shuffles.
45631   if (LogicalShift && (ShiftVal % 8) == 0) {
45632     SDValue Op(N, 0);
45633     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
45634       return Res;
45635   }
45636 
45637   // Constant Folding.
45638   APInt UndefElts;
45639   SmallVector<APInt, 32> EltBits;
45640   if (N->isOnlyUserOf(N0.getNode()) &&
45641       getTargetConstantBitsFromNode(N0, NumBitsPerElt, UndefElts, EltBits)) {
45642     assert(EltBits.size() == VT.getVectorNumElements() &&
45643            "Unexpected shift value type");
45644     // Undef elements need to fold to 0. It's possible SimplifyDemandedBits
45645     // created an undef input due to no input bits being demanded, but user
45646     // still expects 0 in other bits.
45647     for (unsigned i = 0, e = EltBits.size(); i != e; ++i) {
45648       APInt &Elt = EltBits[i];
45649       if (UndefElts[i])
45650         Elt = 0;
45651       else if (X86ISD::VSHLI == Opcode)
45652         Elt <<= ShiftVal;
45653       else if (X86ISD::VSRAI == Opcode)
45654         Elt.ashrInPlace(ShiftVal);
45655       else
45656         Elt.lshrInPlace(ShiftVal);
45657     }
45658     // Reset undef elements since they were zeroed above.
45659     UndefElts = 0;
45660     return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
45661   }
45662 
45663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45664   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBitsPerElt),
45665                                DCI))
45666     return SDValue(N, 0);
45667 
45668   return SDValue();
45669 }
45670 
45671 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
45672                                    TargetLowering::DAGCombinerInfo &DCI,
45673                                    const X86Subtarget &Subtarget) {
45674   EVT VT = N->getValueType(0);
45675   assert(((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) ||
45676           (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) ||
45677           N->getOpcode() == ISD::INSERT_VECTOR_ELT) &&
45678          "Unexpected vector insertion");
45679 
45680   if (N->getOpcode() == X86ISD::PINSRB || N->getOpcode() == X86ISD::PINSRW) {
45681     unsigned NumBitsPerElt = VT.getScalarSizeInBits();
45682     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45683     if (TLI.SimplifyDemandedBits(SDValue(N, 0),
45684                                  APInt::getAllOnes(NumBitsPerElt), DCI))
45685       return SDValue(N, 0);
45686   }
45687 
45688   // Attempt to combine insertion patterns to a shuffle.
45689   if (VT.isSimple() && DCI.isAfterLegalizeDAG()) {
45690     SDValue Op(N, 0);
45691     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
45692       return Res;
45693   }
45694 
45695   return SDValue();
45696 }
45697 
45698 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
45699 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
45700 /// OR -> CMPNEQSS.
45701 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
45702                                    TargetLowering::DAGCombinerInfo &DCI,
45703                                    const X86Subtarget &Subtarget) {
45704   unsigned opcode;
45705 
45706   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
45707   // we're requiring SSE2 for both.
45708   if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
45709     SDValue N0 = N->getOperand(0);
45710     SDValue N1 = N->getOperand(1);
45711     SDValue CMP0 = N0.getOperand(1);
45712     SDValue CMP1 = N1.getOperand(1);
45713     SDLoc DL(N);
45714 
45715     // The SETCCs should both refer to the same CMP.
45716     if (CMP0.getOpcode() != X86ISD::FCMP || CMP0 != CMP1)
45717       return SDValue();
45718 
45719     SDValue CMP00 = CMP0->getOperand(0);
45720     SDValue CMP01 = CMP0->getOperand(1);
45721     EVT     VT    = CMP00.getValueType();
45722 
45723     if (VT == MVT::f32 || VT == MVT::f64 ||
45724         (VT == MVT::f16 && Subtarget.hasFP16())) {
45725       bool ExpectingFlags = false;
45726       // Check for any users that want flags:
45727       for (const SDNode *U : N->uses()) {
45728         if (ExpectingFlags)
45729           break;
45730 
45731         switch (U->getOpcode()) {
45732         default:
45733         case ISD::BR_CC:
45734         case ISD::BRCOND:
45735         case ISD::SELECT:
45736           ExpectingFlags = true;
45737           break;
45738         case ISD::CopyToReg:
45739         case ISD::SIGN_EXTEND:
45740         case ISD::ZERO_EXTEND:
45741         case ISD::ANY_EXTEND:
45742           break;
45743         }
45744       }
45745 
45746       if (!ExpectingFlags) {
45747         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
45748         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
45749 
45750         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
45751           X86::CondCode tmp = cc0;
45752           cc0 = cc1;
45753           cc1 = tmp;
45754         }
45755 
45756         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
45757             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
45758           // FIXME: need symbolic constants for these magic numbers.
45759           // See X86ATTInstPrinter.cpp:printSSECC().
45760           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
45761           if (Subtarget.hasAVX512()) {
45762             SDValue FSetCC =
45763                 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
45764                             DAG.getTargetConstant(x86cc, DL, MVT::i8));
45765             // Need to fill with zeros to ensure the bitcast will produce zeroes
45766             // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
45767             SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
45768                                       DAG.getConstant(0, DL, MVT::v16i1),
45769                                       FSetCC, DAG.getIntPtrConstant(0, DL));
45770             return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
45771                                       N->getSimpleValueType(0));
45772           }
45773           SDValue OnesOrZeroesF =
45774               DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
45775                           CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
45776 
45777           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
45778           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
45779 
45780           if (is64BitFP && !Subtarget.is64Bit()) {
45781             // On a 32-bit target, we cannot bitcast the 64-bit float to a
45782             // 64-bit integer, since that's not a legal type. Since
45783             // OnesOrZeroesF is all ones or all zeroes, we don't need all the
45784             // bits, but can do this little dance to extract the lowest 32 bits
45785             // and work with those going forward.
45786             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
45787                                            OnesOrZeroesF);
45788             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
45789             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
45790                                         Vector32, DAG.getIntPtrConstant(0, DL));
45791             IntVT = MVT::i32;
45792           }
45793 
45794           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
45795           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
45796                                       DAG.getConstant(1, DL, IntVT));
45797           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
45798                                               ANDed);
45799           return OneBitOfTruth;
45800         }
45801       }
45802     }
45803   }
45804   return SDValue();
45805 }
45806 
45807 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
45808 static SDValue combineAndNotIntoANDNP(SDNode *N, SelectionDAG &DAG) {
45809   assert(N->getOpcode() == ISD::AND);
45810 
45811   MVT VT = N->getSimpleValueType(0);
45812   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
45813     return SDValue();
45814 
45815   SDValue X, Y;
45816   SDValue N0 = N->getOperand(0);
45817   SDValue N1 = N->getOperand(1);
45818 
45819   auto GetNot = [&VT, &DAG](SDValue V) {
45820     // Basic X = NOT(Y) detection.
45821     if (SDValue Not = IsNOT(V, DAG))
45822       return Not;
45823     // Fold BROADCAST(NOT(Y)) -> BROADCAST(Y).
45824     if (V.getOpcode() == X86ISD::VBROADCAST) {
45825       SDValue Src = V.getOperand(0);
45826       EVT SrcVT = Src.getValueType();
45827       if (!SrcVT.isVector())
45828         return SDValue();
45829       if (SDValue Not = IsNOT(Src, DAG))
45830         return DAG.getNode(X86ISD::VBROADCAST, SDLoc(V), VT,
45831                            DAG.getBitcast(SrcVT, Not));
45832     }
45833     return SDValue();
45834   };
45835 
45836   if (SDValue Not = GetNot(N0)) {
45837     X = Not;
45838     Y = N1;
45839   } else if (SDValue Not = GetNot(N1)) {
45840     X = Not;
45841     Y = N0;
45842   } else
45843     return SDValue();
45844 
45845   X = DAG.getBitcast(VT, X);
45846   Y = DAG.getBitcast(VT, Y);
45847   return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
45848 }
45849 
45850 // Try to widen AND, OR and XOR nodes to VT in order to remove casts around
45851 // logical operations, like in the example below.
45852 //   or (and (truncate x, truncate y)),
45853 //      (xor (truncate z, build_vector (constants)))
45854 // Given a target type \p VT, we generate
45855 //   or (and x, y), (xor z, zext(build_vector (constants)))
45856 // given x, y and z are of type \p VT. We can do so, if operands are either
45857 // truncates from VT types, the second operand is a vector of constants or can
45858 // be recursively promoted.
45859 static SDValue PromoteMaskArithmetic(SDNode *N, EVT VT, SelectionDAG &DAG,
45860                                      unsigned Depth) {
45861   // Limit recursion to avoid excessive compile times.
45862   if (Depth >= SelectionDAG::MaxRecursionDepth)
45863     return SDValue();
45864 
45865   if (N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND &&
45866       N->getOpcode() != ISD::OR)
45867     return SDValue();
45868 
45869   SDValue N0 = N->getOperand(0);
45870   SDValue N1 = N->getOperand(1);
45871   SDLoc DL(N);
45872 
45873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45874   if (!TLI.isOperationLegalOrPromote(N->getOpcode(), VT))
45875     return SDValue();
45876 
45877   if (SDValue NN0 = PromoteMaskArithmetic(N0.getNode(), VT, DAG, Depth + 1))
45878     N0 = NN0;
45879   else {
45880     // The Left side has to be a trunc.
45881     if (N0.getOpcode() != ISD::TRUNCATE)
45882       return SDValue();
45883 
45884     // The type of the truncated inputs.
45885     if (N0.getOperand(0).getValueType() != VT)
45886       return SDValue();
45887 
45888     N0 = N0.getOperand(0);
45889   }
45890 
45891   if (SDValue NN1 = PromoteMaskArithmetic(N1.getNode(), VT, DAG, Depth + 1))
45892     N1 = NN1;
45893   else {
45894     // The right side has to be a 'trunc' or a constant vector.
45895     bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
45896                     N1.getOperand(0).getValueType() == VT;
45897     if (!RHSTrunc && !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
45898       return SDValue();
45899 
45900     if (RHSTrunc)
45901       N1 = N1.getOperand(0);
45902     else
45903       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
45904   }
45905 
45906   return DAG.getNode(N->getOpcode(), DL, VT, N0, N1);
45907 }
45908 
45909 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
45910 // register. In most cases we actually compare or select YMM-sized registers
45911 // and mixing the two types creates horrible code. This method optimizes
45912 // some of the transition sequences.
45913 // Even with AVX-512 this is still useful for removing casts around logical
45914 // operations on vXi1 mask types.
45915 static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
45916                                      const X86Subtarget &Subtarget) {
45917   EVT VT = N->getValueType(0);
45918   assert(VT.isVector() && "Expected vector type");
45919 
45920   SDLoc DL(N);
45921   assert((N->getOpcode() == ISD::ANY_EXTEND ||
45922           N->getOpcode() == ISD::ZERO_EXTEND ||
45923           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
45924 
45925   SDValue Narrow = N->getOperand(0);
45926   EVT NarrowVT = Narrow.getValueType();
45927 
45928   // Generate the wide operation.
45929   SDValue Op = PromoteMaskArithmetic(Narrow.getNode(), VT, DAG, 0);
45930   if (!Op)
45931     return SDValue();
45932   switch (N->getOpcode()) {
45933   default: llvm_unreachable("Unexpected opcode");
45934   case ISD::ANY_EXTEND:
45935     return Op;
45936   case ISD::ZERO_EXTEND:
45937     return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
45938   case ISD::SIGN_EXTEND:
45939     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
45940                        Op, DAG.getValueType(NarrowVT));
45941   }
45942 }
45943 
45944 static unsigned convertIntLogicToFPLogicOpcode(unsigned Opcode) {
45945   unsigned FPOpcode;
45946   switch (Opcode) {
45947   default: llvm_unreachable("Unexpected input node for FP logic conversion");
45948   case ISD::AND: FPOpcode = X86ISD::FAND; break;
45949   case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
45950   case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
45951   }
45952   return FPOpcode;
45953 }
45954 
45955 /// If both input operands of a logic op are being cast from floating-point
45956 /// types or FP compares, try to convert this into a floating-point logic node
45957 /// to avoid unnecessary moves from SSE to integer registers.
45958 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
45959                                         TargetLowering::DAGCombinerInfo &DCI,
45960                                         const X86Subtarget &Subtarget) {
45961   EVT VT = N->getValueType(0);
45962   SDValue N0 = N->getOperand(0);
45963   SDValue N1 = N->getOperand(1);
45964   SDLoc DL(N);
45965 
45966   if (!((N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) ||
45967         (N0.getOpcode() == ISD::SETCC && N1.getOpcode() == ISD::SETCC)))
45968     return SDValue();
45969 
45970   SDValue N00 = N0.getOperand(0);
45971   SDValue N10 = N1.getOperand(0);
45972   EVT N00Type = N00.getValueType();
45973   EVT N10Type = N10.getValueType();
45974 
45975   // Ensure that both types are the same and are legal scalar fp types.
45976   if (N00Type != N10Type || !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
45977                               (Subtarget.hasSSE2() && N00Type == MVT::f64) ||
45978                               (Subtarget.hasFP16() && N00Type == MVT::f16)))
45979     return SDValue();
45980 
45981   if (N0.getOpcode() == ISD::BITCAST && !DCI.isBeforeLegalizeOps()) {
45982     unsigned FPOpcode = convertIntLogicToFPLogicOpcode(N->getOpcode());
45983     SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
45984     return DAG.getBitcast(VT, FPLogic);
45985   }
45986 
45987   // The vector ISA for FP predicates is incomplete before AVX, so converting
45988   // COMIS* to CMPS* may not be a win before AVX.
45989   // TODO: Check types/predicates to see if they are available with SSE/SSE2.
45990   if (!Subtarget.hasAVX() || VT != MVT::i1 || N0.getOpcode() != ISD::SETCC ||
45991       !N0.hasOneUse() || !N1.hasOneUse())
45992     return SDValue();
45993 
45994   // Convert scalar FP compares and logic to vector compares (COMIS* to CMPS*)
45995   // and vector logic:
45996   // logic (setcc N00, N01), (setcc N10, N11) -->
45997   // extelt (logic (setcc (s2v N00), (s2v N01)), setcc (s2v N10), (s2v N11))), 0
45998   unsigned NumElts = 128 / N00Type.getSizeInBits();
45999   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), N00Type, NumElts);
46000   EVT BoolVecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
46001   SDValue ZeroIndex = DAG.getVectorIdxConstant(0, DL);
46002   SDValue N01 = N0.getOperand(1);
46003   SDValue N11 = N1.getOperand(1);
46004   SDValue Vec00 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N00);
46005   SDValue Vec01 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N01);
46006   SDValue Vec10 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N10);
46007   SDValue Vec11 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N11);
46008   SDValue Setcc0 = DAG.getSetCC(DL, BoolVecVT, Vec00, Vec01,
46009                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
46010   SDValue Setcc1 = DAG.getSetCC(DL, BoolVecVT, Vec10, Vec11,
46011                                 cast<CondCodeSDNode>(N1.getOperand(2))->get());
46012   SDValue Logic = DAG.getNode(N->getOpcode(), DL, BoolVecVT, Setcc0, Setcc1);
46013   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Logic, ZeroIndex);
46014 }
46015 
46016 // Attempt to fold BITOP(MOVMSK(X),MOVMSK(Y)) -> MOVMSK(BITOP(X,Y))
46017 // to reduce XMM->GPR traffic.
46018 static SDValue combineBitOpWithMOVMSK(SDNode *N, SelectionDAG &DAG) {
46019   unsigned Opc = N->getOpcode();
46020   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
46021          "Unexpected bit opcode");
46022 
46023   SDValue N0 = N->getOperand(0);
46024   SDValue N1 = N->getOperand(1);
46025 
46026   // Both operands must be single use MOVMSK.
46027   if (N0.getOpcode() != X86ISD::MOVMSK || !N0.hasOneUse() ||
46028       N1.getOpcode() != X86ISD::MOVMSK || !N1.hasOneUse())
46029     return SDValue();
46030 
46031   SDValue Vec0 = N0.getOperand(0);
46032   SDValue Vec1 = N1.getOperand(0);
46033   EVT VecVT0 = Vec0.getValueType();
46034   EVT VecVT1 = Vec1.getValueType();
46035 
46036   // Both MOVMSK operands must be from vectors of the same size and same element
46037   // size, but its OK for a fp/int diff.
46038   if (VecVT0.getSizeInBits() != VecVT1.getSizeInBits() ||
46039       VecVT0.getScalarSizeInBits() != VecVT1.getScalarSizeInBits())
46040     return SDValue();
46041 
46042   SDLoc DL(N);
46043   unsigned VecOpc =
46044       VecVT0.isFloatingPoint() ? convertIntLogicToFPLogicOpcode(Opc) : Opc;
46045   SDValue Result =
46046       DAG.getNode(VecOpc, DL, VecVT0, Vec0, DAG.getBitcast(VecVT0, Vec1));
46047   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
46048 }
46049 
46050 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
46051 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
46052 /// with a shift-right to eliminate loading the vector constant mask value.
46053 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
46054                                      const X86Subtarget &Subtarget) {
46055   SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
46056   SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
46057   EVT VT = Op0.getValueType();
46058   if (VT != Op1.getValueType() || !VT.isSimple() || !VT.isInteger())
46059     return SDValue();
46060 
46061   // Try to convert an "is positive" signbit masking operation into arithmetic
46062   // shift and "andn". This saves a materialization of a -1 vector constant.
46063   // The "is negative" variant should be handled more generally because it only
46064   // requires "and" rather than "andn":
46065   // and (pcmpgt X, -1), Y --> pandn (vsrai X, BitWidth - 1), Y
46066   //
46067   // This is limited to the original type to avoid producing even more bitcasts.
46068   // If the bitcasts can't be eliminated, then it is unlikely that this fold
46069   // will be profitable.
46070   if (N->getValueType(0) == VT &&
46071       supportedVectorShiftWithImm(VT.getSimpleVT(), Subtarget, ISD::SRA)) {
46072     SDValue X, Y;
46073     if (Op1.hasOneUse() && Op1.getOpcode() == X86ISD::PCMPGT &&
46074         isAllOnesOrAllOnesSplat(Op1.getOperand(1))) {
46075       X = Op1.getOperand(0);
46076       Y = Op0;
46077     } else if (Op0.hasOneUse() && Op0.getOpcode() == X86ISD::PCMPGT &&
46078                isAllOnesOrAllOnesSplat(Op0.getOperand(1))) {
46079       X = Op0.getOperand(0);
46080       Y = Op1;
46081     }
46082     if (X && Y) {
46083       SDLoc DL(N);
46084       SDValue Sra =
46085           getTargetVShiftByConstNode(X86ISD::VSRAI, DL, VT.getSimpleVT(), X,
46086                                      VT.getScalarSizeInBits() - 1, DAG);
46087       return DAG.getNode(X86ISD::ANDNP, DL, VT, Sra, Y);
46088     }
46089   }
46090 
46091   APInt SplatVal;
46092   if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) ||
46093       !SplatVal.isMask())
46094     return SDValue();
46095 
46096   // Don't prevent creation of ANDN.
46097   if (isBitwiseNot(Op0))
46098     return SDValue();
46099 
46100   if (!supportedVectorShiftWithImm(VT.getSimpleVT(), Subtarget, ISD::SRL))
46101     return SDValue();
46102 
46103   unsigned EltBitWidth = VT.getScalarSizeInBits();
46104   if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
46105     return SDValue();
46106 
46107   SDLoc DL(N);
46108   unsigned ShiftVal = SplatVal.countTrailingOnes();
46109   SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
46110   SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT, Op0, ShAmt);
46111   return DAG.getBitcast(N->getValueType(0), Shift);
46112 }
46113 
46114 // Get the index node from the lowered DAG of a GEP IR instruction with one
46115 // indexing dimension.
46116 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
46117   if (Ld->isIndexed())
46118     return SDValue();
46119 
46120   SDValue Base = Ld->getBasePtr();
46121 
46122   if (Base.getOpcode() != ISD::ADD)
46123     return SDValue();
46124 
46125   SDValue ShiftedIndex = Base.getOperand(0);
46126 
46127   if (ShiftedIndex.getOpcode() != ISD::SHL)
46128     return SDValue();
46129 
46130   return ShiftedIndex.getOperand(0);
46131 
46132 }
46133 
46134 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
46135   if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
46136     switch (VT.getSizeInBits()) {
46137     default: return false;
46138     case 64: return Subtarget.is64Bit() ? true : false;
46139     case 32: return true;
46140     }
46141   }
46142   return false;
46143 }
46144 
46145 // This function recognizes cases where X86 bzhi instruction can replace and
46146 // 'and-load' sequence.
46147 // In case of loading integer value from an array of constants which is defined
46148 // as follows:
46149 //
46150 //   int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
46151 //
46152 // then applying a bitwise and on the result with another input.
46153 // It's equivalent to performing bzhi (zero high bits) on the input, with the
46154 // same index of the load.
46155 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
46156                                     const X86Subtarget &Subtarget) {
46157   MVT VT = Node->getSimpleValueType(0);
46158   SDLoc dl(Node);
46159 
46160   // Check if subtarget has BZHI instruction for the node's type
46161   if (!hasBZHI(Subtarget, VT))
46162     return SDValue();
46163 
46164   // Try matching the pattern for both operands.
46165   for (unsigned i = 0; i < 2; i++) {
46166     SDValue N = Node->getOperand(i);
46167     LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
46168 
46169      // continue if the operand is not a load instruction
46170     if (!Ld)
46171       return SDValue();
46172 
46173     const Value *MemOp = Ld->getMemOperand()->getValue();
46174 
46175     if (!MemOp)
46176       return SDValue();
46177 
46178     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
46179       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
46180         if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
46181 
46182           Constant *Init = GV->getInitializer();
46183           Type *Ty = Init->getType();
46184           if (!isa<ConstantDataArray>(Init) ||
46185               !Ty->getArrayElementType()->isIntegerTy() ||
46186               Ty->getArrayElementType()->getScalarSizeInBits() !=
46187                   VT.getSizeInBits() ||
46188               Ty->getArrayNumElements() >
46189                   Ty->getArrayElementType()->getScalarSizeInBits())
46190             continue;
46191 
46192           // Check if the array's constant elements are suitable to our case.
46193           uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
46194           bool ConstantsMatch = true;
46195           for (uint64_t j = 0; j < ArrayElementCount; j++) {
46196             auto *Elem = cast<ConstantInt>(Init->getAggregateElement(j));
46197             if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
46198               ConstantsMatch = false;
46199               break;
46200             }
46201           }
46202           if (!ConstantsMatch)
46203             continue;
46204 
46205           // Do the transformation (For 32-bit type):
46206           // -> (and (load arr[idx]), inp)
46207           // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
46208           //    that will be replaced with one bzhi instruction.
46209           SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
46210           SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
46211 
46212           // Get the Node which indexes into the array.
46213           SDValue Index = getIndexFromUnindexedLoad(Ld);
46214           if (!Index)
46215             return SDValue();
46216           Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
46217 
46218           SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
46219           Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
46220 
46221           SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
46222           SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
46223 
46224           return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
46225         }
46226       }
46227     }
46228   }
46229   return SDValue();
46230 }
46231 
46232 // Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
46233 // Where C is a mask containing the same number of bits as the setcc and
46234 // where the setcc will freely 0 upper bits of k-register. We can replace the
46235 // undef in the concat with 0s and remove the AND. This mainly helps with
46236 // v2i1/v4i1 setcc being casted to scalar.
46237 static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
46238                                              const X86Subtarget &Subtarget) {
46239   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
46240 
46241   EVT VT = N->getValueType(0);
46242 
46243   // Make sure this is an AND with constant. We will check the value of the
46244   // constant later.
46245   if (!isa<ConstantSDNode>(N->getOperand(1)))
46246     return SDValue();
46247 
46248   // This is implied by the ConstantSDNode.
46249   assert(!VT.isVector() && "Expected scalar VT!");
46250 
46251   if (N->getOperand(0).getOpcode() != ISD::BITCAST ||
46252       !N->getOperand(0).hasOneUse() ||
46253       !N->getOperand(0).getOperand(0).hasOneUse())
46254     return SDValue();
46255 
46256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46257   SDValue Src = N->getOperand(0).getOperand(0);
46258   EVT SrcVT = Src.getValueType();
46259   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
46260       !TLI.isTypeLegal(SrcVT))
46261     return SDValue();
46262 
46263   if (Src.getOpcode() != ISD::CONCAT_VECTORS)
46264     return SDValue();
46265 
46266   // We only care about the first subvector of the concat, we expect the
46267   // other subvectors to be ignored due to the AND if we make the change.
46268   SDValue SubVec = Src.getOperand(0);
46269   EVT SubVecVT = SubVec.getValueType();
46270 
46271   // First subvector should be a setcc with a legal result type. The RHS of the
46272   // AND should be a mask with this many bits.
46273   if (SubVec.getOpcode() != ISD::SETCC || !TLI.isTypeLegal(SubVecVT) ||
46274       !N->getConstantOperandAPInt(1).isMask(SubVecVT.getVectorNumElements()))
46275     return SDValue();
46276 
46277   EVT SetccVT = SubVec.getOperand(0).getValueType();
46278   if (!TLI.isTypeLegal(SetccVT) ||
46279       !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
46280     return SDValue();
46281 
46282   if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
46283     return SDValue();
46284 
46285   // We passed all the checks. Rebuild the concat_vectors with zeroes
46286   // and cast it back to VT.
46287   SDLoc dl(N);
46288   SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
46289                               DAG.getConstant(0, dl, SubVecVT));
46290   Ops[0] = SubVec;
46291   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
46292                                Ops);
46293   return DAG.getBitcast(VT, Concat);
46294 }
46295 
46296 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
46297                           TargetLowering::DAGCombinerInfo &DCI,
46298                           const X86Subtarget &Subtarget) {
46299   SDValue N0 = N->getOperand(0);
46300   SDValue N1 = N->getOperand(1);
46301   EVT VT = N->getValueType(0);
46302   SDLoc dl(N);
46303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46304 
46305   // If this is SSE1 only convert to FAND to avoid scalarization.
46306   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
46307     return DAG.getBitcast(MVT::v4i32,
46308                           DAG.getNode(X86ISD::FAND, dl, MVT::v4f32,
46309                                       DAG.getBitcast(MVT::v4f32, N0),
46310                                       DAG.getBitcast(MVT::v4f32, N1)));
46311   }
46312 
46313   // Use a 32-bit and+zext if upper bits known zero.
46314   if (VT == MVT::i64 && Subtarget.is64Bit() && !isa<ConstantSDNode>(N1)) {
46315     APInt HiMask = APInt::getHighBitsSet(64, 32);
46316     if (DAG.MaskedValueIsZero(N1, HiMask) ||
46317         DAG.MaskedValueIsZero(N0, HiMask)) {
46318       SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N0);
46319       SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N1);
46320       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
46321                          DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
46322     }
46323   }
46324 
46325   // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
46326   // TODO: Support multiple SrcOps.
46327   if (VT == MVT::i1) {
46328     SmallVector<SDValue, 2> SrcOps;
46329     SmallVector<APInt, 2> SrcPartials;
46330     if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps, &SrcPartials) &&
46331         SrcOps.size() == 1) {
46332       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
46333       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
46334       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
46335       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
46336         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
46337       if (Mask) {
46338         assert(SrcPartials[0].getBitWidth() == NumElts &&
46339                "Unexpected partial reduction mask");
46340         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
46341         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
46342         return DAG.getSetCC(dl, MVT::i1, Mask, PartialBits, ISD::SETEQ);
46343       }
46344     }
46345   }
46346 
46347   if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
46348     return V;
46349 
46350   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
46351     return R;
46352 
46353   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
46354     return FPLogic;
46355 
46356   if (DCI.isBeforeLegalizeOps())
46357     return SDValue();
46358 
46359   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
46360     return R;
46361 
46362   if (SDValue R = combineAndNotIntoANDNP(N, DAG))
46363     return R;
46364 
46365   if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
46366     return ShiftRight;
46367 
46368   if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
46369     return R;
46370 
46371   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
46372     // Attempt to recursively combine a bitmask AND with shuffles.
46373     SDValue Op(N, 0);
46374     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
46375       return Res;
46376 
46377     // If either operand is a constant mask, then only the elements that aren't
46378     // zero are actually demanded by the other operand.
46379     auto SimplifyUndemandedElts = [&](SDValue Op, SDValue OtherOp) {
46380       APInt UndefElts;
46381       SmallVector<APInt> EltBits;
46382       int NumElts = VT.getVectorNumElements();
46383       int EltSizeInBits = VT.getScalarSizeInBits();
46384       if (!getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts, EltBits))
46385         return false;
46386 
46387       APInt DemandedElts = APInt::getZero(NumElts);
46388       for (int I = 0; I != NumElts; ++I)
46389         if (!EltBits[I].isZero())
46390           DemandedElts.setBit(I);
46391 
46392       APInt KnownUndef, KnownZero;
46393       return TLI.SimplifyDemandedVectorElts(OtherOp, DemandedElts, KnownUndef,
46394                                             KnownZero, DCI);
46395     };
46396     if (SimplifyUndemandedElts(N0, N1) || SimplifyUndemandedElts(N1, N0)) {
46397       if (N->getOpcode() != ISD::DELETED_NODE)
46398         DCI.AddToWorklist(N);
46399       return SDValue(N, 0);
46400     }
46401   }
46402 
46403   // Attempt to combine a scalar bitmask AND with an extracted shuffle.
46404   if ((VT.getScalarSizeInBits() % 8) == 0 &&
46405       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
46406       isa<ConstantSDNode>(N0.getOperand(1))) {
46407     SDValue BitMask = N1;
46408     SDValue SrcVec = N0.getOperand(0);
46409     EVT SrcVecVT = SrcVec.getValueType();
46410 
46411     // Check that the constant bitmask masks whole bytes.
46412     APInt UndefElts;
46413     SmallVector<APInt, 64> EltBits;
46414     if (VT == SrcVecVT.getScalarType() && N0->isOnlyUserOf(SrcVec.getNode()) &&
46415         getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
46416         llvm::all_of(EltBits, [](const APInt &M) {
46417           return M.isZero() || M.isAllOnes();
46418         })) {
46419       unsigned NumElts = SrcVecVT.getVectorNumElements();
46420       unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
46421       unsigned Idx = N0.getConstantOperandVal(1);
46422 
46423       // Create a root shuffle mask from the byte mask and the extracted index.
46424       SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
46425       for (unsigned i = 0; i != Scale; ++i) {
46426         if (UndefElts[i])
46427           continue;
46428         int VecIdx = Scale * Idx + i;
46429         ShuffleMask[VecIdx] = EltBits[i].isZero() ? SM_SentinelZero : VecIdx;
46430       }
46431 
46432       if (SDValue Shuffle = combineX86ShufflesRecursively(
46433               {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
46434               X86::MaxShuffleCombineDepth,
46435               /*HasVarMask*/ false, /*AllowVarCrossLaneMask*/ true,
46436               /*AllowVarPerLaneMask*/ true, DAG, Subtarget))
46437         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Shuffle,
46438                            N0.getOperand(1));
46439     }
46440   }
46441 
46442   return SDValue();
46443 }
46444 
46445 // Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
46446 static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
46447                                      const X86Subtarget &Subtarget) {
46448   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
46449 
46450   MVT VT = N->getSimpleValueType(0);
46451   unsigned EltSizeInBits = VT.getScalarSizeInBits();
46452   if (!VT.isVector() || (EltSizeInBits % 8) != 0)
46453     return SDValue();
46454 
46455   SDValue N0 = peekThroughBitcasts(N->getOperand(0));
46456   SDValue N1 = peekThroughBitcasts(N->getOperand(1));
46457   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
46458     return SDValue();
46459 
46460   // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
46461   // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
46462   if (!(Subtarget.hasXOP() || useVPTERNLOG(Subtarget, VT) ||
46463         !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
46464     return SDValue();
46465 
46466   // Attempt to extract constant byte masks.
46467   APInt UndefElts0, UndefElts1;
46468   SmallVector<APInt, 32> EltBits0, EltBits1;
46469   if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
46470                                      false, false))
46471     return SDValue();
46472   if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
46473                                      false, false))
46474     return SDValue();
46475 
46476   for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
46477     // TODO - add UNDEF elts support.
46478     if (UndefElts0[i] || UndefElts1[i])
46479       return SDValue();
46480     if (EltBits0[i] != ~EltBits1[i])
46481       return SDValue();
46482   }
46483 
46484   SDLoc DL(N);
46485 
46486   if (useVPTERNLOG(Subtarget, VT)) {
46487     // Emit a VPTERNLOG node directly - 0xCA is the imm code for A?B:C.
46488     // VPTERNLOG is only available as vXi32/64-bit types.
46489     MVT OpSVT = EltSizeInBits == 32 ? MVT::i32 : MVT::i64;
46490     MVT OpVT =
46491         MVT::getVectorVT(OpSVT, VT.getSizeInBits() / OpSVT.getSizeInBits());
46492     SDValue A = DAG.getBitcast(OpVT, N0.getOperand(1));
46493     SDValue B = DAG.getBitcast(OpVT, N0.getOperand(0));
46494     SDValue C = DAG.getBitcast(OpVT, N1.getOperand(0));
46495     SDValue Imm = DAG.getTargetConstant(0xCA, DL, MVT::i8);
46496     SDValue Res = getAVX512Node(X86ISD::VPTERNLOG, DL, OpVT, {A, B, C, Imm},
46497                                 DAG, Subtarget);
46498     return DAG.getBitcast(VT, Res);
46499   }
46500 
46501   SDValue X = N->getOperand(0);
46502   SDValue Y =
46503       DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
46504                   DAG.getBitcast(VT, N1.getOperand(0)));
46505   return DAG.getNode(ISD::OR, DL, VT, X, Y);
46506 }
46507 
46508 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
46509 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
46510   if (N->getOpcode() != ISD::OR)
46511     return false;
46512 
46513   SDValue N0 = N->getOperand(0);
46514   SDValue N1 = N->getOperand(1);
46515 
46516   // Canonicalize AND to LHS.
46517   if (N1.getOpcode() == ISD::AND)
46518     std::swap(N0, N1);
46519 
46520   // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
46521   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
46522     return false;
46523 
46524   Mask = N1.getOperand(0);
46525   X = N1.getOperand(1);
46526 
46527   // Check to see if the mask appeared in both the AND and ANDNP.
46528   if (N0.getOperand(0) == Mask)
46529     Y = N0.getOperand(1);
46530   else if (N0.getOperand(1) == Mask)
46531     Y = N0.getOperand(0);
46532   else
46533     return false;
46534 
46535   // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
46536   // ANDNP combine allows other combines to happen that prevent matching.
46537   return true;
46538 }
46539 
46540 // Try to fold:
46541 //   (or (and (m, y), (pandn m, x)))
46542 // into:
46543 //   (vselect m, x, y)
46544 // As a special case, try to fold:
46545 //   (or (and (m, (sub 0, x)), (pandn m, x)))
46546 // into:
46547 //   (sub (xor X, M), M)
46548 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
46549                                             const X86Subtarget &Subtarget) {
46550   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
46551 
46552   EVT VT = N->getValueType(0);
46553   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
46554         (VT.is256BitVector() && Subtarget.hasInt256())))
46555     return SDValue();
46556 
46557   SDValue X, Y, Mask;
46558   if (!matchLogicBlend(N, X, Y, Mask))
46559     return SDValue();
46560 
46561   // Validate that X, Y, and Mask are bitcasts, and see through them.
46562   Mask = peekThroughBitcasts(Mask);
46563   X = peekThroughBitcasts(X);
46564   Y = peekThroughBitcasts(Y);
46565 
46566   EVT MaskVT = Mask.getValueType();
46567   unsigned EltBits = MaskVT.getScalarSizeInBits();
46568 
46569   // TODO: Attempt to handle floating point cases as well?
46570   if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
46571     return SDValue();
46572 
46573   SDLoc DL(N);
46574 
46575   // Attempt to combine to conditional negate: (sub (xor X, M), M)
46576   if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
46577                                                            DAG, Subtarget))
46578     return Res;
46579 
46580   // PBLENDVB is only available on SSE 4.1.
46581   if (!Subtarget.hasSSE41())
46582     return SDValue();
46583 
46584   // If we have VPTERNLOG we should prefer that since PBLENDVB is multiple uops.
46585   if (Subtarget.hasVLX())
46586     return SDValue();
46587 
46588   MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
46589 
46590   X = DAG.getBitcast(BlendVT, X);
46591   Y = DAG.getBitcast(BlendVT, Y);
46592   Mask = DAG.getBitcast(BlendVT, Mask);
46593   Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
46594   return DAG.getBitcast(VT, Mask);
46595 }
46596 
46597 // Helper function for combineOrCmpEqZeroToCtlzSrl
46598 // Transforms:
46599 //   seteq(cmp x, 0)
46600 //   into:
46601 //   srl(ctlz x), log2(bitsize(x))
46602 // Input pattern is checked by caller.
46603 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, EVT ExtTy,
46604                                           SelectionDAG &DAG) {
46605   SDValue Cmp = Op.getOperand(1);
46606   EVT VT = Cmp.getOperand(0).getValueType();
46607   unsigned Log2b = Log2_32(VT.getSizeInBits());
46608   SDLoc dl(Op);
46609   SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
46610   // The result of the shift is true or false, and on X86, the 32-bit
46611   // encoding of shr and lzcnt is more desirable.
46612   SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
46613   SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
46614                             DAG.getConstant(Log2b, dl, MVT::i8));
46615   return DAG.getZExtOrTrunc(Scc, dl, ExtTy);
46616 }
46617 
46618 // Try to transform:
46619 //   zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
46620 //   into:
46621 //   srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
46622 // Will also attempt to match more generic cases, eg:
46623 //   zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
46624 // Only applies if the target supports the FastLZCNT feature.
46625 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
46626                                            TargetLowering::DAGCombinerInfo &DCI,
46627                                            const X86Subtarget &Subtarget) {
46628   if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
46629     return SDValue();
46630 
46631   auto isORCandidate = [](SDValue N) {
46632     return (N->getOpcode() == ISD::OR && N->hasOneUse());
46633   };
46634 
46635   // Check the zero extend is extending to 32-bit or more. The code generated by
46636   // srl(ctlz) for 16-bit or less variants of the pattern would require extra
46637   // instructions to clear the upper bits.
46638   if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
46639       !isORCandidate(N->getOperand(0)))
46640     return SDValue();
46641 
46642   // Check the node matches: setcc(eq, cmp 0)
46643   auto isSetCCCandidate = [](SDValue N) {
46644     return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
46645            X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
46646            N->getOperand(1).getOpcode() == X86ISD::CMP &&
46647            isNullConstant(N->getOperand(1).getOperand(1)) &&
46648            N->getOperand(1).getValueType().bitsGE(MVT::i32);
46649   };
46650 
46651   SDNode *OR = N->getOperand(0).getNode();
46652   SDValue LHS = OR->getOperand(0);
46653   SDValue RHS = OR->getOperand(1);
46654 
46655   // Save nodes matching or(or, setcc(eq, cmp 0)).
46656   SmallVector<SDNode *, 2> ORNodes;
46657   while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
46658           (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
46659     ORNodes.push_back(OR);
46660     OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
46661     LHS = OR->getOperand(0);
46662     RHS = OR->getOperand(1);
46663   }
46664 
46665   // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
46666   if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
46667       !isORCandidate(SDValue(OR, 0)))
46668     return SDValue();
46669 
46670   // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
46671   // to
46672   // or(srl(ctlz),srl(ctlz)).
46673   // The dag combiner can then fold it into:
46674   // srl(or(ctlz, ctlz)).
46675   EVT VT = OR->getValueType(0);
46676   SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, VT, DAG);
46677   SDValue Ret, NewRHS;
46678   if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG)))
46679     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, NewLHS, NewRHS);
46680 
46681   if (!Ret)
46682     return SDValue();
46683 
46684   // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
46685   while (ORNodes.size() > 0) {
46686     OR = ORNodes.pop_back_val();
46687     LHS = OR->getOperand(0);
46688     RHS = OR->getOperand(1);
46689     // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
46690     if (RHS->getOpcode() == ISD::OR)
46691       std::swap(LHS, RHS);
46692     NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG);
46693     if (!NewRHS)
46694       return SDValue();
46695     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, Ret, NewRHS);
46696   }
46697 
46698   if (Ret)
46699     Ret = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
46700 
46701   return Ret;
46702 }
46703 
46704 static SDValue foldMaskedMergeImpl(SDValue And0_L, SDValue And0_R,
46705                                    SDValue And1_L, SDValue And1_R, SDLoc DL,
46706                                    SelectionDAG &DAG) {
46707   if (!isBitwiseNot(And0_L, true) || !And0_L->hasOneUse())
46708     return SDValue();
46709   SDValue NotOp = And0_L->getOperand(0);
46710   if (NotOp == And1_R)
46711     std::swap(And1_R, And1_L);
46712   if (NotOp != And1_L)
46713     return SDValue();
46714 
46715   // (~(NotOp) & And0_R) | (NotOp & And1_R)
46716   // --> ((And0_R ^ And1_R) & NotOp) ^ And1_R
46717   EVT VT = And1_L->getValueType(0);
46718   SDValue Freeze_And0_R = DAG.getNode(ISD::FREEZE, SDLoc(), VT, And0_R);
46719   SDValue Xor0 = DAG.getNode(ISD::XOR, DL, VT, And1_R, Freeze_And0_R);
46720   SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor0, NotOp);
46721   SDValue Xor1 = DAG.getNode(ISD::XOR, DL, VT, And, Freeze_And0_R);
46722   return Xor1;
46723 }
46724 
46725 /// Fold "masked merge" expressions like `(m & x) | (~m & y)` into the
46726 /// equivalent `((x ^ y) & m) ^ y)` pattern.
46727 /// This is typically a better representation for  targets without a fused
46728 /// "and-not" operation. This function is intended to be called from a
46729 /// `TargetLowering::PerformDAGCombine` callback on `ISD::OR` nodes.
46730 static SDValue foldMaskedMerge(SDNode *Node, SelectionDAG &DAG) {
46731   // Note that masked-merge variants using XOR or ADD expressions are
46732   // normalized to OR by InstCombine so we only check for OR.
46733   assert(Node->getOpcode() == ISD::OR && "Must be called with ISD::OR node");
46734   SDValue N0 = Node->getOperand(0);
46735   if (N0->getOpcode() != ISD::AND || !N0->hasOneUse())
46736     return SDValue();
46737   SDValue N1 = Node->getOperand(1);
46738   if (N1->getOpcode() != ISD::AND || !N1->hasOneUse())
46739     return SDValue();
46740 
46741   SDLoc DL(Node);
46742   SDValue N00 = N0->getOperand(0);
46743   SDValue N01 = N0->getOperand(1);
46744   SDValue N10 = N1->getOperand(0);
46745   SDValue N11 = N1->getOperand(1);
46746   if (SDValue Result = foldMaskedMergeImpl(N00, N01, N10, N11, DL, DAG))
46747     return Result;
46748   if (SDValue Result = foldMaskedMergeImpl(N01, N00, N10, N11, DL, DAG))
46749     return Result;
46750   if (SDValue Result = foldMaskedMergeImpl(N10, N11, N00, N01, DL, DAG))
46751     return Result;
46752   if (SDValue Result = foldMaskedMergeImpl(N11, N10, N00, N01, DL, DAG))
46753     return Result;
46754   return SDValue();
46755 }
46756 
46757 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
46758                          TargetLowering::DAGCombinerInfo &DCI,
46759                          const X86Subtarget &Subtarget) {
46760   SDValue N0 = N->getOperand(0);
46761   SDValue N1 = N->getOperand(1);
46762   EVT VT = N->getValueType(0);
46763   SDLoc dl(N);
46764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46765 
46766   // If this is SSE1 only convert to FOR to avoid scalarization.
46767   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
46768     return DAG.getBitcast(MVT::v4i32,
46769                           DAG.getNode(X86ISD::FOR, dl, MVT::v4f32,
46770                                       DAG.getBitcast(MVT::v4f32, N0),
46771                                       DAG.getBitcast(MVT::v4f32, N1)));
46772   }
46773 
46774   // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
46775   // TODO: Support multiple SrcOps.
46776   if (VT == MVT::i1) {
46777     SmallVector<SDValue, 2> SrcOps;
46778     SmallVector<APInt, 2> SrcPartials;
46779     if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps, &SrcPartials) &&
46780         SrcOps.size() == 1) {
46781       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
46782       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
46783       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
46784       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
46785         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
46786       if (Mask) {
46787         assert(SrcPartials[0].getBitWidth() == NumElts &&
46788                "Unexpected partial reduction mask");
46789         SDValue ZeroBits = DAG.getConstant(0, dl, MaskVT);
46790         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
46791         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
46792         return DAG.getSetCC(dl, MVT::i1, Mask, ZeroBits, ISD::SETNE);
46793       }
46794     }
46795   }
46796 
46797   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
46798     return R;
46799 
46800   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
46801     return FPLogic;
46802 
46803   if (DCI.isBeforeLegalizeOps())
46804     return SDValue();
46805 
46806   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
46807     return R;
46808 
46809   if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
46810     return R;
46811 
46812   if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
46813     return R;
46814 
46815   // Combine OR(X,KSHIFTL(Y,Elts/2)) -> CONCAT_VECTORS(X,Y) == KUNPCK(X,Y).
46816   // Combine OR(KSHIFTL(X,Elts/2),Y) -> CONCAT_VECTORS(Y,X) == KUNPCK(Y,X).
46817   // iff the upper elements of the non-shifted arg are zero.
46818   // KUNPCK require 16+ bool vector elements.
46819   if (N0.getOpcode() == X86ISD::KSHIFTL || N1.getOpcode() == X86ISD::KSHIFTL) {
46820     unsigned NumElts = VT.getVectorNumElements();
46821     unsigned HalfElts = NumElts / 2;
46822     APInt UpperElts = APInt::getHighBitsSet(NumElts, HalfElts);
46823     if (NumElts >= 16 && N1.getOpcode() == X86ISD::KSHIFTL &&
46824         N1.getConstantOperandAPInt(1) == HalfElts &&
46825         DAG.MaskedValueIsZero(N0, APInt(1, 1), UpperElts)) {
46826       return DAG.getNode(
46827           ISD::CONCAT_VECTORS, dl, VT,
46828           extractSubVector(N0, 0, DAG, dl, HalfElts),
46829           extractSubVector(N1.getOperand(0), 0, DAG, dl, HalfElts));
46830     }
46831     if (NumElts >= 16 && N0.getOpcode() == X86ISD::KSHIFTL &&
46832         N0.getConstantOperandAPInt(1) == HalfElts &&
46833         DAG.MaskedValueIsZero(N1, APInt(1, 1), UpperElts)) {
46834       return DAG.getNode(
46835           ISD::CONCAT_VECTORS, dl, VT,
46836           extractSubVector(N1, 0, DAG, dl, HalfElts),
46837           extractSubVector(N0.getOperand(0), 0, DAG, dl, HalfElts));
46838     }
46839   }
46840 
46841   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
46842     // Attempt to recursively combine an OR of shuffles.
46843     SDValue Op(N, 0);
46844     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
46845       return Res;
46846 
46847     // If either operand is a constant mask, then only the elements that aren't
46848     // allones are actually demanded by the other operand.
46849     auto SimplifyUndemandedElts = [&](SDValue Op, SDValue OtherOp) {
46850       APInt UndefElts;
46851       SmallVector<APInt> EltBits;
46852       int NumElts = VT.getVectorNumElements();
46853       int EltSizeInBits = VT.getScalarSizeInBits();
46854       if (!getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts, EltBits))
46855         return false;
46856 
46857       APInt DemandedElts = APInt::getZero(NumElts);
46858       for (int I = 0; I != NumElts; ++I)
46859         if (!EltBits[I].isAllOnes())
46860           DemandedElts.setBit(I);
46861 
46862       APInt KnownUndef, KnownZero;
46863       return TLI.SimplifyDemandedVectorElts(OtherOp, DemandedElts, KnownUndef,
46864                                             KnownZero, DCI);
46865     };
46866     if (SimplifyUndemandedElts(N0, N1) || SimplifyUndemandedElts(N1, N0)) {
46867       if (N->getOpcode() != ISD::DELETED_NODE)
46868         DCI.AddToWorklist(N);
46869       return SDValue(N, 0);
46870     }
46871   }
46872 
46873   // We should fold "masked merge" patterns when `andn` is not available.
46874   if (!Subtarget.hasBMI() && VT.isScalarInteger() && VT != MVT::i1)
46875     if (SDValue R = foldMaskedMerge(N, DAG))
46876       return R;
46877 
46878   return SDValue();
46879 }
46880 
46881 /// Try to turn tests against the signbit in the form of:
46882 ///   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
46883 /// into:
46884 ///   SETGT(X, -1)
46885 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
46886   // This is only worth doing if the output type is i8 or i1.
46887   EVT ResultType = N->getValueType(0);
46888   if (ResultType != MVT::i8 && ResultType != MVT::i1)
46889     return SDValue();
46890 
46891   SDValue N0 = N->getOperand(0);
46892   SDValue N1 = N->getOperand(1);
46893 
46894   // We should be performing an xor against a truncated shift.
46895   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
46896     return SDValue();
46897 
46898   // Make sure we are performing an xor against one.
46899   if (!isOneConstant(N1))
46900     return SDValue();
46901 
46902   // SetCC on x86 zero extends so only act on this if it's a logical shift.
46903   SDValue Shift = N0.getOperand(0);
46904   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
46905     return SDValue();
46906 
46907   // Make sure we are truncating from one of i16, i32 or i64.
46908   EVT ShiftTy = Shift.getValueType();
46909   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
46910     return SDValue();
46911 
46912   // Make sure the shift amount extracts the sign bit.
46913   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
46914       Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
46915     return SDValue();
46916 
46917   // Create a greater-than comparison against -1.
46918   // N.B. Using SETGE against 0 works but we want a canonical looking
46919   // comparison, using SETGT matches up with what TranslateX86CC.
46920   SDLoc DL(N);
46921   SDValue ShiftOp = Shift.getOperand(0);
46922   EVT ShiftOpTy = ShiftOp.getValueType();
46923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46924   EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
46925                                                *DAG.getContext(), ResultType);
46926   SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
46927                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
46928   if (SetCCResultType != ResultType)
46929     Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
46930   return Cond;
46931 }
46932 
46933 /// Turn vector tests of the signbit in the form of:
46934 ///   xor (sra X, elt_size(X)-1), -1
46935 /// into:
46936 ///   pcmpgt X, -1
46937 ///
46938 /// This should be called before type legalization because the pattern may not
46939 /// persist after that.
46940 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
46941                                          const X86Subtarget &Subtarget) {
46942   EVT VT = N->getValueType(0);
46943   if (!VT.isSimple())
46944     return SDValue();
46945 
46946   switch (VT.getSimpleVT().SimpleTy) {
46947   default: return SDValue();
46948   case MVT::v16i8:
46949   case MVT::v8i16:
46950   case MVT::v4i32:
46951   case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
46952   case MVT::v32i8:
46953   case MVT::v16i16:
46954   case MVT::v8i32:
46955   case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
46956   }
46957 
46958   // There must be a shift right algebraic before the xor, and the xor must be a
46959   // 'not' operation.
46960   SDValue Shift = N->getOperand(0);
46961   SDValue Ones = N->getOperand(1);
46962   if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
46963       !ISD::isBuildVectorAllOnes(Ones.getNode()))
46964     return SDValue();
46965 
46966   // The shift should be smearing the sign bit across each vector element.
46967   auto *ShiftAmt =
46968       isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
46969   if (!ShiftAmt ||
46970       ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
46971     return SDValue();
46972 
46973   // Create a greater-than comparison against -1. We don't use the more obvious
46974   // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
46975   return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
46976 }
46977 
46978 /// Detect patterns of truncation with unsigned saturation:
46979 ///
46980 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
46981 ///   Return the source value x to be truncated or SDValue() if the pattern was
46982 ///   not matched.
46983 ///
46984 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
46985 ///   where C1 >= 0 and C2 is unsigned max of destination type.
46986 ///
46987 ///    (truncate (smax (smin (x, C2), C1)) to dest_type)
46988 ///   where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
46989 ///
46990 ///   These two patterns are equivalent to:
46991 ///   (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
46992 ///   So return the smax(x, C1) value to be truncated or SDValue() if the
46993 ///   pattern was not matched.
46994 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
46995                                  const SDLoc &DL) {
46996   EVT InVT = In.getValueType();
46997 
46998   // Saturation with truncation. We truncate from InVT to VT.
46999   assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
47000          "Unexpected types for truncate operation");
47001 
47002   // Match min/max and return limit value as a parameter.
47003   auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
47004     if (V.getOpcode() == Opcode &&
47005         ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
47006       return V.getOperand(0);
47007     return SDValue();
47008   };
47009 
47010   APInt C1, C2;
47011   if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
47012     // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
47013     // the element size of the destination type.
47014     if (C2.isMask(VT.getScalarSizeInBits()))
47015       return UMin;
47016 
47017   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
47018     if (MatchMinMax(SMin, ISD::SMAX, C1))
47019       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
47020         return SMin;
47021 
47022   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
47023     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
47024       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
47025           C2.uge(C1)) {
47026         return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
47027       }
47028 
47029   return SDValue();
47030 }
47031 
47032 /// Detect patterns of truncation with signed saturation:
47033 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
47034 ///                  signed_max_of_dest_type)) to dest_type)
47035 /// or:
47036 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
47037 ///                  signed_min_of_dest_type)) to dest_type).
47038 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
47039 /// Return the source value to be truncated or SDValue() if the pattern was not
47040 /// matched.
47041 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
47042   unsigned NumDstBits = VT.getScalarSizeInBits();
47043   unsigned NumSrcBits = In.getScalarValueSizeInBits();
47044   assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
47045 
47046   auto MatchMinMax = [](SDValue V, unsigned Opcode,
47047                         const APInt &Limit) -> SDValue {
47048     APInt C;
47049     if (V.getOpcode() == Opcode &&
47050         ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
47051       return V.getOperand(0);
47052     return SDValue();
47053   };
47054 
47055   APInt SignedMax, SignedMin;
47056   if (MatchPackUS) {
47057     SignedMax = APInt::getAllOnes(NumDstBits).zext(NumSrcBits);
47058     SignedMin = APInt(NumSrcBits, 0);
47059   } else {
47060     SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
47061     SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
47062   }
47063 
47064   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
47065     if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
47066       return SMax;
47067 
47068   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
47069     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
47070       return SMin;
47071 
47072   return SDValue();
47073 }
47074 
47075 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
47076                                       SelectionDAG &DAG,
47077                                       const X86Subtarget &Subtarget) {
47078   if (!Subtarget.hasSSE2() || !VT.isVector())
47079     return SDValue();
47080 
47081   EVT SVT = VT.getVectorElementType();
47082   EVT InVT = In.getValueType();
47083   EVT InSVT = InVT.getVectorElementType();
47084 
47085   // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
47086   // split across two registers. We can use a packusdw+perm to clamp to 0-65535
47087   // and concatenate at the same time. Then we can use a final vpmovuswb to
47088   // clip to 0-255.
47089   if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
47090       InVT == MVT::v16i32 && VT == MVT::v16i8) {
47091     if (auto USatVal = detectSSatPattern(In, VT, true)) {
47092       // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
47093       SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
47094                                            DL, DAG, Subtarget);
47095       assert(Mid && "Failed to pack!");
47096       return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
47097     }
47098   }
47099 
47100   // vXi32 truncate instructions are available with AVX512F.
47101   // vXi16 truncate instructions are only available with AVX512BW.
47102   // For 256-bit or smaller vectors, we require VLX.
47103   // FIXME: We could widen truncates to 512 to remove the VLX restriction.
47104   // If the result type is 256-bits or larger and we have disable 512-bit
47105   // registers, we should go ahead and use the pack instructions if possible.
47106   bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
47107                        (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
47108                       (InVT.getSizeInBits() > 128) &&
47109                       (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
47110                       !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
47111 
47112   if (isPowerOf2_32(VT.getVectorNumElements()) && !PreferAVX512 &&
47113       VT.getSizeInBits() >= 64 &&
47114       (SVT == MVT::i8 || SVT == MVT::i16) &&
47115       (InSVT == MVT::i16 || InSVT == MVT::i32)) {
47116     if (auto USatVal = detectSSatPattern(In, VT, true)) {
47117       // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
47118       // Only do this when the result is at least 64 bits or we'll leaving
47119       // dangling PACKSSDW nodes.
47120       if (SVT == MVT::i8 && InSVT == MVT::i32) {
47121         EVT MidVT = VT.changeVectorElementType(MVT::i16);
47122         SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
47123                                              DAG, Subtarget);
47124         assert(Mid && "Failed to pack!");
47125         SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
47126                                            Subtarget);
47127         assert(V && "Failed to pack!");
47128         return V;
47129       } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
47130         return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
47131                                       Subtarget);
47132     }
47133     if (auto SSatVal = detectSSatPattern(In, VT))
47134       return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
47135                                     Subtarget);
47136   }
47137 
47138   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47139   if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
47140       Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI()) &&
47141       (SVT == MVT::i32 || SVT == MVT::i16 || SVT == MVT::i8)) {
47142     unsigned TruncOpc = 0;
47143     SDValue SatVal;
47144     if (auto SSatVal = detectSSatPattern(In, VT)) {
47145       SatVal = SSatVal;
47146       TruncOpc = X86ISD::VTRUNCS;
47147     } else if (auto USatVal = detectUSatPattern(In, VT, DAG, DL)) {
47148       SatVal = USatVal;
47149       TruncOpc = X86ISD::VTRUNCUS;
47150     }
47151     if (SatVal) {
47152       unsigned ResElts = VT.getVectorNumElements();
47153       // If the input type is less than 512 bits and we don't have VLX, we need
47154       // to widen to 512 bits.
47155       if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
47156         unsigned NumConcats = 512 / InVT.getSizeInBits();
47157         ResElts *= NumConcats;
47158         SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
47159         ConcatOps[0] = SatVal;
47160         InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
47161                                 NumConcats * InVT.getVectorNumElements());
47162         SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
47163       }
47164       // Widen the result if its narrower than 128 bits.
47165       if (ResElts * SVT.getSizeInBits() < 128)
47166         ResElts = 128 / SVT.getSizeInBits();
47167       EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
47168       SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
47169       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
47170                          DAG.getIntPtrConstant(0, DL));
47171     }
47172   }
47173 
47174   return SDValue();
47175 }
47176 
47177 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
47178 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
47179 /// X86ISD::AVG instruction.
47180 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
47181                                 const X86Subtarget &Subtarget,
47182                                 const SDLoc &DL) {
47183   if (!VT.isVector())
47184     return SDValue();
47185   EVT InVT = In.getValueType();
47186   unsigned NumElems = VT.getVectorNumElements();
47187 
47188   EVT ScalarVT = VT.getVectorElementType();
47189   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) && NumElems >= 2))
47190     return SDValue();
47191 
47192   // InScalarVT is the intermediate type in AVG pattern and it should be greater
47193   // than the original input type (i8/i16).
47194   EVT InScalarVT = InVT.getVectorElementType();
47195   if (InScalarVT.getFixedSizeInBits() <= ScalarVT.getFixedSizeInBits())
47196     return SDValue();
47197 
47198   if (!Subtarget.hasSSE2())
47199     return SDValue();
47200 
47201   // Detect the following pattern:
47202   //
47203   //   %1 = zext <N x i8> %a to <N x i32>
47204   //   %2 = zext <N x i8> %b to <N x i32>
47205   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
47206   //   %4 = add nuw nsw <N x i32> %3, %2
47207   //   %5 = lshr <N x i32> %N, <i32 1 x N>
47208   //   %6 = trunc <N x i32> %5 to <N x i8>
47209   //
47210   // In AVX512, the last instruction can also be a trunc store.
47211   if (In.getOpcode() != ISD::SRL)
47212     return SDValue();
47213 
47214   // A lambda checking the given SDValue is a constant vector and each element
47215   // is in the range [Min, Max].
47216   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
47217     return ISD::matchUnaryPredicate(V, [Min, Max](ConstantSDNode *C) {
47218       return !(C->getAPIntValue().ult(Min) || C->getAPIntValue().ugt(Max));
47219     });
47220   };
47221 
47222   auto IsZExtLike = [DAG = &DAG, ScalarVT](SDValue V) {
47223     unsigned MaxActiveBits = DAG->computeKnownBits(V).countMaxActiveBits();
47224     return MaxActiveBits <= ScalarVT.getSizeInBits();
47225   };
47226 
47227   // Check if each element of the vector is right-shifted by one.
47228   SDValue LHS = In.getOperand(0);
47229   SDValue RHS = In.getOperand(1);
47230   if (!IsConstVectorInRange(RHS, 1, 1))
47231     return SDValue();
47232   if (LHS.getOpcode() != ISD::ADD)
47233     return SDValue();
47234 
47235   // Detect a pattern of a + b + 1 where the order doesn't matter.
47236   SDValue Operands[3];
47237   Operands[0] = LHS.getOperand(0);
47238   Operands[1] = LHS.getOperand(1);
47239 
47240   auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
47241                        ArrayRef<SDValue> Ops) {
47242     return DAG.getNode(X86ISD::AVG, DL, Ops[0].getValueType(), Ops);
47243   };
47244 
47245   auto AVGSplitter = [&](std::array<SDValue, 2> Ops) {
47246     for (SDValue &Op : Ops)
47247       if (Op.getValueType() != VT)
47248         Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
47249     // Pad to a power-of-2 vector, split+apply and extract the original vector.
47250     unsigned NumElemsPow2 = PowerOf2Ceil(NumElems);
47251     EVT Pow2VT = EVT::getVectorVT(*DAG.getContext(), ScalarVT, NumElemsPow2);
47252     if (NumElemsPow2 != NumElems) {
47253       for (SDValue &Op : Ops) {
47254         SmallVector<SDValue, 32> EltsOfOp(NumElemsPow2, DAG.getUNDEF(ScalarVT));
47255         for (unsigned i = 0; i != NumElems; ++i) {
47256           SDValue Idx = DAG.getIntPtrConstant(i, DL);
47257           EltsOfOp[i] =
47258               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Op, Idx);
47259         }
47260         Op = DAG.getBuildVector(Pow2VT, DL, EltsOfOp);
47261       }
47262     }
47263     SDValue Res = SplitOpsAndApply(DAG, Subtarget, DL, Pow2VT, Ops, AVGBuilder);
47264     if (NumElemsPow2 == NumElems)
47265       return Res;
47266     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
47267                        DAG.getIntPtrConstant(0, DL));
47268   };
47269 
47270   // Take care of the case when one of the operands is a constant vector whose
47271   // element is in the range [1, 256].
47272   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
47273       IsZExtLike(Operands[0])) {
47274     // The pattern is detected. Subtract one from the constant vector, then
47275     // demote it and emit X86ISD::AVG instruction.
47276     SDValue VecOnes = DAG.getConstant(1, DL, InVT);
47277     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
47278     return AVGSplitter({Operands[0], Operands[1]});
47279   }
47280 
47281   // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
47282   // Match the or case only if its 'add-like' - can be replaced by an add.
47283   auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
47284     if (ISD::ADD == V.getOpcode()) {
47285       Op0 = V.getOperand(0);
47286       Op1 = V.getOperand(1);
47287       return true;
47288     }
47289     if (ISD::ZERO_EXTEND != V.getOpcode())
47290       return false;
47291     V = V.getOperand(0);
47292     if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
47293         !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
47294       return false;
47295     Op0 = V.getOperand(0);
47296     Op1 = V.getOperand(1);
47297     return true;
47298   };
47299 
47300   SDValue Op0, Op1;
47301   if (FindAddLike(Operands[0], Op0, Op1))
47302     std::swap(Operands[0], Operands[1]);
47303   else if (!FindAddLike(Operands[1], Op0, Op1))
47304     return SDValue();
47305   Operands[2] = Op0;
47306   Operands[1] = Op1;
47307 
47308   // Now we have three operands of two additions. Check that one of them is a
47309   // constant vector with ones, and the other two can be promoted from i8/i16.
47310   for (int i = 0; i < 3; ++i) {
47311     if (!IsConstVectorInRange(Operands[i], 1, 1))
47312       continue;
47313     std::swap(Operands[i], Operands[2]);
47314 
47315     // Check if Operands[0] and Operands[1] are results of type promotion.
47316     for (int j = 0; j < 2; ++j)
47317       if (Operands[j].getValueType() != VT)
47318         if (!IsZExtLike(Operands[j]))
47319           return SDValue();
47320 
47321     // The pattern is detected, emit X86ISD::AVG instruction(s).
47322     return AVGSplitter({Operands[0], Operands[1]});
47323   }
47324 
47325   return SDValue();
47326 }
47327 
47328 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
47329                            TargetLowering::DAGCombinerInfo &DCI,
47330                            const X86Subtarget &Subtarget) {
47331   LoadSDNode *Ld = cast<LoadSDNode>(N);
47332   EVT RegVT = Ld->getValueType(0);
47333   EVT MemVT = Ld->getMemoryVT();
47334   SDLoc dl(Ld);
47335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47336 
47337   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
47338   // into two 16-byte operations. Also split non-temporal aligned loads on
47339   // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
47340   ISD::LoadExtType Ext = Ld->getExtensionType();
47341   bool Fast;
47342   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
47343       Ext == ISD::NON_EXTLOAD &&
47344       ((Ld->isNonTemporal() && !Subtarget.hasInt256() &&
47345         Ld->getAlignment() >= 16) ||
47346        (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
47347                                *Ld->getMemOperand(), &Fast) &&
47348         !Fast))) {
47349     unsigned NumElems = RegVT.getVectorNumElements();
47350     if (NumElems < 2)
47351       return SDValue();
47352 
47353     unsigned HalfOffset = 16;
47354     SDValue Ptr1 = Ld->getBasePtr();
47355     SDValue Ptr2 =
47356         DAG.getMemBasePlusOffset(Ptr1, TypeSize::Fixed(HalfOffset), dl);
47357     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
47358                                   NumElems / 2);
47359     SDValue Load1 =
47360         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
47361                     Ld->getOriginalAlign(),
47362                     Ld->getMemOperand()->getFlags());
47363     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
47364                                 Ld->getPointerInfo().getWithOffset(HalfOffset),
47365                                 Ld->getOriginalAlign(),
47366                                 Ld->getMemOperand()->getFlags());
47367     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
47368                              Load1.getValue(1), Load2.getValue(1));
47369 
47370     SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
47371     return DCI.CombineTo(N, NewVec, TF, true);
47372   }
47373 
47374   // Bool vector load - attempt to cast to an integer, as we have good
47375   // (vXiY *ext(vXi1 bitcast(iX))) handling.
47376   if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
47377       RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
47378     unsigned NumElts = RegVT.getVectorNumElements();
47379     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
47380     if (TLI.isTypeLegal(IntVT)) {
47381       SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
47382                                     Ld->getPointerInfo(),
47383                                     Ld->getOriginalAlign(),
47384                                     Ld->getMemOperand()->getFlags());
47385       SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
47386       return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
47387     }
47388   }
47389 
47390   // If we also broadcast this as a subvector to a wider type, then just extract
47391   // the lowest subvector.
47392   if (Ext == ISD::NON_EXTLOAD && Subtarget.hasAVX() && Ld->isSimple() &&
47393       (RegVT.is128BitVector() || RegVT.is256BitVector())) {
47394     SDValue Ptr = Ld->getBasePtr();
47395     SDValue Chain = Ld->getChain();
47396     for (SDNode *User : Ptr->uses()) {
47397       if (User != N && User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
47398           cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
47399           cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
47400           cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
47401               MemVT.getSizeInBits() &&
47402           !User->hasAnyUseOfValue(1) &&
47403           User->getValueSizeInBits(0).getFixedSize() >
47404               RegVT.getFixedSizeInBits()) {
47405         SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
47406                                            RegVT.getSizeInBits());
47407         Extract = DAG.getBitcast(RegVT, Extract);
47408         return DCI.CombineTo(N, Extract, SDValue(User, 1));
47409       }
47410     }
47411   }
47412 
47413   // Cast ptr32 and ptr64 pointers to the default address space before a load.
47414   unsigned AddrSpace = Ld->getAddressSpace();
47415   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
47416       AddrSpace == X86AS::PTR32_UPTR) {
47417     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
47418     if (PtrVT != Ld->getBasePtr().getSimpleValueType()) {
47419       SDValue Cast =
47420           DAG.getAddrSpaceCast(dl, PtrVT, Ld->getBasePtr(), AddrSpace, 0);
47421       return DAG.getLoad(RegVT, dl, Ld->getChain(), Cast, Ld->getPointerInfo(),
47422                          Ld->getOriginalAlign(),
47423                          Ld->getMemOperand()->getFlags());
47424     }
47425   }
47426 
47427   return SDValue();
47428 }
47429 
47430 /// If V is a build vector of boolean constants and exactly one of those
47431 /// constants is true, return the operand index of that true element.
47432 /// Otherwise, return -1.
47433 static int getOneTrueElt(SDValue V) {
47434   // This needs to be a build vector of booleans.
47435   // TODO: Checking for the i1 type matches the IR definition for the mask,
47436   // but the mask check could be loosened to i8 or other types. That might
47437   // also require checking more than 'allOnesValue'; eg, the x86 HW
47438   // instructions only require that the MSB is set for each mask element.
47439   // The ISD::MSTORE comments/definition do not specify how the mask operand
47440   // is formatted.
47441   auto *BV = dyn_cast<BuildVectorSDNode>(V);
47442   if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
47443     return -1;
47444 
47445   int TrueIndex = -1;
47446   unsigned NumElts = BV->getValueType(0).getVectorNumElements();
47447   for (unsigned i = 0; i < NumElts; ++i) {
47448     const SDValue &Op = BV->getOperand(i);
47449     if (Op.isUndef())
47450       continue;
47451     auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
47452     if (!ConstNode)
47453       return -1;
47454     if (ConstNode->getAPIntValue().countTrailingOnes() >= 1) {
47455       // If we already found a one, this is too many.
47456       if (TrueIndex >= 0)
47457         return -1;
47458       TrueIndex = i;
47459     }
47460   }
47461   return TrueIndex;
47462 }
47463 
47464 /// Given a masked memory load/store operation, return true if it has one mask
47465 /// bit set. If it has one mask bit set, then also return the memory address of
47466 /// the scalar element to load/store, the vector index to insert/extract that
47467 /// scalar element, and the alignment for the scalar memory access.
47468 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
47469                                          SelectionDAG &DAG, SDValue &Addr,
47470                                          SDValue &Index, Align &Alignment,
47471                                          unsigned &Offset) {
47472   int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
47473   if (TrueMaskElt < 0)
47474     return false;
47475 
47476   // Get the address of the one scalar element that is specified by the mask
47477   // using the appropriate offset from the base pointer.
47478   EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
47479   Offset = 0;
47480   Addr = MaskedOp->getBasePtr();
47481   if (TrueMaskElt != 0) {
47482     Offset = TrueMaskElt * EltVT.getStoreSize();
47483     Addr = DAG.getMemBasePlusOffset(Addr, TypeSize::Fixed(Offset),
47484                                     SDLoc(MaskedOp));
47485   }
47486 
47487   Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
47488   Alignment = commonAlignment(MaskedOp->getOriginalAlign(),
47489                               EltVT.getStoreSize());
47490   return true;
47491 }
47492 
47493 /// If exactly one element of the mask is set for a non-extending masked load,
47494 /// it is a scalar load and vector insert.
47495 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
47496 /// mask have already been optimized in IR, so we don't bother with those here.
47497 static SDValue
47498 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
47499                              TargetLowering::DAGCombinerInfo &DCI,
47500                              const X86Subtarget &Subtarget) {
47501   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
47502   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
47503   // However, some target hooks may need to be added to know when the transform
47504   // is profitable. Endianness would also have to be considered.
47505 
47506   SDValue Addr, VecIndex;
47507   Align Alignment;
47508   unsigned Offset;
47509   if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment, Offset))
47510     return SDValue();
47511 
47512   // Load the one scalar element that is specified by the mask using the
47513   // appropriate offset from the base pointer.
47514   SDLoc DL(ML);
47515   EVT VT = ML->getValueType(0);
47516   EVT EltVT = VT.getVectorElementType();
47517 
47518   EVT CastVT = VT;
47519   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
47520     EltVT = MVT::f64;
47521     CastVT = VT.changeVectorElementType(EltVT);
47522   }
47523 
47524   SDValue Load =
47525       DAG.getLoad(EltVT, DL, ML->getChain(), Addr,
47526                   ML->getPointerInfo().getWithOffset(Offset),
47527                   Alignment, ML->getMemOperand()->getFlags());
47528 
47529   SDValue PassThru = DAG.getBitcast(CastVT, ML->getPassThru());
47530 
47531   // Insert the loaded element into the appropriate place in the vector.
47532   SDValue Insert =
47533       DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, CastVT, PassThru, Load, VecIndex);
47534   Insert = DAG.getBitcast(VT, Insert);
47535   return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
47536 }
47537 
47538 static SDValue
47539 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
47540                               TargetLowering::DAGCombinerInfo &DCI) {
47541   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
47542   if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
47543     return SDValue();
47544 
47545   SDLoc DL(ML);
47546   EVT VT = ML->getValueType(0);
47547 
47548   // If we are loading the first and last elements of a vector, it is safe and
47549   // always faster to load the whole vector. Replace the masked load with a
47550   // vector load and select.
47551   unsigned NumElts = VT.getVectorNumElements();
47552   BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
47553   bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
47554   bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
47555   if (LoadFirstElt && LoadLastElt) {
47556     SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
47557                                 ML->getMemOperand());
47558     SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
47559                                   ML->getPassThru());
47560     return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
47561   }
47562 
47563   // Convert a masked load with a constant mask into a masked load and a select.
47564   // This allows the select operation to use a faster kind of select instruction
47565   // (for example, vblendvps -> vblendps).
47566 
47567   // Don't try this if the pass-through operand is already undefined. That would
47568   // cause an infinite loop because that's what we're about to create.
47569   if (ML->getPassThru().isUndef())
47570     return SDValue();
47571 
47572   if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
47573     return SDValue();
47574 
47575   // The new masked load has an undef pass-through operand. The select uses the
47576   // original pass-through operand.
47577   SDValue NewML = DAG.getMaskedLoad(
47578       VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
47579       DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
47580       ML->getAddressingMode(), ML->getExtensionType());
47581   SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
47582                                 ML->getPassThru());
47583 
47584   return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
47585 }
47586 
47587 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
47588                                  TargetLowering::DAGCombinerInfo &DCI,
47589                                  const X86Subtarget &Subtarget) {
47590   auto *Mld = cast<MaskedLoadSDNode>(N);
47591 
47592   // TODO: Expanding load with constant mask may be optimized as well.
47593   if (Mld->isExpandingLoad())
47594     return SDValue();
47595 
47596   if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
47597     if (SDValue ScalarLoad =
47598             reduceMaskedLoadToScalarLoad(Mld, DAG, DCI, Subtarget))
47599       return ScalarLoad;
47600 
47601     // TODO: Do some AVX512 subsets benefit from this transform?
47602     if (!Subtarget.hasAVX512())
47603       if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
47604         return Blend;
47605   }
47606 
47607   // If the mask value has been legalized to a non-boolean vector, try to
47608   // simplify ops leading up to it. We only demand the MSB of each lane.
47609   SDValue Mask = Mld->getMask();
47610   if (Mask.getScalarValueSizeInBits() != 1) {
47611     EVT VT = Mld->getValueType(0);
47612     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47613     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
47614     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
47615       if (N->getOpcode() != ISD::DELETED_NODE)
47616         DCI.AddToWorklist(N);
47617       return SDValue(N, 0);
47618     }
47619     if (SDValue NewMask =
47620             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
47621       return DAG.getMaskedLoad(
47622           VT, SDLoc(N), Mld->getChain(), Mld->getBasePtr(), Mld->getOffset(),
47623           NewMask, Mld->getPassThru(), Mld->getMemoryVT(), Mld->getMemOperand(),
47624           Mld->getAddressingMode(), Mld->getExtensionType());
47625   }
47626 
47627   return SDValue();
47628 }
47629 
47630 /// If exactly one element of the mask is set for a non-truncating masked store,
47631 /// it is a vector extract and scalar store.
47632 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
47633 /// mask have already been optimized in IR, so we don't bother with those here.
47634 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
47635                                               SelectionDAG &DAG,
47636                                               const X86Subtarget &Subtarget) {
47637   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
47638   // However, some target hooks may need to be added to know when the transform
47639   // is profitable. Endianness would also have to be considered.
47640 
47641   SDValue Addr, VecIndex;
47642   Align Alignment;
47643   unsigned Offset;
47644   if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment, Offset))
47645     return SDValue();
47646 
47647   // Extract the one scalar element that is actually being stored.
47648   SDLoc DL(MS);
47649   SDValue Value = MS->getValue();
47650   EVT VT = Value.getValueType();
47651   EVT EltVT = VT.getVectorElementType();
47652   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
47653     EltVT = MVT::f64;
47654     EVT CastVT = VT.changeVectorElementType(EltVT);
47655     Value = DAG.getBitcast(CastVT, Value);
47656   }
47657   SDValue Extract =
47658       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Value, VecIndex);
47659 
47660   // Store that element at the appropriate offset from the base pointer.
47661   return DAG.getStore(MS->getChain(), DL, Extract, Addr,
47662                       MS->getPointerInfo().getWithOffset(Offset),
47663                       Alignment, MS->getMemOperand()->getFlags());
47664 }
47665 
47666 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
47667                                   TargetLowering::DAGCombinerInfo &DCI,
47668                                   const X86Subtarget &Subtarget) {
47669   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
47670   if (Mst->isCompressingStore())
47671     return SDValue();
47672 
47673   EVT VT = Mst->getValue().getValueType();
47674   SDLoc dl(Mst);
47675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47676 
47677   if (Mst->isTruncatingStore())
47678     return SDValue();
47679 
47680   if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG, Subtarget))
47681     return ScalarStore;
47682 
47683   // If the mask value has been legalized to a non-boolean vector, try to
47684   // simplify ops leading up to it. We only demand the MSB of each lane.
47685   SDValue Mask = Mst->getMask();
47686   if (Mask.getScalarValueSizeInBits() != 1) {
47687     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
47688     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
47689       if (N->getOpcode() != ISD::DELETED_NODE)
47690         DCI.AddToWorklist(N);
47691       return SDValue(N, 0);
47692     }
47693     if (SDValue NewMask =
47694             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
47695       return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Mst->getValue(),
47696                                 Mst->getBasePtr(), Mst->getOffset(), NewMask,
47697                                 Mst->getMemoryVT(), Mst->getMemOperand(),
47698                                 Mst->getAddressingMode());
47699   }
47700 
47701   SDValue Value = Mst->getValue();
47702   if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
47703       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
47704                             Mst->getMemoryVT())) {
47705     return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
47706                               Mst->getBasePtr(), Mst->getOffset(), Mask,
47707                               Mst->getMemoryVT(), Mst->getMemOperand(),
47708                               Mst->getAddressingMode(), true);
47709   }
47710 
47711   return SDValue();
47712 }
47713 
47714 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
47715                             TargetLowering::DAGCombinerInfo &DCI,
47716                             const X86Subtarget &Subtarget) {
47717   StoreSDNode *St = cast<StoreSDNode>(N);
47718   EVT StVT = St->getMemoryVT();
47719   SDLoc dl(St);
47720   SDValue StoredVal = St->getValue();
47721   EVT VT = StoredVal.getValueType();
47722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47723 
47724   // Convert a store of vXi1 into a store of iX and a bitcast.
47725   if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
47726       VT.getVectorElementType() == MVT::i1) {
47727 
47728     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
47729     StoredVal = DAG.getBitcast(NewVT, StoredVal);
47730 
47731     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
47732                         St->getPointerInfo(), St->getOriginalAlign(),
47733                         St->getMemOperand()->getFlags());
47734   }
47735 
47736   // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
47737   // This will avoid a copy to k-register.
47738   if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
47739       StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
47740       StoredVal.getOperand(0).getValueType() == MVT::i8) {
47741     SDValue Val = StoredVal.getOperand(0);
47742     // We must store zeros to the unused bits.
47743     Val = DAG.getZeroExtendInReg(Val, dl, MVT::i1);
47744     return DAG.getStore(St->getChain(), dl, Val,
47745                         St->getBasePtr(), St->getPointerInfo(),
47746                         St->getOriginalAlign(),
47747                         St->getMemOperand()->getFlags());
47748   }
47749 
47750   // Widen v2i1/v4i1 stores to v8i1.
47751   if ((VT == MVT::v1i1 || VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
47752       Subtarget.hasAVX512()) {
47753     unsigned NumConcats = 8 / VT.getVectorNumElements();
47754     // We must store zeros to the unused bits.
47755     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, VT));
47756     Ops[0] = StoredVal;
47757     StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
47758     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
47759                         St->getPointerInfo(), St->getOriginalAlign(),
47760                         St->getMemOperand()->getFlags());
47761   }
47762 
47763   // Turn vXi1 stores of constants into a scalar store.
47764   if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
47765        VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
47766       ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
47767     // If its a v64i1 store without 64-bit support, we need two stores.
47768     if (!DCI.isBeforeLegalize() && VT == MVT::v64i1 && !Subtarget.is64Bit()) {
47769       SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
47770                                       StoredVal->ops().slice(0, 32));
47771       Lo = combinevXi1ConstantToInteger(Lo, DAG);
47772       SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
47773                                       StoredVal->ops().slice(32, 32));
47774       Hi = combinevXi1ConstantToInteger(Hi, DAG);
47775 
47776       SDValue Ptr0 = St->getBasePtr();
47777       SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(4), dl);
47778 
47779       SDValue Ch0 =
47780           DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
47781                        St->getOriginalAlign(),
47782                        St->getMemOperand()->getFlags());
47783       SDValue Ch1 =
47784           DAG.getStore(St->getChain(), dl, Hi, Ptr1,
47785                        St->getPointerInfo().getWithOffset(4),
47786                        St->getOriginalAlign(),
47787                        St->getMemOperand()->getFlags());
47788       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
47789     }
47790 
47791     StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
47792     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
47793                         St->getPointerInfo(), St->getOriginalAlign(),
47794                         St->getMemOperand()->getFlags());
47795   }
47796 
47797   // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
47798   // Sandy Bridge, perform two 16-byte stores.
47799   bool Fast;
47800   if (VT.is256BitVector() && StVT == VT &&
47801       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
47802                              *St->getMemOperand(), &Fast) &&
47803       !Fast) {
47804     unsigned NumElems = VT.getVectorNumElements();
47805     if (NumElems < 2)
47806       return SDValue();
47807 
47808     return splitVectorStore(St, DAG);
47809   }
47810 
47811   // Split under-aligned vector non-temporal stores.
47812   if (St->isNonTemporal() && StVT == VT &&
47813       St->getAlignment() < VT.getStoreSize()) {
47814     // ZMM/YMM nt-stores - either it can be stored as a series of shorter
47815     // vectors or the legalizer can scalarize it to use MOVNTI.
47816     if (VT.is256BitVector() || VT.is512BitVector()) {
47817       unsigned NumElems = VT.getVectorNumElements();
47818       if (NumElems < 2)
47819         return SDValue();
47820       return splitVectorStore(St, DAG);
47821     }
47822 
47823     // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
47824     // to use MOVNTI.
47825     if (VT.is128BitVector() && Subtarget.hasSSE2()) {
47826       MVT NTVT = Subtarget.hasSSE4A()
47827                      ? MVT::v2f64
47828                      : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
47829       return scalarizeVectorStore(St, NTVT, DAG);
47830     }
47831   }
47832 
47833   // Try to optimize v16i16->v16i8 truncating stores when BWI is not
47834   // supported, but avx512f is by extending to v16i32 and truncating.
47835   if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
47836       St->getValue().getOpcode() == ISD::TRUNCATE &&
47837       St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
47838       TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
47839       St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
47840     SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32, St->getValue());
47841     return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
47842                              MVT::v16i8, St->getMemOperand());
47843   }
47844 
47845   // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
47846   if (!St->isTruncatingStore() && StoredVal.hasOneUse() &&
47847       (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
47848        StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
47849       TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
47850     bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
47851     return EmitTruncSStore(IsSigned, St->getChain(),
47852                            dl, StoredVal.getOperand(0), St->getBasePtr(),
47853                            VT, St->getMemOperand(), DAG);
47854   }
47855 
47856   // Try to fold a extract_element(VTRUNC) pattern into a truncating store.
47857   if (!St->isTruncatingStore() && StoredVal.hasOneUse()) {
47858     auto IsExtractedElement = [](SDValue V) {
47859       if (V.getOpcode() == ISD::TRUNCATE && V.getOperand(0).hasOneUse())
47860         V = V.getOperand(0);
47861       unsigned Opc = V.getOpcode();
47862       if (Opc == ISD::EXTRACT_VECTOR_ELT || Opc == X86ISD::PEXTRW) {
47863         if (V.getOperand(0).hasOneUse() && isNullConstant(V.getOperand(1)))
47864           return V.getOperand(0);
47865       }
47866       return SDValue();
47867     };
47868     if (SDValue Extract = IsExtractedElement(StoredVal)) {
47869       SDValue Trunc = peekThroughOneUseBitcasts(Extract);
47870       if (Trunc.getOpcode() == X86ISD::VTRUNC) {
47871         SDValue Src = Trunc.getOperand(0);
47872         MVT DstVT = Trunc.getSimpleValueType();
47873         MVT SrcVT = Src.getSimpleValueType();
47874         unsigned NumSrcElts = SrcVT.getVectorNumElements();
47875         unsigned NumTruncBits = DstVT.getScalarSizeInBits() * NumSrcElts;
47876         MVT TruncVT = MVT::getVectorVT(DstVT.getScalarType(), NumSrcElts);
47877         if (NumTruncBits == VT.getSizeInBits() &&
47878             TLI.isTruncStoreLegal(SrcVT, TruncVT)) {
47879           return DAG.getTruncStore(St->getChain(), dl, Src, St->getBasePtr(),
47880                                    TruncVT, St->getMemOperand());
47881         }
47882       }
47883     }
47884   }
47885 
47886   // Optimize trunc store (of multiple scalars) to shuffle and store.
47887   // First, pack all of the elements in one place. Next, store to memory
47888   // in fewer chunks.
47889   if (St->isTruncatingStore() && VT.isVector()) {
47890     // Check if we can detect an AVG pattern from the truncation. If yes,
47891     // replace the trunc store by a normal store with the result of X86ISD::AVG
47892     // instruction.
47893     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(St->getMemoryVT()))
47894       if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
47895                                          Subtarget, dl))
47896         return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
47897                             St->getPointerInfo(), St->getOriginalAlign(),
47898                             St->getMemOperand()->getFlags());
47899 
47900     if (TLI.isTruncStoreLegal(VT, StVT)) {
47901       if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
47902         return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
47903                                dl, Val, St->getBasePtr(),
47904                                St->getMemoryVT(), St->getMemOperand(), DAG);
47905       if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
47906                                           DAG, dl))
47907         return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
47908                                dl, Val, St->getBasePtr(),
47909                                St->getMemoryVT(), St->getMemOperand(), DAG);
47910     }
47911 
47912     return SDValue();
47913   }
47914 
47915   // Cast ptr32 and ptr64 pointers to the default address space before a store.
47916   unsigned AddrSpace = St->getAddressSpace();
47917   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
47918       AddrSpace == X86AS::PTR32_UPTR) {
47919     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
47920     if (PtrVT != St->getBasePtr().getSimpleValueType()) {
47921       SDValue Cast =
47922           DAG.getAddrSpaceCast(dl, PtrVT, St->getBasePtr(), AddrSpace, 0);
47923       return DAG.getStore(St->getChain(), dl, StoredVal, Cast,
47924                           St->getPointerInfo(), St->getOriginalAlign(),
47925                           St->getMemOperand()->getFlags(), St->getAAInfo());
47926     }
47927   }
47928 
47929   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
47930   // the FP state in cases where an emms may be missing.
47931   // A preferable solution to the general problem is to figure out the right
47932   // places to insert EMMS.  This qualifies as a quick hack.
47933 
47934   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
47935   if (VT.getSizeInBits() != 64)
47936     return SDValue();
47937 
47938   const Function &F = DAG.getMachineFunction().getFunction();
47939   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
47940   bool F64IsLegal =
47941       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
47942   if ((VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit()) &&
47943       isa<LoadSDNode>(St->getValue()) &&
47944       cast<LoadSDNode>(St->getValue())->isSimple() &&
47945       St->getChain().hasOneUse() && St->isSimple()) {
47946     LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
47947 
47948     if (!ISD::isNormalLoad(Ld))
47949       return SDValue();
47950 
47951     // Avoid the transformation if there are multiple uses of the loaded value.
47952     if (!Ld->hasNUsesOfValue(1, 0))
47953       return SDValue();
47954 
47955     SDLoc LdDL(Ld);
47956     SDLoc StDL(N);
47957     // Lower to a single movq load/store pair.
47958     SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
47959                                 Ld->getBasePtr(), Ld->getMemOperand());
47960 
47961     // Make sure new load is placed in same chain order.
47962     DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
47963     return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
47964                         St->getMemOperand());
47965   }
47966 
47967   // This is similar to the above case, but here we handle a scalar 64-bit
47968   // integer store that is extracted from a vector on a 32-bit target.
47969   // If we have SSE2, then we can treat it like a floating-point double
47970   // to get past legalization. The execution dependencies fixup pass will
47971   // choose the optimal machine instruction for the store if this really is
47972   // an integer or v2f32 rather than an f64.
47973   if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
47974       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
47975     SDValue OldExtract = St->getOperand(1);
47976     SDValue ExtOp0 = OldExtract.getOperand(0);
47977     unsigned VecSize = ExtOp0.getValueSizeInBits();
47978     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
47979     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
47980     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
47981                                      BitCast, OldExtract.getOperand(1));
47982     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
47983                         St->getPointerInfo(), St->getOriginalAlign(),
47984                         St->getMemOperand()->getFlags());
47985   }
47986 
47987   return SDValue();
47988 }
47989 
47990 static SDValue combineVEXTRACT_STORE(SDNode *N, SelectionDAG &DAG,
47991                                      TargetLowering::DAGCombinerInfo &DCI,
47992                                      const X86Subtarget &Subtarget) {
47993   auto *St = cast<MemIntrinsicSDNode>(N);
47994 
47995   SDValue StoredVal = N->getOperand(1);
47996   MVT VT = StoredVal.getSimpleValueType();
47997   EVT MemVT = St->getMemoryVT();
47998 
47999   // Figure out which elements we demand.
48000   unsigned StElts = MemVT.getSizeInBits() / VT.getScalarSizeInBits();
48001   APInt DemandedElts = APInt::getLowBitsSet(VT.getVectorNumElements(), StElts);
48002 
48003   APInt KnownUndef, KnownZero;
48004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48005   if (TLI.SimplifyDemandedVectorElts(StoredVal, DemandedElts, KnownUndef,
48006                                      KnownZero, DCI)) {
48007     if (N->getOpcode() != ISD::DELETED_NODE)
48008       DCI.AddToWorklist(N);
48009     return SDValue(N, 0);
48010   }
48011 
48012   return SDValue();
48013 }
48014 
48015 /// Return 'true' if this vector operation is "horizontal"
48016 /// and return the operands for the horizontal operation in LHS and RHS.  A
48017 /// horizontal operation performs the binary operation on successive elements
48018 /// of its first operand, then on successive elements of its second operand,
48019 /// returning the resulting values in a vector.  For example, if
48020 ///   A = < float a0, float a1, float a2, float a3 >
48021 /// and
48022 ///   B = < float b0, float b1, float b2, float b3 >
48023 /// then the result of doing a horizontal operation on A and B is
48024 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
48025 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
48026 /// A horizontal-op B, for some already available A and B, and if so then LHS is
48027 /// set to A, RHS to B, and the routine returns 'true'.
48028 static bool isHorizontalBinOp(unsigned HOpcode, SDValue &LHS, SDValue &RHS,
48029                               SelectionDAG &DAG, const X86Subtarget &Subtarget,
48030                               bool IsCommutative,
48031                               SmallVectorImpl<int> &PostShuffleMask) {
48032   // If either operand is undef, bail out. The binop should be simplified.
48033   if (LHS.isUndef() || RHS.isUndef())
48034     return false;
48035 
48036   // Look for the following pattern:
48037   //   A = < float a0, float a1, float a2, float a3 >
48038   //   B = < float b0, float b1, float b2, float b3 >
48039   // and
48040   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
48041   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
48042   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
48043   // which is A horizontal-op B.
48044 
48045   MVT VT = LHS.getSimpleValueType();
48046   assert((VT.is128BitVector() || VT.is256BitVector()) &&
48047          "Unsupported vector type for horizontal add/sub");
48048   unsigned NumElts = VT.getVectorNumElements();
48049 
48050   auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
48051                         SmallVectorImpl<int> &ShuffleMask) {
48052     bool UseSubVector = false;
48053     if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
48054         Op.getOperand(0).getValueType().is256BitVector() &&
48055         llvm::isNullConstant(Op.getOperand(1))) {
48056       Op = Op.getOperand(0);
48057       UseSubVector = true;
48058     }
48059     SmallVector<SDValue, 2> SrcOps;
48060     SmallVector<int, 16> SrcMask, ScaledMask;
48061     SDValue BC = peekThroughBitcasts(Op);
48062     if (getTargetShuffleInputs(BC, SrcOps, SrcMask, DAG) &&
48063         !isAnyZero(SrcMask) && all_of(SrcOps, [BC](SDValue Op) {
48064           return Op.getValueSizeInBits() == BC.getValueSizeInBits();
48065         })) {
48066       resolveTargetShuffleInputsAndMask(SrcOps, SrcMask);
48067       if (!UseSubVector && SrcOps.size() <= 2 &&
48068           scaleShuffleElements(SrcMask, NumElts, ScaledMask)) {
48069         N0 = SrcOps.size() > 0 ? SrcOps[0] : SDValue();
48070         N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
48071         ShuffleMask.assign(ScaledMask.begin(), ScaledMask.end());
48072       }
48073       if (UseSubVector && SrcOps.size() == 1 &&
48074           scaleShuffleElements(SrcMask, 2 * NumElts, ScaledMask)) {
48075         std::tie(N0, N1) = DAG.SplitVector(SrcOps[0], SDLoc(Op));
48076         ArrayRef<int> Mask = ArrayRef<int>(ScaledMask).slice(0, NumElts);
48077         ShuffleMask.assign(Mask.begin(), Mask.end());
48078       }
48079     }
48080   };
48081 
48082   // View LHS in the form
48083   //   LHS = VECTOR_SHUFFLE A, B, LMask
48084   // If LHS is not a shuffle, then pretend it is the identity shuffle:
48085   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
48086   // NOTE: A default initialized SDValue represents an UNDEF of type VT.
48087   SDValue A, B;
48088   SmallVector<int, 16> LMask;
48089   GetShuffle(LHS, A, B, LMask);
48090 
48091   // Likewise, view RHS in the form
48092   //   RHS = VECTOR_SHUFFLE C, D, RMask
48093   SDValue C, D;
48094   SmallVector<int, 16> RMask;
48095   GetShuffle(RHS, C, D, RMask);
48096 
48097   // At least one of the operands should be a vector shuffle.
48098   unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
48099   if (NumShuffles == 0)
48100     return false;
48101 
48102   if (LMask.empty()) {
48103     A = LHS;
48104     for (unsigned i = 0; i != NumElts; ++i)
48105       LMask.push_back(i);
48106   }
48107 
48108   if (RMask.empty()) {
48109     C = RHS;
48110     for (unsigned i = 0; i != NumElts; ++i)
48111       RMask.push_back(i);
48112   }
48113 
48114   // If we have an unary mask, ensure the other op is set to null.
48115   if (isUndefOrInRange(LMask, 0, NumElts))
48116     B = SDValue();
48117   else if (isUndefOrInRange(LMask, NumElts, NumElts * 2))
48118     A = SDValue();
48119 
48120   if (isUndefOrInRange(RMask, 0, NumElts))
48121     D = SDValue();
48122   else if (isUndefOrInRange(RMask, NumElts, NumElts * 2))
48123     C = SDValue();
48124 
48125   // If A and B occur in reverse order in RHS, then canonicalize by commuting
48126   // RHS operands and shuffle mask.
48127   if (A != C) {
48128     std::swap(C, D);
48129     ShuffleVectorSDNode::commuteMask(RMask);
48130   }
48131   // Check that the shuffles are both shuffling the same vectors.
48132   if (!(A == C && B == D))
48133     return false;
48134 
48135   PostShuffleMask.clear();
48136   PostShuffleMask.append(NumElts, SM_SentinelUndef);
48137 
48138   // LHS and RHS are now:
48139   //   LHS = shuffle A, B, LMask
48140   //   RHS = shuffle A, B, RMask
48141   // Check that the masks correspond to performing a horizontal operation.
48142   // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
48143   // so we just repeat the inner loop if this is a 256-bit op.
48144   unsigned Num128BitChunks = VT.getSizeInBits() / 128;
48145   unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
48146   unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
48147   assert((NumEltsPer128BitChunk % 2 == 0) &&
48148          "Vector type should have an even number of elements in each lane");
48149   for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
48150     for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
48151       // Ignore undefined components.
48152       int LIdx = LMask[i + j], RIdx = RMask[i + j];
48153       if (LIdx < 0 || RIdx < 0 ||
48154           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
48155           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
48156         continue;
48157 
48158       // Check that successive odd/even elements are being operated on. If not,
48159       // this is not a horizontal operation.
48160       if (!((RIdx & 1) == 1 && (LIdx + 1) == RIdx) &&
48161           !((LIdx & 1) == 1 && (RIdx + 1) == LIdx && IsCommutative))
48162         return false;
48163 
48164       // Compute the post-shuffle mask index based on where the element
48165       // is stored in the HOP result, and where it needs to be moved to.
48166       int Base = LIdx & ~1u;
48167       int Index = ((Base % NumEltsPer128BitChunk) / 2) +
48168                   ((Base % NumElts) & ~(NumEltsPer128BitChunk - 1));
48169 
48170       // The  low half of the 128-bit result must choose from A.
48171       // The high half of the 128-bit result must choose from B,
48172       // unless B is undef. In that case, we are always choosing from A.
48173       if ((B && Base >= (int)NumElts) || (!B && i >= NumEltsPer64BitChunk))
48174         Index += NumEltsPer64BitChunk;
48175       PostShuffleMask[i + j] = Index;
48176     }
48177   }
48178 
48179   SDValue NewLHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
48180   SDValue NewRHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
48181 
48182   bool IsIdentityPostShuffle =
48183       isSequentialOrUndefInRange(PostShuffleMask, 0, NumElts, 0);
48184   if (IsIdentityPostShuffle)
48185     PostShuffleMask.clear();
48186 
48187   // Avoid 128-bit multi lane shuffles if pre-AVX2 and FP (integer will split).
48188   if (!IsIdentityPostShuffle && !Subtarget.hasAVX2() && VT.isFloatingPoint() &&
48189       isMultiLaneShuffleMask(128, VT.getScalarSizeInBits(), PostShuffleMask))
48190     return false;
48191 
48192   // If the source nodes are already used in HorizOps then always accept this.
48193   // Shuffle folding should merge these back together.
48194   bool FoundHorizLHS = llvm::any_of(NewLHS->uses(), [&](SDNode *User) {
48195     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
48196   });
48197   bool FoundHorizRHS = llvm::any_of(NewRHS->uses(), [&](SDNode *User) {
48198     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
48199   });
48200   bool ForceHorizOp = FoundHorizLHS && FoundHorizRHS;
48201 
48202   // Assume a SingleSource HOP if we only shuffle one input and don't need to
48203   // shuffle the result.
48204   if (!ForceHorizOp &&
48205       !shouldUseHorizontalOp(NewLHS == NewRHS &&
48206                                  (NumShuffles < 2 || !IsIdentityPostShuffle),
48207                              DAG, Subtarget))
48208     return false;
48209 
48210   LHS = DAG.getBitcast(VT, NewLHS);
48211   RHS = DAG.getBitcast(VT, NewRHS);
48212   return true;
48213 }
48214 
48215 // Try to synthesize horizontal (f)hadd/hsub from (f)adds/subs of shuffles.
48216 static SDValue combineToHorizontalAddSub(SDNode *N, SelectionDAG &DAG,
48217                                          const X86Subtarget &Subtarget) {
48218   EVT VT = N->getValueType(0);
48219   unsigned Opcode = N->getOpcode();
48220   bool IsAdd = (Opcode == ISD::FADD) || (Opcode == ISD::ADD);
48221   SmallVector<int, 8> PostShuffleMask;
48222 
48223   switch (Opcode) {
48224   case ISD::FADD:
48225   case ISD::FSUB:
48226     if ((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
48227         (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
48228       SDValue LHS = N->getOperand(0);
48229       SDValue RHS = N->getOperand(1);
48230       auto HorizOpcode = IsAdd ? X86ISD::FHADD : X86ISD::FHSUB;
48231       if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
48232                             PostShuffleMask)) {
48233         SDValue HorizBinOp = DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
48234         if (!PostShuffleMask.empty())
48235           HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
48236                                             DAG.getUNDEF(VT), PostShuffleMask);
48237         return HorizBinOp;
48238       }
48239     }
48240     break;
48241   case ISD::ADD:
48242   case ISD::SUB:
48243     if (Subtarget.hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
48244                                  VT == MVT::v16i16 || VT == MVT::v8i32)) {
48245       SDValue LHS = N->getOperand(0);
48246       SDValue RHS = N->getOperand(1);
48247       auto HorizOpcode = IsAdd ? X86ISD::HADD : X86ISD::HSUB;
48248       if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
48249                             PostShuffleMask)) {
48250         auto HOpBuilder = [HorizOpcode](SelectionDAG &DAG, const SDLoc &DL,
48251                                         ArrayRef<SDValue> Ops) {
48252           return DAG.getNode(HorizOpcode, DL, Ops[0].getValueType(), Ops);
48253         };
48254         SDValue HorizBinOp = SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
48255                                               {LHS, RHS}, HOpBuilder);
48256         if (!PostShuffleMask.empty())
48257           HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
48258                                             DAG.getUNDEF(VT), PostShuffleMask);
48259         return HorizBinOp;
48260       }
48261     }
48262     break;
48263   }
48264 
48265   return SDValue();
48266 }
48267 
48268 //  Try to combine the following nodes
48269 //  t29: i64 = X86ISD::Wrapper TargetConstantPool:i64
48270 //    <i32 -2147483648[float -0.000000e+00]> 0
48271 //  t27: v16i32[v16f32],ch = X86ISD::VBROADCAST_LOAD
48272 //    <(load 4 from constant-pool)> t0, t29
48273 //  [t30: v16i32 = bitcast t27]
48274 //  t6: v16i32 = xor t7, t27[t30]
48275 //  t11: v16f32 = bitcast t6
48276 //  t21: v16f32 = X86ISD::VFMULC[X86ISD::VCFMULC] t11, t8
48277 //  into X86ISD::VFCMULC[X86ISD::VFMULC] if possible:
48278 //  t22: v16f32 = bitcast t7
48279 //  t23: v16f32 = X86ISD::VFCMULC[X86ISD::VFMULC] t8, t22
48280 //  t24: v32f16 = bitcast t23
48281 static SDValue combineFMulcFCMulc(SDNode *N, SelectionDAG &DAG,
48282                                   const X86Subtarget &Subtarget) {
48283   EVT VT = N->getValueType(0);
48284   SDValue LHS = N->getOperand(0);
48285   SDValue RHS = N->getOperand(1);
48286   int CombineOpcode =
48287       N->getOpcode() == X86ISD::VFCMULC ? X86ISD::VFMULC : X86ISD::VFCMULC;
48288   auto isConjugationConstant = [](const Constant *c) {
48289     if (const auto *CI = dyn_cast<ConstantInt>(c)) {
48290       APInt ConjugationInt32 = APInt(32, 0x80000000, true);
48291       APInt ConjugationInt64 = APInt(64, 0x8000000080000000ULL, true);
48292       switch (CI->getBitWidth()) {
48293       case 16:
48294         return false;
48295       case 32:
48296         return CI->getValue() == ConjugationInt32;
48297       case 64:
48298         return CI->getValue() == ConjugationInt64;
48299       default:
48300         llvm_unreachable("Unexpected bit width");
48301       }
48302     }
48303     if (const auto *CF = dyn_cast<ConstantFP>(c))
48304       return CF->isNegativeZeroValue();
48305     return false;
48306   };
48307   auto combineConjugation = [&](SDValue &r) {
48308     if (LHS->getOpcode() == ISD::BITCAST && RHS.hasOneUse()) {
48309       SDValue XOR = LHS.getOperand(0);
48310       if (XOR->getOpcode() == ISD::XOR && XOR.hasOneUse()) {
48311         SDValue XORRHS = XOR.getOperand(1);
48312         if (XORRHS.getOpcode() == ISD::BITCAST && XORRHS.hasOneUse())
48313           XORRHS = XORRHS.getOperand(0);
48314         if (XORRHS.getOpcode() == X86ISD::VBROADCAST_LOAD &&
48315             XORRHS.getOperand(1).getNumOperands()) {
48316           ConstantPoolSDNode *CP =
48317               dyn_cast<ConstantPoolSDNode>(XORRHS.getOperand(1).getOperand(0));
48318           if (CP && isConjugationConstant(CP->getConstVal())) {
48319             SelectionDAG::FlagInserter FlagsInserter(DAG, N);
48320             SDValue I2F = DAG.getBitcast(VT, LHS.getOperand(0).getOperand(0));
48321             SDValue FCMulC = DAG.getNode(CombineOpcode, SDLoc(N), VT, RHS, I2F);
48322             r = DAG.getBitcast(VT, FCMulC);
48323             return true;
48324           }
48325         }
48326       }
48327     }
48328     return false;
48329   };
48330   SDValue Res;
48331   if (combineConjugation(Res))
48332     return Res;
48333   std::swap(LHS, RHS);
48334   if (combineConjugation(Res))
48335     return Res;
48336   return Res;
48337 }
48338 
48339 //  Try to combine the following nodes:
48340 //  FADD(A, FMA(B, C, 0)) and FADD(A, FMUL(B, C)) to FMA(B, C, A)
48341 static SDValue combineFaddCFmul(SDNode *N, SelectionDAG &DAG,
48342                                 const X86Subtarget &Subtarget) {
48343   auto AllowContract = [&DAG](const SDNodeFlags &Flags) {
48344     return DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
48345            Flags.hasAllowContract();
48346   };
48347 
48348   auto HasNoSignedZero = [&DAG](const SDNodeFlags &Flags) {
48349     return DAG.getTarget().Options.NoSignedZerosFPMath ||
48350            Flags.hasNoSignedZeros();
48351   };
48352   auto IsVectorAllNegativeZero = [](const SDNode *N) {
48353     if (N->getOpcode() != X86ISD::VBROADCAST_LOAD)
48354       return false;
48355     assert(N->getSimpleValueType(0).getScalarType() == MVT::f32 &&
48356            "Unexpected vector type!");
48357     if (ConstantPoolSDNode *CP =
48358             dyn_cast<ConstantPoolSDNode>(N->getOperand(1)->getOperand(0))) {
48359       APInt AI = APInt(32, 0x80008000, true);
48360       if (const auto *CI = dyn_cast<ConstantInt>(CP->getConstVal()))
48361         return CI->getValue() == AI;
48362       if (const auto *CF = dyn_cast<ConstantFP>(CP->getConstVal()))
48363         return CF->getValue() == APFloat(APFloat::IEEEsingle(), AI);
48364     }
48365     return false;
48366   };
48367 
48368   if (N->getOpcode() != ISD::FADD || !Subtarget.hasFP16() ||
48369       !AllowContract(N->getFlags()))
48370     return SDValue();
48371 
48372   EVT VT = N->getValueType(0);
48373   if (VT != MVT::v8f16 && VT != MVT::v16f16 && VT != MVT::v32f16)
48374     return SDValue();
48375 
48376   SDValue LHS = N->getOperand(0);
48377   SDValue RHS = N->getOperand(1);
48378   bool IsConj;
48379   SDValue FAddOp1, MulOp0, MulOp1;
48380   auto GetCFmulFrom = [&MulOp0, &MulOp1, &IsConj, &AllowContract,
48381                        &IsVectorAllNegativeZero,
48382                        &HasNoSignedZero](SDValue N) -> bool {
48383     if (!N.hasOneUse() || N.getOpcode() != ISD::BITCAST)
48384       return false;
48385     SDValue Op0 = N.getOperand(0);
48386     unsigned Opcode = Op0.getOpcode();
48387     if (Op0.hasOneUse() && AllowContract(Op0->getFlags())) {
48388       if ((Opcode == X86ISD::VFMULC || Opcode == X86ISD::VFCMULC)) {
48389         MulOp0 = Op0.getOperand(0);
48390         MulOp1 = Op0.getOperand(1);
48391         IsConj = Opcode == X86ISD::VFCMULC;
48392         return true;
48393       }
48394       if ((Opcode == X86ISD::VFMADDC || Opcode == X86ISD::VFCMADDC) &&
48395           ((ISD::isBuildVectorAllZeros(Op0->getOperand(2).getNode()) &&
48396             HasNoSignedZero(Op0->getFlags())) ||
48397            IsVectorAllNegativeZero(Op0->getOperand(2).getNode()))) {
48398         MulOp0 = Op0.getOperand(0);
48399         MulOp1 = Op0.getOperand(1);
48400         IsConj = Opcode == X86ISD::VFCMADDC;
48401         return true;
48402       }
48403     }
48404     return false;
48405   };
48406 
48407   if (GetCFmulFrom(LHS))
48408     FAddOp1 = RHS;
48409   else if (GetCFmulFrom(RHS))
48410     FAddOp1 = LHS;
48411   else
48412     return SDValue();
48413 
48414   MVT CVT = MVT::getVectorVT(MVT::f32, VT.getVectorNumElements() / 2);
48415   FAddOp1 = DAG.getBitcast(CVT, FAddOp1);
48416   unsigned NewOp = IsConj ? X86ISD::VFCMADDC : X86ISD::VFMADDC;
48417   // FIXME: How do we handle when fast math flags of FADD are different from
48418   // CFMUL's?
48419   SDValue CFmul =
48420       DAG.getNode(NewOp, SDLoc(N), CVT, MulOp0, MulOp1, FAddOp1, N->getFlags());
48421   return DAG.getBitcast(VT, CFmul);
48422 }
48423 
48424 /// Do target-specific dag combines on floating-point adds/subs.
48425 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
48426                                const X86Subtarget &Subtarget) {
48427   if (SDValue HOp = combineToHorizontalAddSub(N, DAG, Subtarget))
48428     return HOp;
48429 
48430   if (SDValue COp = combineFaddCFmul(N, DAG, Subtarget))
48431     return COp;
48432 
48433   return SDValue();
48434 }
48435 
48436 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
48437 /// the codegen.
48438 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
48439 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
48440 ///       anything that is guaranteed to be transformed by DAGCombiner.
48441 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
48442                                           const X86Subtarget &Subtarget,
48443                                           const SDLoc &DL) {
48444   assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
48445   SDValue Src = N->getOperand(0);
48446   unsigned SrcOpcode = Src.getOpcode();
48447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48448 
48449   EVT VT = N->getValueType(0);
48450   EVT SrcVT = Src.getValueType();
48451 
48452   auto IsFreeTruncation = [VT](SDValue Op) {
48453     unsigned TruncSizeInBits = VT.getScalarSizeInBits();
48454 
48455     // See if this has been extended from a smaller/equal size to
48456     // the truncation size, allowing a truncation to combine with the extend.
48457     unsigned Opcode = Op.getOpcode();
48458     if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
48459          Opcode == ISD::ZERO_EXTEND) &&
48460         Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
48461       return true;
48462 
48463     // See if this is a single use constant which can be constant folded.
48464     // NOTE: We don't peek throught bitcasts here because there is currently
48465     // no support for constant folding truncate+bitcast+vector_of_constants. So
48466     // we'll just send up with a truncate on both operands which will
48467     // get turned back into (truncate (binop)) causing an infinite loop.
48468     return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
48469   };
48470 
48471   auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
48472     SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
48473     SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
48474     return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
48475   };
48476 
48477   // Don't combine if the operation has other uses.
48478   if (!Src.hasOneUse())
48479     return SDValue();
48480 
48481   // Only support vector truncation for now.
48482   // TODO: i64 scalar math would benefit as well.
48483   if (!VT.isVector())
48484     return SDValue();
48485 
48486   // In most cases its only worth pre-truncating if we're only facing the cost
48487   // of one truncation.
48488   // i.e. if one of the inputs will constant fold or the input is repeated.
48489   switch (SrcOpcode) {
48490   case ISD::MUL:
48491     // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
48492     // better to truncate if we have the chance.
48493     if (SrcVT.getScalarType() == MVT::i64 &&
48494         TLI.isOperationLegal(SrcOpcode, VT) &&
48495         !TLI.isOperationLegal(SrcOpcode, SrcVT))
48496       return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
48497     LLVM_FALLTHROUGH;
48498   case ISD::AND:
48499   case ISD::XOR:
48500   case ISD::OR:
48501   case ISD::ADD:
48502   case ISD::SUB: {
48503     SDValue Op0 = Src.getOperand(0);
48504     SDValue Op1 = Src.getOperand(1);
48505     if (TLI.isOperationLegal(SrcOpcode, VT) &&
48506         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
48507       return TruncateArithmetic(Op0, Op1);
48508     break;
48509   }
48510   }
48511 
48512   return SDValue();
48513 }
48514 
48515 /// Truncate using ISD::AND mask and X86ISD::PACKUS.
48516 /// e.g. trunc <8 x i32> X to <8 x i16> -->
48517 /// MaskX = X & 0xffff (clear high bits to prevent saturation)
48518 /// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
48519 static SDValue combineVectorTruncationWithPACKUS(SDNode *N, const SDLoc &DL,
48520                                                  const X86Subtarget &Subtarget,
48521                                                  SelectionDAG &DAG) {
48522   SDValue In = N->getOperand(0);
48523   EVT InVT = In.getValueType();
48524   EVT OutVT = N->getValueType(0);
48525 
48526   APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(),
48527                                     OutVT.getScalarSizeInBits());
48528   In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT));
48529   return truncateVectorWithPACK(X86ISD::PACKUS, OutVT, In, DL, DAG, Subtarget);
48530 }
48531 
48532 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
48533 static SDValue combineVectorTruncationWithPACKSS(SDNode *N, const SDLoc &DL,
48534                                                  const X86Subtarget &Subtarget,
48535                                                  SelectionDAG &DAG) {
48536   SDValue In = N->getOperand(0);
48537   EVT InVT = In.getValueType();
48538   EVT OutVT = N->getValueType(0);
48539   In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InVT, In,
48540                    DAG.getValueType(OutVT));
48541   return truncateVectorWithPACK(X86ISD::PACKSS, OutVT, In, DL, DAG, Subtarget);
48542 }
48543 
48544 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
48545 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
48546 /// legalization the truncation will be translated into a BUILD_VECTOR with each
48547 /// element that is extracted from a vector and then truncated, and it is
48548 /// difficult to do this optimization based on them.
48549 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
48550                                        const X86Subtarget &Subtarget) {
48551   EVT OutVT = N->getValueType(0);
48552   if (!OutVT.isVector())
48553     return SDValue();
48554 
48555   SDValue In = N->getOperand(0);
48556   if (!In.getValueType().isSimple())
48557     return SDValue();
48558 
48559   EVT InVT = In.getValueType();
48560   unsigned NumElems = OutVT.getVectorNumElements();
48561 
48562   // AVX512 provides fast truncate ops.
48563   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
48564     return SDValue();
48565 
48566   EVT OutSVT = OutVT.getVectorElementType();
48567   EVT InSVT = InVT.getVectorElementType();
48568   if (!((InSVT == MVT::i16 || InSVT == MVT::i32 || InSVT == MVT::i64) &&
48569         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
48570         NumElems >= 8))
48571     return SDValue();
48572 
48573   // SSSE3's pshufb results in less instructions in the cases below.
48574   if (Subtarget.hasSSSE3() && NumElems == 8 && InSVT != MVT::i64)
48575     return SDValue();
48576 
48577   SDLoc DL(N);
48578   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
48579   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
48580   // truncate 2 x v4i32 to v8i16.
48581   if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
48582     return combineVectorTruncationWithPACKUS(N, DL, Subtarget, DAG);
48583   if (InSVT == MVT::i32)
48584     return combineVectorTruncationWithPACKSS(N, DL, Subtarget, DAG);
48585 
48586   return SDValue();
48587 }
48588 
48589 /// This function transforms vector truncation of 'extended sign-bits' or
48590 /// 'extended zero-bits' values.
48591 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
48592 static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
48593                                                SelectionDAG &DAG,
48594                                                const X86Subtarget &Subtarget) {
48595   // Requires SSE2.
48596   if (!Subtarget.hasSSE2())
48597     return SDValue();
48598 
48599   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
48600     return SDValue();
48601 
48602   SDValue In = N->getOperand(0);
48603   if (!In.getValueType().isSimple())
48604     return SDValue();
48605 
48606   MVT VT = N->getValueType(0).getSimpleVT();
48607   MVT SVT = VT.getScalarType();
48608 
48609   MVT InVT = In.getValueType().getSimpleVT();
48610   MVT InSVT = InVT.getScalarType();
48611 
48612   // Check we have a truncation suited for PACKSS/PACKUS.
48613   if (!isPowerOf2_32(VT.getVectorNumElements()))
48614     return SDValue();
48615   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
48616     return SDValue();
48617   if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
48618     return SDValue();
48619 
48620   // Truncation to sub-128bit vXi32 can be better handled with shuffles.
48621   if (SVT == MVT::i32 && VT.getSizeInBits() < 128)
48622     return SDValue();
48623 
48624   // AVX512 has fast truncate, but if the input is already going to be split,
48625   // there's no harm in trying pack.
48626   if (Subtarget.hasAVX512() &&
48627       !(!Subtarget.useAVX512Regs() && VT.is256BitVector() &&
48628         InVT.is512BitVector())) {
48629     // PACK should still be worth it for 128-bit vectors if the sources were
48630     // originally concatenated from subvectors.
48631     SmallVector<SDValue> ConcatOps;
48632     if (VT.getSizeInBits() > 128 || !collectConcatOps(In.getNode(), ConcatOps))
48633     return SDValue();
48634   }
48635 
48636   unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
48637   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
48638 
48639   // Use PACKUS if the input has zero-bits that extend all the way to the
48640   // packed/truncated value. e.g. masks, zext_in_reg, etc.
48641   KnownBits Known = DAG.computeKnownBits(In);
48642   unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
48643   if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
48644     return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
48645 
48646   // Use PACKSS if the input has sign-bits that extend all the way to the
48647   // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
48648   unsigned NumSignBits = DAG.ComputeNumSignBits(In);
48649 
48650   // Don't use PACKSS for vXi64 -> vXi32 truncations unless we're dealing with
48651   // a sign splat. ComputeNumSignBits struggles to see through BITCASTs later
48652   // on and combines/simplifications can't then use it.
48653   if (SVT == MVT::i32 && NumSignBits != InSVT.getSizeInBits())
48654     return SDValue();
48655 
48656   unsigned MinSignBits = InSVT.getSizeInBits() - NumPackedSignBits;
48657   if (NumSignBits > MinSignBits)
48658     return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
48659 
48660   // If we have a srl that only generates signbits that we will discard in
48661   // the truncation then we can use PACKSS by converting the srl to a sra.
48662   // SimplifyDemandedBits often relaxes sra to srl so we need to reverse it.
48663   if (In.getOpcode() == ISD::SRL && N->isOnlyUserOf(In.getNode()))
48664     if (const APInt *ShAmt = DAG.getValidShiftAmountConstant(
48665             In, APInt::getAllOnes(VT.getVectorNumElements()))) {
48666       if (*ShAmt == MinSignBits) {
48667         SDValue NewIn = DAG.getNode(ISD::SRA, DL, InVT, In->ops());
48668         return truncateVectorWithPACK(X86ISD::PACKSS, VT, NewIn, DL, DAG,
48669                                       Subtarget);
48670       }
48671     }
48672 
48673   return SDValue();
48674 }
48675 
48676 // Try to form a MULHU or MULHS node by looking for
48677 // (trunc (srl (mul ext, ext), 16))
48678 // TODO: This is X86 specific because we want to be able to handle wide types
48679 // before type legalization. But we can only do it if the vector will be
48680 // legalized via widening/splitting. Type legalization can't handle promotion
48681 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
48682 // combiner.
48683 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
48684                             SelectionDAG &DAG, const X86Subtarget &Subtarget) {
48685   // First instruction should be a right shift of a multiply.
48686   if (Src.getOpcode() != ISD::SRL ||
48687       Src.getOperand(0).getOpcode() != ISD::MUL)
48688     return SDValue();
48689 
48690   if (!Subtarget.hasSSE2())
48691     return SDValue();
48692 
48693   // Only handle vXi16 types that are at least 128-bits unless they will be
48694   // widened.
48695   if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
48696     return SDValue();
48697 
48698   // Input type should be at least vXi32.
48699   EVT InVT = Src.getValueType();
48700   if (InVT.getVectorElementType().getSizeInBits() < 32)
48701     return SDValue();
48702 
48703   // Need a shift by 16.
48704   APInt ShiftAmt;
48705   if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
48706       ShiftAmt != 16)
48707     return SDValue();
48708 
48709   SDValue LHS = Src.getOperand(0).getOperand(0);
48710   SDValue RHS = Src.getOperand(0).getOperand(1);
48711 
48712   // Count leading sign/zero bits on both inputs - if there are enough then
48713   // truncation back to vXi16 will be cheap - either as a pack/shuffle
48714   // sequence or using AVX512 truncations. If the inputs are sext/zext then the
48715   // truncations may actually be free by peeking through to the ext source.
48716   auto IsSext = [&DAG](SDValue V) {
48717     return DAG.ComputeMinSignedBits(V) <= 16;
48718   };
48719   auto IsZext = [&DAG](SDValue V) {
48720     return DAG.computeKnownBits(V).countMaxActiveBits() <= 16;
48721   };
48722 
48723   bool IsSigned = IsSext(LHS) && IsSext(RHS);
48724   bool IsUnsigned = IsZext(LHS) && IsZext(RHS);
48725   if (!IsSigned && !IsUnsigned)
48726     return SDValue();
48727 
48728   // Check if both inputs are extensions, which will be removed by truncation.
48729   bool IsTruncateFree = (LHS.getOpcode() == ISD::SIGN_EXTEND ||
48730                          LHS.getOpcode() == ISD::ZERO_EXTEND) &&
48731                         (RHS.getOpcode() == ISD::SIGN_EXTEND ||
48732                          RHS.getOpcode() == ISD::ZERO_EXTEND) &&
48733                         LHS.getOperand(0).getScalarValueSizeInBits() <= 16 &&
48734                         RHS.getOperand(0).getScalarValueSizeInBits() <= 16;
48735 
48736   // For AVX2+ targets, with the upper bits known zero, we can perform MULHU on
48737   // the (bitcasted) inputs directly, and then cheaply pack/truncate the result
48738   // (upper elts will be zero). Don't attempt this with just AVX512F as MULHU
48739   // will have to split anyway.
48740   unsigned InSizeInBits = InVT.getSizeInBits();
48741   if (IsUnsigned && !IsTruncateFree && Subtarget.hasInt256() &&
48742       !(Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.is256BitVector()) &&
48743       (InSizeInBits % 16) == 0) {
48744     EVT BCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
48745                                 InVT.getSizeInBits() / 16);
48746     SDValue Res = DAG.getNode(ISD::MULHU, DL, BCVT, DAG.getBitcast(BCVT, LHS),
48747                               DAG.getBitcast(BCVT, RHS));
48748     return DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getBitcast(InVT, Res));
48749   }
48750 
48751   // Truncate back to source type.
48752   LHS = DAG.getNode(ISD::TRUNCATE, DL, VT, LHS);
48753   RHS = DAG.getNode(ISD::TRUNCATE, DL, VT, RHS);
48754 
48755   unsigned Opc = IsSigned ? ISD::MULHS : ISD::MULHU;
48756   return DAG.getNode(Opc, DL, VT, LHS, RHS);
48757 }
48758 
48759 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
48760 // from one vector with signed bytes from another vector, adds together
48761 // adjacent pairs of 16-bit products, and saturates the result before
48762 // truncating to 16-bits.
48763 //
48764 // Which looks something like this:
48765 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
48766 //                 (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
48767 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
48768                                const X86Subtarget &Subtarget,
48769                                const SDLoc &DL) {
48770   if (!VT.isVector() || !Subtarget.hasSSSE3())
48771     return SDValue();
48772 
48773   unsigned NumElems = VT.getVectorNumElements();
48774   EVT ScalarVT = VT.getVectorElementType();
48775   if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
48776     return SDValue();
48777 
48778   SDValue SSatVal = detectSSatPattern(In, VT);
48779   if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
48780     return SDValue();
48781 
48782   // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
48783   // of multiplies from even/odd elements.
48784   SDValue N0 = SSatVal.getOperand(0);
48785   SDValue N1 = SSatVal.getOperand(1);
48786 
48787   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
48788     return SDValue();
48789 
48790   SDValue N00 = N0.getOperand(0);
48791   SDValue N01 = N0.getOperand(1);
48792   SDValue N10 = N1.getOperand(0);
48793   SDValue N11 = N1.getOperand(1);
48794 
48795   // TODO: Handle constant vectors and use knownbits/computenumsignbits?
48796   // Canonicalize zero_extend to LHS.
48797   if (N01.getOpcode() == ISD::ZERO_EXTEND)
48798     std::swap(N00, N01);
48799   if (N11.getOpcode() == ISD::ZERO_EXTEND)
48800     std::swap(N10, N11);
48801 
48802   // Ensure we have a zero_extend and a sign_extend.
48803   if (N00.getOpcode() != ISD::ZERO_EXTEND ||
48804       N01.getOpcode() != ISD::SIGN_EXTEND ||
48805       N10.getOpcode() != ISD::ZERO_EXTEND ||
48806       N11.getOpcode() != ISD::SIGN_EXTEND)
48807     return SDValue();
48808 
48809   // Peek through the extends.
48810   N00 = N00.getOperand(0);
48811   N01 = N01.getOperand(0);
48812   N10 = N10.getOperand(0);
48813   N11 = N11.getOperand(0);
48814 
48815   // Ensure the extend is from vXi8.
48816   if (N00.getValueType().getVectorElementType() != MVT::i8 ||
48817       N01.getValueType().getVectorElementType() != MVT::i8 ||
48818       N10.getValueType().getVectorElementType() != MVT::i8 ||
48819       N11.getValueType().getVectorElementType() != MVT::i8)
48820     return SDValue();
48821 
48822   // All inputs should be build_vectors.
48823   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
48824       N01.getOpcode() != ISD::BUILD_VECTOR ||
48825       N10.getOpcode() != ISD::BUILD_VECTOR ||
48826       N11.getOpcode() != ISD::BUILD_VECTOR)
48827     return SDValue();
48828 
48829   // N00/N10 are zero extended. N01/N11 are sign extended.
48830 
48831   // For each element, we need to ensure we have an odd element from one vector
48832   // multiplied by the odd element of another vector and the even element from
48833   // one of the same vectors being multiplied by the even element from the
48834   // other vector. So we need to make sure for each element i, this operator
48835   // is being performed:
48836   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
48837   SDValue ZExtIn, SExtIn;
48838   for (unsigned i = 0; i != NumElems; ++i) {
48839     SDValue N00Elt = N00.getOperand(i);
48840     SDValue N01Elt = N01.getOperand(i);
48841     SDValue N10Elt = N10.getOperand(i);
48842     SDValue N11Elt = N11.getOperand(i);
48843     // TODO: Be more tolerant to undefs.
48844     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48845         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48846         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48847         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
48848       return SDValue();
48849     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
48850     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
48851     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
48852     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
48853     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
48854       return SDValue();
48855     unsigned IdxN00 = ConstN00Elt->getZExtValue();
48856     unsigned IdxN01 = ConstN01Elt->getZExtValue();
48857     unsigned IdxN10 = ConstN10Elt->getZExtValue();
48858     unsigned IdxN11 = ConstN11Elt->getZExtValue();
48859     // Add is commutative so indices can be reordered.
48860     if (IdxN00 > IdxN10) {
48861       std::swap(IdxN00, IdxN10);
48862       std::swap(IdxN01, IdxN11);
48863     }
48864     // N0 indices be the even element. N1 indices must be the next odd element.
48865     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
48866         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
48867       return SDValue();
48868     SDValue N00In = N00Elt.getOperand(0);
48869     SDValue N01In = N01Elt.getOperand(0);
48870     SDValue N10In = N10Elt.getOperand(0);
48871     SDValue N11In = N11Elt.getOperand(0);
48872     // First time we find an input capture it.
48873     if (!ZExtIn) {
48874       ZExtIn = N00In;
48875       SExtIn = N01In;
48876     }
48877     if (ZExtIn != N00In || SExtIn != N01In ||
48878         ZExtIn != N10In || SExtIn != N11In)
48879       return SDValue();
48880   }
48881 
48882   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
48883                          ArrayRef<SDValue> Ops) {
48884     // Shrink by adding truncate nodes and let DAGCombine fold with the
48885     // sources.
48886     EVT InVT = Ops[0].getValueType();
48887     assert(InVT.getScalarType() == MVT::i8 &&
48888            "Unexpected scalar element type");
48889     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
48890     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
48891                                  InVT.getVectorNumElements() / 2);
48892     return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
48893   };
48894   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
48895                           PMADDBuilder);
48896 }
48897 
48898 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
48899                                const X86Subtarget &Subtarget) {
48900   EVT VT = N->getValueType(0);
48901   SDValue Src = N->getOperand(0);
48902   SDLoc DL(N);
48903 
48904   // Attempt to pre-truncate inputs to arithmetic ops instead.
48905   if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
48906     return V;
48907 
48908   // Try to detect AVG pattern first.
48909   if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
48910     return Avg;
48911 
48912   // Try to detect PMADD
48913   if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
48914     return PMAdd;
48915 
48916   // Try to combine truncation with signed/unsigned saturation.
48917   if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
48918     return Val;
48919 
48920   // Try to combine PMULHUW/PMULHW for vXi16.
48921   if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
48922     return V;
48923 
48924   // The bitcast source is a direct mmx result.
48925   // Detect bitcasts between i32 to x86mmx
48926   if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
48927     SDValue BCSrc = Src.getOperand(0);
48928     if (BCSrc.getValueType() == MVT::x86mmx)
48929       return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
48930   }
48931 
48932   // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
48933   if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
48934     return V;
48935 
48936   return combineVectorTruncation(N, DAG, Subtarget);
48937 }
48938 
48939 static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG,
48940                              TargetLowering::DAGCombinerInfo &DCI) {
48941   EVT VT = N->getValueType(0);
48942   SDValue In = N->getOperand(0);
48943   SDLoc DL(N);
48944 
48945   if (auto SSatVal = detectSSatPattern(In, VT))
48946     return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
48947   if (auto USatVal = detectUSatPattern(In, VT, DAG, DL))
48948     return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
48949 
48950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48951   APInt DemandedMask(APInt::getAllOnes(VT.getScalarSizeInBits()));
48952   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
48953     return SDValue(N, 0);
48954 
48955   return SDValue();
48956 }
48957 
48958 /// Returns the negated value if the node \p N flips sign of FP value.
48959 ///
48960 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
48961 /// or FSUB(0, x)
48962 /// AVX512F does not have FXOR, so FNEG is lowered as
48963 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
48964 /// In this case we go though all bitcasts.
48965 /// This also recognizes splat of a negated value and returns the splat of that
48966 /// value.
48967 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
48968   if (N->getOpcode() == ISD::FNEG)
48969     return N->getOperand(0);
48970 
48971   // Don't recurse exponentially.
48972   if (Depth > SelectionDAG::MaxRecursionDepth)
48973     return SDValue();
48974 
48975   unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
48976 
48977   SDValue Op = peekThroughBitcasts(SDValue(N, 0));
48978   EVT VT = Op->getValueType(0);
48979 
48980   // Make sure the element size doesn't change.
48981   if (VT.getScalarSizeInBits() != ScalarSize)
48982     return SDValue();
48983 
48984   unsigned Opc = Op.getOpcode();
48985   switch (Opc) {
48986   case ISD::VECTOR_SHUFFLE: {
48987     // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
48988     // of this is VECTOR_SHUFFLE(-VEC1, UNDEF).  The mask can be anything here.
48989     if (!Op.getOperand(1).isUndef())
48990       return SDValue();
48991     if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
48992       if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
48993         return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
48994                                     cast<ShuffleVectorSDNode>(Op)->getMask());
48995     break;
48996   }
48997   case ISD::INSERT_VECTOR_ELT: {
48998     // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
48999     // -V, INDEX).
49000     SDValue InsVector = Op.getOperand(0);
49001     SDValue InsVal = Op.getOperand(1);
49002     if (!InsVector.isUndef())
49003       return SDValue();
49004     if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
49005       if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
49006         return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
49007                            NegInsVal, Op.getOperand(2));
49008     break;
49009   }
49010   case ISD::FSUB:
49011   case ISD::XOR:
49012   case X86ISD::FXOR: {
49013     SDValue Op1 = Op.getOperand(1);
49014     SDValue Op0 = Op.getOperand(0);
49015 
49016     // For XOR and FXOR, we want to check if constant
49017     // bits of Op1 are sign bit masks. For FSUB, we
49018     // have to check if constant bits of Op0 are sign
49019     // bit masks and hence we swap the operands.
49020     if (Opc == ISD::FSUB)
49021       std::swap(Op0, Op1);
49022 
49023     APInt UndefElts;
49024     SmallVector<APInt, 16> EltBits;
49025     // Extract constant bits and see if they are all
49026     // sign bit masks. Ignore the undef elements.
49027     if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
49028                                       /* AllowWholeUndefs */ true,
49029                                       /* AllowPartialUndefs */ false)) {
49030       for (unsigned I = 0, E = EltBits.size(); I < E; I++)
49031         if (!UndefElts[I] && !EltBits[I].isSignMask())
49032           return SDValue();
49033 
49034       return peekThroughBitcasts(Op0);
49035     }
49036   }
49037   }
49038 
49039   return SDValue();
49040 }
49041 
49042 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
49043                                 bool NegRes) {
49044   if (NegMul) {
49045     switch (Opcode) {
49046     default: llvm_unreachable("Unexpected opcode");
49047     case ISD::FMA:              Opcode = X86ISD::FNMADD;        break;
49048     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FNMADD; break;
49049     case X86ISD::FMADD_RND:     Opcode = X86ISD::FNMADD_RND;    break;
49050     case X86ISD::FMSUB:         Opcode = X86ISD::FNMSUB;        break;
49051     case X86ISD::STRICT_FMSUB:  Opcode = X86ISD::STRICT_FNMSUB; break;
49052     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FNMSUB_RND;    break;
49053     case X86ISD::FNMADD:        Opcode = ISD::FMA;              break;
49054     case X86ISD::STRICT_FNMADD: Opcode = ISD::STRICT_FMA;       break;
49055     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FMADD_RND;     break;
49056     case X86ISD::FNMSUB:        Opcode = X86ISD::FMSUB;         break;
49057     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FMSUB;  break;
49058     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FMSUB_RND;     break;
49059     }
49060   }
49061 
49062   if (NegAcc) {
49063     switch (Opcode) {
49064     default: llvm_unreachable("Unexpected opcode");
49065     case ISD::FMA:              Opcode = X86ISD::FMSUB;         break;
49066     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FMSUB;  break;
49067     case X86ISD::FMADD_RND:     Opcode = X86ISD::FMSUB_RND;     break;
49068     case X86ISD::FMSUB:         Opcode = ISD::FMA;              break;
49069     case X86ISD::STRICT_FMSUB:  Opcode = ISD::STRICT_FMA;       break;
49070     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FMADD_RND;     break;
49071     case X86ISD::FNMADD:        Opcode = X86ISD::FNMSUB;        break;
49072     case X86ISD::STRICT_FNMADD: Opcode = X86ISD::STRICT_FNMSUB; break;
49073     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FNMSUB_RND;    break;
49074     case X86ISD::FNMSUB:        Opcode = X86ISD::FNMADD;        break;
49075     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FNMADD; break;
49076     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FNMADD_RND;    break;
49077     case X86ISD::FMADDSUB:      Opcode = X86ISD::FMSUBADD;      break;
49078     case X86ISD::FMADDSUB_RND:  Opcode = X86ISD::FMSUBADD_RND;  break;
49079     case X86ISD::FMSUBADD:      Opcode = X86ISD::FMADDSUB;      break;
49080     case X86ISD::FMSUBADD_RND:  Opcode = X86ISD::FMADDSUB_RND;  break;
49081     }
49082   }
49083 
49084   if (NegRes) {
49085     switch (Opcode) {
49086     // For accuracy reason, we never combine fneg and fma under strict FP.
49087     default: llvm_unreachable("Unexpected opcode");
49088     case ISD::FMA:             Opcode = X86ISD::FNMSUB;       break;
49089     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
49090     case X86ISD::FMSUB:        Opcode = X86ISD::FNMADD;       break;
49091     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMADD_RND;   break;
49092     case X86ISD::FNMADD:       Opcode = X86ISD::FMSUB;        break;
49093     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMSUB_RND;    break;
49094     case X86ISD::FNMSUB:       Opcode = ISD::FMA;             break;
49095     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMADD_RND;    break;
49096     }
49097   }
49098 
49099   return Opcode;
49100 }
49101 
49102 /// Do target-specific dag combines on floating point negations.
49103 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
49104                            TargetLowering::DAGCombinerInfo &DCI,
49105                            const X86Subtarget &Subtarget) {
49106   EVT OrigVT = N->getValueType(0);
49107   SDValue Arg = isFNEG(DAG, N);
49108   if (!Arg)
49109     return SDValue();
49110 
49111   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49112   EVT VT = Arg.getValueType();
49113   EVT SVT = VT.getScalarType();
49114   SDLoc DL(N);
49115 
49116   // Let legalize expand this if it isn't a legal type yet.
49117   if (!TLI.isTypeLegal(VT))
49118     return SDValue();
49119 
49120   // If we're negating a FMUL node on a target with FMA, then we can avoid the
49121   // use of a constant by performing (-0 - A*B) instead.
49122   // FIXME: Check rounding control flags as well once it becomes available.
49123   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
49124       Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
49125     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
49126     SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
49127                                   Arg.getOperand(1), Zero);
49128     return DAG.getBitcast(OrigVT, NewNode);
49129   }
49130 
49131   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
49132   bool LegalOperations = !DCI.isBeforeLegalizeOps();
49133   if (SDValue NegArg =
49134           TLI.getNegatedExpression(Arg, DAG, LegalOperations, CodeSize))
49135     return DAG.getBitcast(OrigVT, NegArg);
49136 
49137   return SDValue();
49138 }
49139 
49140 SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
49141                                                 bool LegalOperations,
49142                                                 bool ForCodeSize,
49143                                                 NegatibleCost &Cost,
49144                                                 unsigned Depth) const {
49145   // fneg patterns are removable even if they have multiple uses.
49146   if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth)) {
49147     Cost = NegatibleCost::Cheaper;
49148     return DAG.getBitcast(Op.getValueType(), Arg);
49149   }
49150 
49151   EVT VT = Op.getValueType();
49152   EVT SVT = VT.getScalarType();
49153   unsigned Opc = Op.getOpcode();
49154   SDNodeFlags Flags = Op.getNode()->getFlags();
49155   switch (Opc) {
49156   case ISD::FMA:
49157   case X86ISD::FMSUB:
49158   case X86ISD::FNMADD:
49159   case X86ISD::FNMSUB:
49160   case X86ISD::FMADD_RND:
49161   case X86ISD::FMSUB_RND:
49162   case X86ISD::FNMADD_RND:
49163   case X86ISD::FNMSUB_RND: {
49164     if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
49165         !(SVT == MVT::f32 || SVT == MVT::f64) ||
49166         !isOperationLegal(ISD::FMA, VT))
49167       break;
49168 
49169     // Don't fold (fneg (fma (fneg x), y, (fneg z))) to (fma x, y, z)
49170     // if it may have signed zeros.
49171     if (!Flags.hasNoSignedZeros())
49172       break;
49173 
49174     // This is always negatible for free but we might be able to remove some
49175     // extra operand negations as well.
49176     SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
49177     for (int i = 0; i != 3; ++i)
49178       NewOps[i] = getCheaperNegatedExpression(
49179           Op.getOperand(i), DAG, LegalOperations, ForCodeSize, Depth + 1);
49180 
49181     bool NegA = !!NewOps[0];
49182     bool NegB = !!NewOps[1];
49183     bool NegC = !!NewOps[2];
49184     unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
49185 
49186     Cost = (NegA || NegB || NegC) ? NegatibleCost::Cheaper
49187                                   : NegatibleCost::Neutral;
49188 
49189     // Fill in the non-negated ops with the original values.
49190     for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
49191       if (!NewOps[i])
49192         NewOps[i] = Op.getOperand(i);
49193     return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
49194   }
49195   case X86ISD::FRCP:
49196     if (SDValue NegOp0 =
49197             getNegatedExpression(Op.getOperand(0), DAG, LegalOperations,
49198                                  ForCodeSize, Cost, Depth + 1))
49199       return DAG.getNode(Opc, SDLoc(Op), VT, NegOp0);
49200     break;
49201   }
49202 
49203   return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
49204                                               ForCodeSize, Cost, Depth);
49205 }
49206 
49207 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
49208                                  const X86Subtarget &Subtarget) {
49209   MVT VT = N->getSimpleValueType(0);
49210   // If we have integer vector types available, use the integer opcodes.
49211   if (!VT.isVector() || !Subtarget.hasSSE2())
49212     return SDValue();
49213 
49214   SDLoc dl(N);
49215 
49216   unsigned IntBits = VT.getScalarSizeInBits();
49217   MVT IntSVT = MVT::getIntegerVT(IntBits);
49218   MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
49219 
49220   SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
49221   SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
49222   unsigned IntOpcode;
49223   switch (N->getOpcode()) {
49224   default: llvm_unreachable("Unexpected FP logic op");
49225   case X86ISD::FOR:   IntOpcode = ISD::OR; break;
49226   case X86ISD::FXOR:  IntOpcode = ISD::XOR; break;
49227   case X86ISD::FAND:  IntOpcode = ISD::AND; break;
49228   case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
49229   }
49230   SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
49231   return DAG.getBitcast(VT, IntOp);
49232 }
49233 
49234 
49235 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
49236 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
49237   if (N->getOpcode() != ISD::XOR)
49238     return SDValue();
49239 
49240   SDValue LHS = N->getOperand(0);
49241   if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
49242     return SDValue();
49243 
49244   X86::CondCode NewCC = X86::GetOppositeBranchCondition(
49245       X86::CondCode(LHS->getConstantOperandVal(0)));
49246   SDLoc DL(N);
49247   return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
49248 }
49249 
49250 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
49251                           TargetLowering::DAGCombinerInfo &DCI,
49252                           const X86Subtarget &Subtarget) {
49253   SDValue N0 = N->getOperand(0);
49254   SDValue N1 = N->getOperand(1);
49255   EVT VT = N->getValueType(0);
49256 
49257   // If this is SSE1 only convert to FXOR to avoid scalarization.
49258   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
49259     return DAG.getBitcast(MVT::v4i32,
49260                           DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
49261                                       DAG.getBitcast(MVT::v4f32, N0),
49262                                       DAG.getBitcast(MVT::v4f32, N1)));
49263   }
49264 
49265   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
49266     return Cmp;
49267 
49268   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
49269     return R;
49270 
49271   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
49272     return FPLogic;
49273 
49274   if (DCI.isBeforeLegalizeOps())
49275     return SDValue();
49276 
49277   if (SDValue SetCC = foldXor1SetCC(N, DAG))
49278     return SetCC;
49279 
49280   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
49281     return RV;
49282 
49283   // Fold not(iX bitcast(vXi1)) -> (iX bitcast(not(vec))) for legal boolvecs.
49284   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49285   if (llvm::isAllOnesConstant(N1) && N0.getOpcode() == ISD::BITCAST &&
49286       N0.getOperand(0).getValueType().isVector() &&
49287       N0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
49288       TLI.isTypeLegal(N0.getOperand(0).getValueType()) && N0.hasOneUse()) {
49289     return DAG.getBitcast(VT, DAG.getNOT(SDLoc(N), N0.getOperand(0),
49290                                          N0.getOperand(0).getValueType()));
49291   }
49292 
49293   // Handle AVX512 mask widening.
49294   // Fold not(insert_subvector(undef,sub)) -> insert_subvector(undef,not(sub))
49295   if (ISD::isBuildVectorAllOnes(N1.getNode()) && VT.isVector() &&
49296       VT.getVectorElementType() == MVT::i1 &&
49297       N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.getOperand(0).isUndef() &&
49298       TLI.isTypeLegal(N0.getOperand(1).getValueType())) {
49299     return DAG.getNode(
49300         ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
49301         DAG.getNOT(SDLoc(N), N0.getOperand(1), N0.getOperand(1).getValueType()),
49302         N0.getOperand(2));
49303   }
49304 
49305   // Fold xor(zext(xor(x,c1)),c2) -> xor(zext(x),xor(zext(c1),c2))
49306   // Fold xor(truncate(xor(x,c1)),c2) -> xor(truncate(x),xor(truncate(c1),c2))
49307   // TODO: Under what circumstances could this be performed in DAGCombine?
49308   if ((N0.getOpcode() == ISD::TRUNCATE || N0.getOpcode() == ISD::ZERO_EXTEND) &&
49309       N0.getOperand(0).getOpcode() == N->getOpcode()) {
49310     SDValue TruncExtSrc = N0.getOperand(0);
49311     auto *N1C = dyn_cast<ConstantSDNode>(N1);
49312     auto *N001C = dyn_cast<ConstantSDNode>(TruncExtSrc.getOperand(1));
49313     if (N1C && !N1C->isOpaque() && N001C && !N001C->isOpaque()) {
49314       SDLoc DL(N);
49315       SDValue LHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(0), DL, VT);
49316       SDValue RHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(1), DL, VT);
49317       return DAG.getNode(ISD::XOR, DL, VT, LHS,
49318                          DAG.getNode(ISD::XOR, DL, VT, RHS, N1));
49319     }
49320   }
49321 
49322   return combineFneg(N, DAG, DCI, Subtarget);
49323 }
49324 
49325 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
49326                             TargetLowering::DAGCombinerInfo &DCI,
49327                             const X86Subtarget &Subtarget) {
49328   EVT VT = N->getValueType(0);
49329   unsigned NumBits = VT.getSizeInBits();
49330 
49331   // TODO - Constant Folding.
49332 
49333   // Simplify the inputs.
49334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49335   APInt DemandedMask(APInt::getAllOnes(NumBits));
49336   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
49337     return SDValue(N, 0);
49338 
49339   return SDValue();
49340 }
49341 
49342 static bool isNullFPScalarOrVectorConst(SDValue V) {
49343   return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
49344 }
49345 
49346 /// If a value is a scalar FP zero or a vector FP zero (potentially including
49347 /// undefined elements), return a zero constant that may be used to fold away
49348 /// that value. In the case of a vector, the returned constant will not contain
49349 /// undefined elements even if the input parameter does. This makes it suitable
49350 /// to be used as a replacement operand with operations (eg, bitwise-and) where
49351 /// an undef should not propagate.
49352 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
49353                                         const X86Subtarget &Subtarget) {
49354   if (!isNullFPScalarOrVectorConst(V))
49355     return SDValue();
49356 
49357   if (V.getValueType().isVector())
49358     return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
49359 
49360   return V;
49361 }
49362 
49363 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
49364                                       const X86Subtarget &Subtarget) {
49365   SDValue N0 = N->getOperand(0);
49366   SDValue N1 = N->getOperand(1);
49367   EVT VT = N->getValueType(0);
49368   SDLoc DL(N);
49369 
49370   // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
49371   if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
49372         (VT == MVT::f64 && Subtarget.hasSSE2()) ||
49373         (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
49374     return SDValue();
49375 
49376   auto isAllOnesConstantFP = [](SDValue V) {
49377     if (V.getSimpleValueType().isVector())
49378       return ISD::isBuildVectorAllOnes(V.getNode());
49379     auto *C = dyn_cast<ConstantFPSDNode>(V);
49380     return C && C->getConstantFPValue()->isAllOnesValue();
49381   };
49382 
49383   // fand (fxor X, -1), Y --> fandn X, Y
49384   if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
49385     return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
49386 
49387   // fand X, (fxor Y, -1) --> fandn Y, X
49388   if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
49389     return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
49390 
49391   return SDValue();
49392 }
49393 
49394 /// Do target-specific dag combines on X86ISD::FAND nodes.
49395 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
49396                            const X86Subtarget &Subtarget) {
49397   // FAND(0.0, x) -> 0.0
49398   if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
49399     return V;
49400 
49401   // FAND(x, 0.0) -> 0.0
49402   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
49403     return V;
49404 
49405   if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
49406     return V;
49407 
49408   return lowerX86FPLogicOp(N, DAG, Subtarget);
49409 }
49410 
49411 /// Do target-specific dag combines on X86ISD::FANDN nodes.
49412 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
49413                             const X86Subtarget &Subtarget) {
49414   // FANDN(0.0, x) -> x
49415   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
49416     return N->getOperand(1);
49417 
49418   // FANDN(x, 0.0) -> 0.0
49419   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
49420     return V;
49421 
49422   return lowerX86FPLogicOp(N, DAG, Subtarget);
49423 }
49424 
49425 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
49426 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
49427                           TargetLowering::DAGCombinerInfo &DCI,
49428                           const X86Subtarget &Subtarget) {
49429   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
49430 
49431   // F[X]OR(0.0, x) -> x
49432   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
49433     return N->getOperand(1);
49434 
49435   // F[X]OR(x, 0.0) -> x
49436   if (isNullFPScalarOrVectorConst(N->getOperand(1)))
49437     return N->getOperand(0);
49438 
49439   if (SDValue NewVal = combineFneg(N, DAG, DCI, Subtarget))
49440     return NewVal;
49441 
49442   return lowerX86FPLogicOp(N, DAG, Subtarget);
49443 }
49444 
49445 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
49446 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
49447   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
49448 
49449   // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
49450   if (!DAG.getTarget().Options.NoNaNsFPMath ||
49451       !DAG.getTarget().Options.NoSignedZerosFPMath)
49452     return SDValue();
49453 
49454   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
49455   // into FMINC and FMAXC, which are Commutative operations.
49456   unsigned NewOp = 0;
49457   switch (N->getOpcode()) {
49458     default: llvm_unreachable("unknown opcode");
49459     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
49460     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
49461   }
49462 
49463   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
49464                      N->getOperand(0), N->getOperand(1));
49465 }
49466 
49467 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
49468                                      const X86Subtarget &Subtarget) {
49469   if (Subtarget.useSoftFloat())
49470     return SDValue();
49471 
49472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49473 
49474   EVT VT = N->getValueType(0);
49475   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
49476         (Subtarget.hasSSE2() && VT == MVT::f64) ||
49477         (Subtarget.hasFP16() && VT == MVT::f16) ||
49478         (VT.isVector() && TLI.isTypeLegal(VT))))
49479     return SDValue();
49480 
49481   SDValue Op0 = N->getOperand(0);
49482   SDValue Op1 = N->getOperand(1);
49483   SDLoc DL(N);
49484   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
49485 
49486   // If we don't have to respect NaN inputs, this is a direct translation to x86
49487   // min/max instructions.
49488   if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
49489     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
49490 
49491   // If one of the operands is known non-NaN use the native min/max instructions
49492   // with the non-NaN input as second operand.
49493   if (DAG.isKnownNeverNaN(Op1))
49494     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
49495   if (DAG.isKnownNeverNaN(Op0))
49496     return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
49497 
49498   // If we have to respect NaN inputs, this takes at least 3 instructions.
49499   // Favor a library call when operating on a scalar and minimizing code size.
49500   if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
49501     return SDValue();
49502 
49503   EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
49504                                          VT);
49505 
49506   // There are 4 possibilities involving NaN inputs, and these are the required
49507   // outputs:
49508   //                   Op1
49509   //               Num     NaN
49510   //            ----------------
49511   //       Num  |  Max  |  Op0 |
49512   // Op0        ----------------
49513   //       NaN  |  Op1  |  NaN |
49514   //            ----------------
49515   //
49516   // The SSE FP max/min instructions were not designed for this case, but rather
49517   // to implement:
49518   //   Min = Op1 < Op0 ? Op1 : Op0
49519   //   Max = Op1 > Op0 ? Op1 : Op0
49520   //
49521   // So they always return Op0 if either input is a NaN. However, we can still
49522   // use those instructions for fmaxnum by selecting away a NaN input.
49523 
49524   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
49525   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
49526   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
49527 
49528   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
49529   // are NaN, the NaN value of Op1 is the result.
49530   return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
49531 }
49532 
49533 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
49534                                    TargetLowering::DAGCombinerInfo &DCI) {
49535   EVT VT = N->getValueType(0);
49536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49537 
49538   APInt KnownUndef, KnownZero;
49539   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
49540   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
49541                                      KnownZero, DCI))
49542     return SDValue(N, 0);
49543 
49544   // Convert a full vector load into vzload when not all bits are needed.
49545   SDValue In = N->getOperand(0);
49546   MVT InVT = In.getSimpleValueType();
49547   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
49548       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
49549     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
49550     LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
49551     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
49552     MVT MemVT = MVT::getIntegerVT(NumBits);
49553     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
49554     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
49555       SDLoc dl(N);
49556       SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
49557                                     DAG.getBitcast(InVT, VZLoad));
49558       DCI.CombineTo(N, Convert);
49559       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
49560       DCI.recursivelyDeleteUnusedNodes(LN);
49561       return SDValue(N, 0);
49562     }
49563   }
49564 
49565   return SDValue();
49566 }
49567 
49568 static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
49569                                      TargetLowering::DAGCombinerInfo &DCI) {
49570   bool IsStrict = N->isTargetStrictFPOpcode();
49571   EVT VT = N->getValueType(0);
49572 
49573   // Convert a full vector load into vzload when not all bits are needed.
49574   SDValue In = N->getOperand(IsStrict ? 1 : 0);
49575   MVT InVT = In.getSimpleValueType();
49576   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
49577       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
49578     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
49579     LoadSDNode *LN = cast<LoadSDNode>(In);
49580     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
49581     MVT MemVT = MVT::getFloatingPointVT(NumBits);
49582     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
49583     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
49584       SDLoc dl(N);
49585       if (IsStrict) {
49586         SDValue Convert =
49587             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
49588                         {N->getOperand(0), DAG.getBitcast(InVT, VZLoad)});
49589         DCI.CombineTo(N, Convert, Convert.getValue(1));
49590       } else {
49591         SDValue Convert =
49592             DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(InVT, VZLoad));
49593         DCI.CombineTo(N, Convert);
49594       }
49595       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
49596       DCI.recursivelyDeleteUnusedNodes(LN);
49597       return SDValue(N, 0);
49598     }
49599   }
49600 
49601   return SDValue();
49602 }
49603 
49604 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
49605 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
49606                             TargetLowering::DAGCombinerInfo &DCI,
49607                             const X86Subtarget &Subtarget) {
49608   MVT VT = N->getSimpleValueType(0);
49609 
49610   // ANDNP(0, x) -> x
49611   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
49612     return N->getOperand(1);
49613 
49614   // ANDNP(x, 0) -> 0
49615   if (ISD::isBuildVectorAllZeros(N->getOperand(1).getNode()))
49616     return DAG.getConstant(0, SDLoc(N), VT);
49617 
49618   // Turn ANDNP back to AND if input is inverted.
49619   if (SDValue Not = IsNOT(N->getOperand(0), DAG))
49620     return DAG.getNode(ISD::AND, SDLoc(N), VT, DAG.getBitcast(VT, Not),
49621                        N->getOperand(1));
49622 
49623   // Attempt to recursively combine a bitmask ANDNP with shuffles.
49624   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
49625     SDValue Op(N, 0);
49626     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
49627       return Res;
49628   }
49629 
49630   return SDValue();
49631 }
49632 
49633 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
49634                          TargetLowering::DAGCombinerInfo &DCI) {
49635   SDValue N1 = N->getOperand(1);
49636 
49637   // BT ignores high bits in the bit index operand.
49638   unsigned BitWidth = N1.getValueSizeInBits();
49639   APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
49640   if (DAG.getTargetLoweringInfo().SimplifyDemandedBits(N1, DemandedMask, DCI)) {
49641     if (N->getOpcode() != ISD::DELETED_NODE)
49642       DCI.AddToWorklist(N);
49643     return SDValue(N, 0);
49644   }
49645 
49646   return SDValue();
49647 }
49648 
49649 static SDValue combineCVTPH2PS(SDNode *N, SelectionDAG &DAG,
49650                                TargetLowering::DAGCombinerInfo &DCI) {
49651   bool IsStrict = N->getOpcode() == X86ISD::STRICT_CVTPH2PS;
49652   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
49653 
49654   if (N->getValueType(0) == MVT::v4f32 && Src.getValueType() == MVT::v8i16) {
49655     APInt KnownUndef, KnownZero;
49656     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49657     APInt DemandedElts = APInt::getLowBitsSet(8, 4);
49658     if (TLI.SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
49659                                        DCI)) {
49660       if (N->getOpcode() != ISD::DELETED_NODE)
49661         DCI.AddToWorklist(N);
49662       return SDValue(N, 0);
49663     }
49664 
49665     // Convert a full vector load into vzload when not all bits are needed.
49666     if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
49667       LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(IsStrict ? 1 : 0));
49668       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::i64, MVT::v2i64, DAG)) {
49669         SDLoc dl(N);
49670         if (IsStrict) {
49671           SDValue Convert = DAG.getNode(
49672               N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
49673               {N->getOperand(0), DAG.getBitcast(MVT::v8i16, VZLoad)});
49674           DCI.CombineTo(N, Convert, Convert.getValue(1));
49675         } else {
49676           SDValue Convert = DAG.getNode(N->getOpcode(), dl, MVT::v4f32,
49677                                         DAG.getBitcast(MVT::v8i16, VZLoad));
49678           DCI.CombineTo(N, Convert);
49679         }
49680 
49681         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
49682         DCI.recursivelyDeleteUnusedNodes(LN);
49683         return SDValue(N, 0);
49684       }
49685     }
49686   }
49687 
49688   return SDValue();
49689 }
49690 
49691 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
49692 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
49693   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
49694 
49695   EVT DstVT = N->getValueType(0);
49696 
49697   SDValue N0 = N->getOperand(0);
49698   SDValue N1 = N->getOperand(1);
49699   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
49700 
49701   if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
49702     return SDValue();
49703 
49704   // Look through single use any_extends / truncs.
49705   SDValue IntermediateBitwidthOp;
49706   if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
49707       N0.hasOneUse()) {
49708     IntermediateBitwidthOp = N0;
49709     N0 = N0.getOperand(0);
49710   }
49711 
49712   // See if we have a single use cmov.
49713   if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
49714     return SDValue();
49715 
49716   SDValue CMovOp0 = N0.getOperand(0);
49717   SDValue CMovOp1 = N0.getOperand(1);
49718 
49719   // Make sure both operands are constants.
49720   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
49721       !isa<ConstantSDNode>(CMovOp1.getNode()))
49722     return SDValue();
49723 
49724   SDLoc DL(N);
49725 
49726   // If we looked through an any_extend/trunc above, add one to the constants.
49727   if (IntermediateBitwidthOp) {
49728     unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
49729     CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
49730     CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
49731   }
49732 
49733   CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
49734   CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
49735 
49736   EVT CMovVT = DstVT;
49737   // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
49738   if (DstVT == MVT::i16) {
49739     CMovVT = MVT::i32;
49740     CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
49741     CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
49742   }
49743 
49744   SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
49745                              N0.getOperand(2), N0.getOperand(3));
49746 
49747   if (CMovVT != DstVT)
49748     CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
49749 
49750   return CMov;
49751 }
49752 
49753 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
49754                                       const X86Subtarget &Subtarget) {
49755   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
49756 
49757   if (SDValue V = combineSextInRegCmov(N, DAG))
49758     return V;
49759 
49760   EVT VT = N->getValueType(0);
49761   SDValue N0 = N->getOperand(0);
49762   SDValue N1 = N->getOperand(1);
49763   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
49764   SDLoc dl(N);
49765 
49766   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
49767   // both SSE and AVX2 since there is no sign-extended shift right
49768   // operation on a vector with 64-bit elements.
49769   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
49770   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
49771   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
49772                            N0.getOpcode() == ISD::SIGN_EXTEND)) {
49773     SDValue N00 = N0.getOperand(0);
49774 
49775     // EXTLOAD has a better solution on AVX2,
49776     // it may be replaced with X86ISD::VSEXT node.
49777     if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
49778       if (!ISD::isNormalLoad(N00.getNode()))
49779         return SDValue();
49780 
49781     // Attempt to promote any comparison mask ops before moving the
49782     // SIGN_EXTEND_INREG in the way.
49783     if (SDValue Promote = PromoteMaskArithmetic(N0.getNode(), DAG, Subtarget))
49784       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Promote, N1);
49785 
49786     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
49787       SDValue Tmp =
49788           DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, N00, N1);
49789       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
49790     }
49791   }
49792   return SDValue();
49793 }
49794 
49795 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
49796 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
49797 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
49798 /// opportunities to combine math ops, use an LEA, or use a complex addressing
49799 /// mode. This can eliminate extend, add, and shift instructions.
49800 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
49801                                    const X86Subtarget &Subtarget) {
49802   if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
49803       Ext->getOpcode() != ISD::ZERO_EXTEND)
49804     return SDValue();
49805 
49806   // TODO: This should be valid for other integer types.
49807   EVT VT = Ext->getValueType(0);
49808   if (VT != MVT::i64)
49809     return SDValue();
49810 
49811   SDValue Add = Ext->getOperand(0);
49812   if (Add.getOpcode() != ISD::ADD)
49813     return SDValue();
49814 
49815   bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
49816   bool NSW = Add->getFlags().hasNoSignedWrap();
49817   bool NUW = Add->getFlags().hasNoUnsignedWrap();
49818 
49819   // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
49820   // into the 'zext'
49821   if ((Sext && !NSW) || (!Sext && !NUW))
49822     return SDValue();
49823 
49824   // Having a constant operand to the 'add' ensures that we are not increasing
49825   // the instruction count because the constant is extended for free below.
49826   // A constant operand can also become the displacement field of an LEA.
49827   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
49828   if (!AddOp1)
49829     return SDValue();
49830 
49831   // Don't make the 'add' bigger if there's no hope of combining it with some
49832   // other 'add' or 'shl' instruction.
49833   // TODO: It may be profitable to generate simpler LEA instructions in place
49834   // of single 'add' instructions, but the cost model for selecting an LEA
49835   // currently has a high threshold.
49836   bool HasLEAPotential = false;
49837   for (auto *User : Ext->uses()) {
49838     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
49839       HasLEAPotential = true;
49840       break;
49841     }
49842   }
49843   if (!HasLEAPotential)
49844     return SDValue();
49845 
49846   // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
49847   int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
49848   SDValue AddOp0 = Add.getOperand(0);
49849   SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
49850   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
49851 
49852   // The wider add is guaranteed to not wrap because both operands are
49853   // sign-extended.
49854   SDNodeFlags Flags;
49855   Flags.setNoSignedWrap(NSW);
49856   Flags.setNoUnsignedWrap(NUW);
49857   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
49858 }
49859 
49860 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
49861 // operands and the result of CMOV is not used anywhere else - promote CMOV
49862 // itself instead of promoting its result. This could be beneficial, because:
49863 //     1) X86TargetLowering::EmitLoweredSelect later can do merging of two
49864 //        (or more) pseudo-CMOVs only when they go one-after-another and
49865 //        getting rid of result extension code after CMOV will help that.
49866 //     2) Promotion of constant CMOV arguments is free, hence the
49867 //        {ANY,SIGN,ZERO}_EXTEND will just be deleted.
49868 //     3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
49869 //        promotion is also good in terms of code-size.
49870 //        (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
49871 //         promotion).
49872 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
49873   SDValue CMovN = Extend->getOperand(0);
49874   if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
49875     return SDValue();
49876 
49877   EVT TargetVT = Extend->getValueType(0);
49878   unsigned ExtendOpcode = Extend->getOpcode();
49879   SDLoc DL(Extend);
49880 
49881   EVT VT = CMovN.getValueType();
49882   SDValue CMovOp0 = CMovN.getOperand(0);
49883   SDValue CMovOp1 = CMovN.getOperand(1);
49884 
49885   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
49886       !isa<ConstantSDNode>(CMovOp1.getNode()))
49887     return SDValue();
49888 
49889   // Only extend to i32 or i64.
49890   if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
49891     return SDValue();
49892 
49893   // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
49894   // are free.
49895   if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
49896     return SDValue();
49897 
49898   // If this a zero extend to i64, we should only extend to i32 and use a free
49899   // zero extend to finish.
49900   EVT ExtendVT = TargetVT;
49901   if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
49902     ExtendVT = MVT::i32;
49903 
49904   CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
49905   CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
49906 
49907   SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
49908                             CMovN.getOperand(2), CMovN.getOperand(3));
49909 
49910   // Finish extending if needed.
49911   if (ExtendVT != TargetVT)
49912     Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
49913 
49914   return Res;
49915 }
49916 
49917 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
49918 // This is more or less the reverse of combineBitcastvxi1.
49919 static SDValue
49920 combineToExtendBoolVectorInReg(SDNode *N, SelectionDAG &DAG,
49921                                TargetLowering::DAGCombinerInfo &DCI,
49922                                const X86Subtarget &Subtarget) {
49923   unsigned Opcode = N->getOpcode();
49924   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
49925       Opcode != ISD::ANY_EXTEND)
49926     return SDValue();
49927   if (!DCI.isBeforeLegalizeOps())
49928     return SDValue();
49929   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
49930     return SDValue();
49931 
49932   SDValue N0 = N->getOperand(0);
49933   EVT VT = N->getValueType(0);
49934   EVT SVT = VT.getScalarType();
49935   EVT InSVT = N0.getValueType().getScalarType();
49936   unsigned EltSizeInBits = SVT.getSizeInBits();
49937 
49938   // Input type must be extending a bool vector (bit-casted from a scalar
49939   // integer) to legal integer types.
49940   if (!VT.isVector())
49941     return SDValue();
49942   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
49943     return SDValue();
49944   if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
49945     return SDValue();
49946 
49947   SDValue N00 = N0.getOperand(0);
49948   EVT SclVT = N0.getOperand(0).getValueType();
49949   if (!SclVT.isScalarInteger())
49950     return SDValue();
49951 
49952   SDLoc DL(N);
49953   SDValue Vec;
49954   SmallVector<int, 32> ShuffleMask;
49955   unsigned NumElts = VT.getVectorNumElements();
49956   assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
49957 
49958   // Broadcast the scalar integer to the vector elements.
49959   if (NumElts > EltSizeInBits) {
49960     // If the scalar integer is greater than the vector element size, then we
49961     // must split it down into sub-sections for broadcasting. For example:
49962     //   i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
49963     //   i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
49964     assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
49965     unsigned Scale = NumElts / EltSizeInBits;
49966     EVT BroadcastVT =
49967         EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
49968     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
49969     Vec = DAG.getBitcast(VT, Vec);
49970 
49971     for (unsigned i = 0; i != Scale; ++i)
49972       ShuffleMask.append(EltSizeInBits, i);
49973     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
49974   } else if (Subtarget.hasAVX2() && NumElts < EltSizeInBits &&
49975              (SclVT == MVT::i8 || SclVT == MVT::i16 || SclVT == MVT::i32)) {
49976     // If we have register broadcast instructions, use the scalar size as the
49977     // element type for the shuffle. Then cast to the wider element type. The
49978     // widened bits won't be used, and this might allow the use of a broadcast
49979     // load.
49980     assert((EltSizeInBits % NumElts) == 0 && "Unexpected integer scale");
49981     unsigned Scale = EltSizeInBits / NumElts;
49982     EVT BroadcastVT =
49983         EVT::getVectorVT(*DAG.getContext(), SclVT, NumElts * Scale);
49984     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
49985     ShuffleMask.append(NumElts * Scale, 0);
49986     Vec = DAG.getVectorShuffle(BroadcastVT, DL, Vec, Vec, ShuffleMask);
49987     Vec = DAG.getBitcast(VT, Vec);
49988   } else {
49989     // For smaller scalar integers, we can simply any-extend it to the vector
49990     // element size (we don't care about the upper bits) and broadcast it to all
49991     // elements.
49992     SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
49993     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
49994     ShuffleMask.append(NumElts, 0);
49995     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
49996   }
49997 
49998   // Now, mask the relevant bit in each element.
49999   SmallVector<SDValue, 32> Bits;
50000   for (unsigned i = 0; i != NumElts; ++i) {
50001     int BitIdx = (i % EltSizeInBits);
50002     APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
50003     Bits.push_back(DAG.getConstant(Bit, DL, SVT));
50004   }
50005   SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
50006   Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
50007 
50008   // Compare against the bitmask and extend the result.
50009   EVT CCVT = VT.changeVectorElementType(MVT::i1);
50010   Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
50011   Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
50012 
50013   // For SEXT, this is now done, otherwise shift the result down for
50014   // zero-extension.
50015   if (Opcode == ISD::SIGN_EXTEND)
50016     return Vec;
50017   return DAG.getNode(ISD::SRL, DL, VT, Vec,
50018                      DAG.getConstant(EltSizeInBits - 1, DL, VT));
50019 }
50020 
50021 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
50022 // result type.
50023 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
50024                                const X86Subtarget &Subtarget) {
50025   SDValue N0 = N->getOperand(0);
50026   EVT VT = N->getValueType(0);
50027   SDLoc dl(N);
50028 
50029   // Only do this combine with AVX512 for vector extends.
50030   if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
50031     return SDValue();
50032 
50033   // Only combine legal element types.
50034   EVT SVT = VT.getVectorElementType();
50035   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
50036       SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
50037     return SDValue();
50038 
50039   // We don't have CMPP Instruction for vxf16
50040   if (N0.getOperand(0).getValueType().getVectorElementType() == MVT::f16)
50041     return SDValue();
50042   // We can only do this if the vector size in 256 bits or less.
50043   unsigned Size = VT.getSizeInBits();
50044   if (Size > 256 && Subtarget.useAVX512Regs())
50045     return SDValue();
50046 
50047   // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
50048   // that's the only integer compares with we have.
50049   ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
50050   if (ISD::isUnsignedIntSetCC(CC))
50051     return SDValue();
50052 
50053   // Only do this combine if the extension will be fully consumed by the setcc.
50054   EVT N00VT = N0.getOperand(0).getValueType();
50055   EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
50056   if (Size != MatchingVecType.getSizeInBits())
50057     return SDValue();
50058 
50059   SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
50060 
50061   if (N->getOpcode() == ISD::ZERO_EXTEND)
50062     Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType());
50063 
50064   return Res;
50065 }
50066 
50067 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
50068                            TargetLowering::DAGCombinerInfo &DCI,
50069                            const X86Subtarget &Subtarget) {
50070   SDValue N0 = N->getOperand(0);
50071   EVT VT = N->getValueType(0);
50072   SDLoc DL(N);
50073 
50074   // (i32 (sext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
50075   if (!DCI.isBeforeLegalizeOps() &&
50076       N0.getOpcode() == X86ISD::SETCC_CARRY) {
50077     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, N0->getOperand(0),
50078                                  N0->getOperand(1));
50079     bool ReplaceOtherUses = !N0.hasOneUse();
50080     DCI.CombineTo(N, Setcc);
50081     // Replace other uses with a truncate of the widened setcc_carry.
50082     if (ReplaceOtherUses) {
50083       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
50084                                   N0.getValueType(), Setcc);
50085       DCI.CombineTo(N0.getNode(), Trunc);
50086     }
50087 
50088     return SDValue(N, 0);
50089   }
50090 
50091   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
50092     return NewCMov;
50093 
50094   if (!DCI.isBeforeLegalizeOps())
50095     return SDValue();
50096 
50097   if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
50098     return V;
50099 
50100   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
50101     return V;
50102 
50103   if (VT.isVector()) {
50104     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
50105       return R;
50106 
50107     if (N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG)
50108       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
50109   }
50110 
50111   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
50112     return NewAdd;
50113 
50114   return SDValue();
50115 }
50116 
50117 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
50118                           TargetLowering::DAGCombinerInfo &DCI,
50119                           const X86Subtarget &Subtarget) {
50120   SDLoc dl(N);
50121   EVT VT = N->getValueType(0);
50122   bool IsStrict = N->isStrictFPOpcode() || N->isTargetStrictFPOpcode();
50123 
50124   // Let legalize expand this if it isn't a legal type yet.
50125   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50126   if (!TLI.isTypeLegal(VT))
50127     return SDValue();
50128 
50129   SDValue A = N->getOperand(IsStrict ? 1 : 0);
50130   SDValue B = N->getOperand(IsStrict ? 2 : 1);
50131   SDValue C = N->getOperand(IsStrict ? 3 : 2);
50132 
50133   // If the operation allows fast-math and the target does not support FMA,
50134   // split this into mul+add to avoid libcall(s).
50135   SDNodeFlags Flags = N->getFlags();
50136   if (!IsStrict && Flags.hasAllowReassociation() &&
50137       TLI.isOperationExpand(ISD::FMA, VT)) {
50138     SDValue Fmul = DAG.getNode(ISD::FMUL, dl, VT, A, B, Flags);
50139     return DAG.getNode(ISD::FADD, dl, VT, Fmul, C, Flags);
50140   }
50141 
50142   EVT ScalarVT = VT.getScalarType();
50143   if (((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
50144        !Subtarget.hasAnyFMA()) &&
50145       !(ScalarVT == MVT::f16 && Subtarget.hasFP16()))
50146     return SDValue();
50147 
50148   auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
50149     bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
50150     bool LegalOperations = !DCI.isBeforeLegalizeOps();
50151     if (SDValue NegV = TLI.getCheaperNegatedExpression(V, DAG, LegalOperations,
50152                                                        CodeSize)) {
50153       V = NegV;
50154       return true;
50155     }
50156     // Look through extract_vector_elts. If it comes from an FNEG, create a
50157     // new extract from the FNEG input.
50158     if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
50159         isNullConstant(V.getOperand(1))) {
50160       SDValue Vec = V.getOperand(0);
50161       if (SDValue NegV = TLI.getCheaperNegatedExpression(
50162               Vec, DAG, LegalOperations, CodeSize)) {
50163         V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
50164                         NegV, V.getOperand(1));
50165         return true;
50166       }
50167     }
50168 
50169     return false;
50170   };
50171 
50172   // Do not convert the passthru input of scalar intrinsics.
50173   // FIXME: We could allow negations of the lower element only.
50174   bool NegA = invertIfNegative(A);
50175   bool NegB = invertIfNegative(B);
50176   bool NegC = invertIfNegative(C);
50177 
50178   if (!NegA && !NegB && !NegC)
50179     return SDValue();
50180 
50181   unsigned NewOpcode =
50182       negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
50183 
50184   // Propagate fast-math-flags to new FMA node.
50185   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
50186   if (IsStrict) {
50187     assert(N->getNumOperands() == 4 && "Shouldn't be greater than 4");
50188     return DAG.getNode(NewOpcode, dl, {VT, MVT::Other},
50189                        {N->getOperand(0), A, B, C});
50190   } else {
50191     if (N->getNumOperands() == 4)
50192       return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
50193     return DAG.getNode(NewOpcode, dl, VT, A, B, C);
50194   }
50195 }
50196 
50197 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
50198 // Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
50199 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
50200                                TargetLowering::DAGCombinerInfo &DCI) {
50201   SDLoc dl(N);
50202   EVT VT = N->getValueType(0);
50203   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50204   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
50205   bool LegalOperations = !DCI.isBeforeLegalizeOps();
50206 
50207   SDValue N2 = N->getOperand(2);
50208 
50209   SDValue NegN2 =
50210       TLI.getCheaperNegatedExpression(N2, DAG, LegalOperations, CodeSize);
50211   if (!NegN2)
50212     return SDValue();
50213   unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
50214 
50215   if (N->getNumOperands() == 4)
50216     return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
50217                        NegN2, N->getOperand(3));
50218   return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
50219                      NegN2);
50220 }
50221 
50222 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
50223                            TargetLowering::DAGCombinerInfo &DCI,
50224                            const X86Subtarget &Subtarget) {
50225   SDLoc dl(N);
50226   SDValue N0 = N->getOperand(0);
50227   EVT VT = N->getValueType(0);
50228 
50229   // (i32 (aext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
50230   // FIXME: Is this needed? We don't seem to have any tests for it.
50231   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ANY_EXTEND &&
50232       N0.getOpcode() == X86ISD::SETCC_CARRY) {
50233     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, N0->getOperand(0),
50234                                  N0->getOperand(1));
50235     bool ReplaceOtherUses = !N0.hasOneUse();
50236     DCI.CombineTo(N, Setcc);
50237     // Replace other uses with a truncate of the widened setcc_carry.
50238     if (ReplaceOtherUses) {
50239       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
50240                                   N0.getValueType(), Setcc);
50241       DCI.CombineTo(N0.getNode(), Trunc);
50242     }
50243 
50244     return SDValue(N, 0);
50245   }
50246 
50247   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
50248     return NewCMov;
50249 
50250   if (DCI.isBeforeLegalizeOps())
50251     if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
50252       return V;
50253 
50254   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
50255     return V;
50256 
50257   if (VT.isVector())
50258     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
50259       return R;
50260 
50261   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
50262     return NewAdd;
50263 
50264   if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
50265     return R;
50266 
50267   // TODO: Combine with any target/faux shuffle.
50268   if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
50269       VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
50270     SDValue N00 = N0.getOperand(0);
50271     SDValue N01 = N0.getOperand(1);
50272     unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
50273     APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
50274     if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
50275         (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
50276       return concatSubVectors(N00, N01, DAG, dl);
50277     }
50278   }
50279 
50280   return SDValue();
50281 }
50282 
50283 /// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
50284 /// recognizable memcmp expansion.
50285 static bool isOrXorXorTree(SDValue X, bool Root = true) {
50286   if (X.getOpcode() == ISD::OR)
50287     return isOrXorXorTree(X.getOperand(0), false) &&
50288            isOrXorXorTree(X.getOperand(1), false);
50289   if (Root)
50290     return false;
50291   return X.getOpcode() == ISD::XOR;
50292 }
50293 
50294 /// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
50295 /// expansion.
50296 template<typename F>
50297 static SDValue emitOrXorXorTree(SDValue X, SDLoc &DL, SelectionDAG &DAG,
50298                                 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
50299   SDValue Op0 = X.getOperand(0);
50300   SDValue Op1 = X.getOperand(1);
50301   if (X.getOpcode() == ISD::OR) {
50302     SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
50303     SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
50304     if (VecVT != CmpVT)
50305       return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
50306     if (HasPT)
50307       return DAG.getNode(ISD::OR, DL, VecVT, A, B);
50308     return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
50309   } else if (X.getOpcode() == ISD::XOR) {
50310     SDValue A = SToV(Op0);
50311     SDValue B = SToV(Op1);
50312     if (VecVT != CmpVT)
50313       return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
50314     if (HasPT)
50315       return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
50316     return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
50317   }
50318   llvm_unreachable("Impossible");
50319 }
50320 
50321 /// Try to map a 128-bit or larger integer comparison to vector instructions
50322 /// before type legalization splits it up into chunks.
50323 static SDValue combineVectorSizedSetCCEquality(SDNode *SetCC, SelectionDAG &DAG,
50324                                                const X86Subtarget &Subtarget) {
50325   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
50326   assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
50327 
50328   // We're looking for an oversized integer equality comparison.
50329   SDValue X = SetCC->getOperand(0);
50330   SDValue Y = SetCC->getOperand(1);
50331   EVT OpVT = X.getValueType();
50332   unsigned OpSize = OpVT.getSizeInBits();
50333   if (!OpVT.isScalarInteger() || OpSize < 128)
50334     return SDValue();
50335 
50336   // Ignore a comparison with zero because that gets special treatment in
50337   // EmitTest(). But make an exception for the special case of a pair of
50338   // logically-combined vector-sized operands compared to zero. This pattern may
50339   // be generated by the memcmp expansion pass with oversized integer compares
50340   // (see PR33325).
50341   bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
50342   if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
50343     return SDValue();
50344 
50345   // Don't perform this combine if constructing the vector will be expensive.
50346   auto IsVectorBitCastCheap = [](SDValue X) {
50347     X = peekThroughBitcasts(X);
50348     return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
50349            X.getOpcode() == ISD::LOAD;
50350   };
50351   if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
50352       !IsOrXorXorTreeCCZero)
50353     return SDValue();
50354 
50355   EVT VT = SetCC->getValueType(0);
50356   SDLoc DL(SetCC);
50357 
50358   // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
50359   // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
50360   // Otherwise use PCMPEQ (plus AND) and mask testing.
50361   if ((OpSize == 128 && Subtarget.hasSSE2()) ||
50362       (OpSize == 256 && Subtarget.hasAVX()) ||
50363       (OpSize == 512 && Subtarget.useAVX512Regs())) {
50364     bool HasPT = Subtarget.hasSSE41();
50365 
50366     // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
50367     // vector registers are essentially free. (Technically, widening registers
50368     // prevents load folding, but the tradeoff is worth it.)
50369     bool PreferKOT = Subtarget.preferMaskRegisters();
50370     bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
50371 
50372     EVT VecVT = MVT::v16i8;
50373     EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
50374     if (OpSize == 256) {
50375       VecVT = MVT::v32i8;
50376       CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
50377     }
50378     EVT CastVT = VecVT;
50379     bool NeedsAVX512FCast = false;
50380     if (OpSize == 512 || NeedZExt) {
50381       if (Subtarget.hasBWI()) {
50382         VecVT = MVT::v64i8;
50383         CmpVT = MVT::v64i1;
50384         if (OpSize == 512)
50385           CastVT = VecVT;
50386       } else {
50387         VecVT = MVT::v16i32;
50388         CmpVT = MVT::v16i1;
50389         CastVT = OpSize == 512 ? VecVT :
50390                  OpSize == 256 ? MVT::v8i32 : MVT::v4i32;
50391         NeedsAVX512FCast = true;
50392       }
50393     }
50394 
50395     auto ScalarToVector = [&](SDValue X) -> SDValue {
50396       bool TmpZext = false;
50397       EVT TmpCastVT = CastVT;
50398       if (X.getOpcode() == ISD::ZERO_EXTEND) {
50399         SDValue OrigX = X.getOperand(0);
50400         unsigned OrigSize = OrigX.getScalarValueSizeInBits();
50401         if (OrigSize < OpSize) {
50402           if (OrigSize == 128) {
50403             TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
50404             X = OrigX;
50405             TmpZext = true;
50406           } else if (OrigSize == 256) {
50407             TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
50408             X = OrigX;
50409             TmpZext = true;
50410           }
50411         }
50412       }
50413       X = DAG.getBitcast(TmpCastVT, X);
50414       if (!NeedZExt && !TmpZext)
50415         return X;
50416       return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
50417                          DAG.getConstant(0, DL, VecVT), X,
50418                          DAG.getVectorIdxConstant(0, DL));
50419     };
50420 
50421     SDValue Cmp;
50422     if (IsOrXorXorTreeCCZero) {
50423       // This is a bitwise-combined equality comparison of 2 pairs of vectors:
50424       // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
50425       // Use 2 vector equality compares and 'and' the results before doing a
50426       // MOVMSK.
50427       Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
50428     } else {
50429       SDValue VecX = ScalarToVector(X);
50430       SDValue VecY = ScalarToVector(Y);
50431       if (VecVT != CmpVT) {
50432         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
50433       } else if (HasPT) {
50434         Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
50435       } else {
50436         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
50437       }
50438     }
50439     // AVX512 should emit a setcc that will lower to kortest.
50440     if (VecVT != CmpVT) {
50441       EVT KRegVT = CmpVT == MVT::v64i1 ? MVT::i64 :
50442                    CmpVT == MVT::v32i1 ? MVT::i32 : MVT::i16;
50443       return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
50444                           DAG.getConstant(0, DL, KRegVT), CC);
50445     }
50446     if (HasPT) {
50447       SDValue BCCmp = DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64,
50448                                      Cmp);
50449       SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
50450       X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
50451       SDValue X86SetCC = getSETCC(X86CC, PT, DL, DAG);
50452       return DAG.getNode(ISD::TRUNCATE, DL, VT, X86SetCC.getValue(0));
50453     }
50454     // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
50455     // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
50456     // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
50457     assert(Cmp.getValueType() == MVT::v16i8 &&
50458            "Non 128-bit vector on pre-SSE41 target");
50459     SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
50460     SDValue FFFFs = DAG.getConstant(0xFFFF, DL, MVT::i32);
50461     return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
50462   }
50463 
50464   return SDValue();
50465 }
50466 
50467 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
50468                             TargetLowering::DAGCombinerInfo &DCI,
50469                             const X86Subtarget &Subtarget) {
50470   const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
50471   const SDValue LHS = N->getOperand(0);
50472   const SDValue RHS = N->getOperand(1);
50473   EVT VT = N->getValueType(0);
50474   EVT OpVT = LHS.getValueType();
50475   SDLoc DL(N);
50476 
50477   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
50478     if (SDValue V = combineVectorSizedSetCCEquality(N, DAG, Subtarget))
50479       return V;
50480 
50481     if (VT == MVT::i1 && isNullConstant(RHS)) {
50482       SDValue X86CC;
50483       if (SDValue V =
50484               MatchVectorAllZeroTest(LHS, CC, DL, Subtarget, DAG, X86CC))
50485         return DAG.getNode(ISD::TRUNCATE, DL, VT,
50486                            DAG.getNode(X86ISD::SETCC, DL, MVT::i8, X86CC, V));
50487     }
50488 
50489     if (OpVT.isScalarInteger()) {
50490       // cmpeq(or(X,Y),X) --> cmpeq(and(~X,Y),0)
50491       // cmpne(or(X,Y),X) --> cmpne(and(~X,Y),0)
50492       auto MatchOrCmpEq = [&](SDValue N0, SDValue N1) {
50493         if (N0.getOpcode() == ISD::OR && N0->hasOneUse()) {
50494           if (N0.getOperand(0) == N1)
50495             return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
50496                                N0.getOperand(1));
50497           if (N0.getOperand(1) == N1)
50498             return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
50499                                N0.getOperand(0));
50500         }
50501         return SDValue();
50502       };
50503       if (SDValue AndN = MatchOrCmpEq(LHS, RHS))
50504         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
50505       if (SDValue AndN = MatchOrCmpEq(RHS, LHS))
50506         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
50507 
50508       // cmpeq(and(X,Y),Y) --> cmpeq(and(~X,Y),0)
50509       // cmpne(and(X,Y),Y) --> cmpne(and(~X,Y),0)
50510       auto MatchAndCmpEq = [&](SDValue N0, SDValue N1) {
50511         if (N0.getOpcode() == ISD::AND && N0->hasOneUse()) {
50512           if (N0.getOperand(0) == N1)
50513             return DAG.getNode(ISD::AND, DL, OpVT, N1,
50514                                DAG.getNOT(DL, N0.getOperand(1), OpVT));
50515           if (N0.getOperand(1) == N1)
50516             return DAG.getNode(ISD::AND, DL, OpVT, N1,
50517                                DAG.getNOT(DL, N0.getOperand(0), OpVT));
50518         }
50519         return SDValue();
50520       };
50521       if (SDValue AndN = MatchAndCmpEq(LHS, RHS))
50522         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
50523       if (SDValue AndN = MatchAndCmpEq(RHS, LHS))
50524         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
50525 
50526       // cmpeq(trunc(x),0) --> cmpeq(x,0)
50527       // cmpne(trunc(x),0) --> cmpne(x,0)
50528       // iff x upper bits are zero.
50529       // TODO: Add support for RHS to be truncate as well?
50530       if (LHS.getOpcode() == ISD::TRUNCATE &&
50531           LHS.getOperand(0).getScalarValueSizeInBits() >= 32 &&
50532           isNullConstant(RHS) && !DCI.isBeforeLegalize()) {
50533         EVT SrcVT = LHS.getOperand(0).getValueType();
50534         APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
50535                                                 OpVT.getScalarSizeInBits());
50536         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50537         if (DAG.MaskedValueIsZero(LHS.getOperand(0), UpperBits) &&
50538             TLI.isTypeLegal(LHS.getOperand(0).getValueType()))
50539           return DAG.getSetCC(DL, VT, LHS.getOperand(0),
50540                               DAG.getConstant(0, DL, SrcVT), CC);
50541       }
50542     }
50543   }
50544 
50545   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
50546       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
50547     // Using temporaries to avoid messing up operand ordering for later
50548     // transformations if this doesn't work.
50549     SDValue Op0 = LHS;
50550     SDValue Op1 = RHS;
50551     ISD::CondCode TmpCC = CC;
50552     // Put build_vector on the right.
50553     if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
50554       std::swap(Op0, Op1);
50555       TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
50556     }
50557 
50558     bool IsSEXT0 =
50559         (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
50560         (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
50561     bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
50562 
50563     if (IsSEXT0 && IsVZero1) {
50564       assert(VT == Op0.getOperand(0).getValueType() &&
50565              "Unexpected operand type");
50566       if (TmpCC == ISD::SETGT)
50567         return DAG.getConstant(0, DL, VT);
50568       if (TmpCC == ISD::SETLE)
50569         return DAG.getConstant(1, DL, VT);
50570       if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
50571         return DAG.getNOT(DL, Op0.getOperand(0), VT);
50572 
50573       assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&
50574              "Unexpected condition code!");
50575       return Op0.getOperand(0);
50576     }
50577   }
50578 
50579   // If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
50580   // pre-promote its result type since vXi1 vectors don't get promoted
50581   // during type legalization.
50582   // NOTE: The element count check is to ignore operand types that need to
50583   // go through type promotion to a 128-bit vector.
50584   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
50585       VT.getVectorElementType() == MVT::i1 &&
50586       (OpVT.getVectorElementType() == MVT::i8 ||
50587        OpVT.getVectorElementType() == MVT::i16)) {
50588     SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
50589     return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
50590   }
50591 
50592   // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
50593   // to avoid scalarization via legalization because v4i32 is not a legal type.
50594   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
50595       LHS.getValueType() == MVT::v4f32)
50596     return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
50597 
50598   return SDValue();
50599 }
50600 
50601 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
50602                              TargetLowering::DAGCombinerInfo &DCI,
50603                              const X86Subtarget &Subtarget) {
50604   SDValue Src = N->getOperand(0);
50605   MVT SrcVT = Src.getSimpleValueType();
50606   MVT VT = N->getSimpleValueType(0);
50607   unsigned NumBits = VT.getScalarSizeInBits();
50608   unsigned NumElts = SrcVT.getVectorNumElements();
50609 
50610   // Perform constant folding.
50611   if (ISD::isBuildVectorOfConstantSDNodes(Src.getNode())) {
50612     assert(VT == MVT::i32 && "Unexpected result type");
50613     APInt Imm(32, 0);
50614     for (unsigned Idx = 0, e = Src.getNumOperands(); Idx < e; ++Idx) {
50615       if (!Src.getOperand(Idx).isUndef() &&
50616           Src.getConstantOperandAPInt(Idx).isNegative())
50617         Imm.setBit(Idx);
50618     }
50619     return DAG.getConstant(Imm, SDLoc(N), VT);
50620   }
50621 
50622   // Look through int->fp bitcasts that don't change the element width.
50623   unsigned EltWidth = SrcVT.getScalarSizeInBits();
50624   if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
50625       Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
50626     return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
50627 
50628   // Fold movmsk(not(x)) -> not(movmsk(x)) to improve folding of movmsk results
50629   // with scalar comparisons.
50630   if (SDValue NotSrc = IsNOT(Src, DAG)) {
50631     SDLoc DL(N);
50632     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
50633     NotSrc = DAG.getBitcast(SrcVT, NotSrc);
50634     return DAG.getNode(ISD::XOR, DL, VT,
50635                        DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
50636                        DAG.getConstant(NotMask, DL, VT));
50637   }
50638 
50639   // Fold movmsk(icmp_sgt(x,-1)) -> not(movmsk(x)) to improve folding of movmsk
50640   // results with scalar comparisons.
50641   if (Src.getOpcode() == X86ISD::PCMPGT &&
50642       ISD::isBuildVectorAllOnes(Src.getOperand(1).getNode())) {
50643     SDLoc DL(N);
50644     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
50645     return DAG.getNode(ISD::XOR, DL, VT,
50646                        DAG.getNode(X86ISD::MOVMSK, DL, VT, Src.getOperand(0)),
50647                        DAG.getConstant(NotMask, DL, VT));
50648   }
50649 
50650   // Simplify the inputs.
50651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50652   APInt DemandedMask(APInt::getAllOnes(NumBits));
50653   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
50654     return SDValue(N, 0);
50655 
50656   return SDValue();
50657 }
50658 
50659 static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
50660                                        TargetLowering::DAGCombinerInfo &DCI,
50661                                        const X86Subtarget &Subtarget) {
50662   auto *MemOp = cast<X86MaskedGatherScatterSDNode>(N);
50663   SDValue BasePtr = MemOp->getBasePtr();
50664   SDValue Index = MemOp->getIndex();
50665   SDValue Scale = MemOp->getScale();
50666   SDValue Mask = MemOp->getMask();
50667 
50668   // Attempt to fold an index scale into the scale value directly.
50669   // For smaller indices, implicit sext is performed BEFORE scale, preventing
50670   // this fold under most circumstances.
50671   // TODO: Move this into X86DAGToDAGISel::matchVectorAddressRecursively?
50672   if ((Index.getOpcode() == X86ISD::VSHLI ||
50673        (Index.getOpcode() == ISD::ADD &&
50674         Index.getOperand(0) == Index.getOperand(1))) &&
50675       isa<ConstantSDNode>(Scale) &&
50676       BasePtr.getScalarValueSizeInBits() == Index.getScalarValueSizeInBits()) {
50677     unsigned ShiftAmt =
50678         Index.getOpcode() == ISD::ADD ? 1 : Index.getConstantOperandVal(1);
50679     uint64_t ScaleAmt = cast<ConstantSDNode>(Scale)->getZExtValue();
50680     uint64_t NewScaleAmt = ScaleAmt * (1ULL << ShiftAmt);
50681     if (isPowerOf2_64(NewScaleAmt) && NewScaleAmt <= 8) {
50682       SDValue NewIndex = Index.getOperand(0);
50683       SDValue NewScale =
50684           DAG.getTargetConstant(NewScaleAmt, SDLoc(N), Scale.getValueType());
50685       if (N->getOpcode() == X86ISD::MGATHER)
50686         return getAVX2GatherNode(N->getOpcode(), SDValue(N, 0), DAG,
50687                                  MemOp->getOperand(1), Mask,
50688                                  MemOp->getBasePtr(), NewIndex, NewScale,
50689                                  MemOp->getChain(), Subtarget);
50690       if (N->getOpcode() == X86ISD::MSCATTER)
50691         return getScatterNode(N->getOpcode(), SDValue(N, 0), DAG,
50692                               MemOp->getOperand(1), Mask, MemOp->getBasePtr(),
50693                               NewIndex, NewScale, MemOp->getChain(), Subtarget);
50694     }
50695   }
50696 
50697   // With vector masks we only demand the upper bit of the mask.
50698   if (Mask.getScalarValueSizeInBits() != 1) {
50699     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50700     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
50701     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
50702       if (N->getOpcode() != ISD::DELETED_NODE)
50703         DCI.AddToWorklist(N);
50704       return SDValue(N, 0);
50705     }
50706   }
50707 
50708   return SDValue();
50709 }
50710 
50711 static SDValue rebuildGatherScatter(MaskedGatherScatterSDNode *GorS,
50712                                     SDValue Index, SDValue Base, SDValue Scale,
50713                                     SelectionDAG &DAG) {
50714   SDLoc DL(GorS);
50715 
50716   if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
50717     SDValue Ops[] = { Gather->getChain(), Gather->getPassThru(),
50718                       Gather->getMask(), Base, Index, Scale } ;
50719     return DAG.getMaskedGather(Gather->getVTList(),
50720                                Gather->getMemoryVT(), DL, Ops,
50721                                Gather->getMemOperand(),
50722                                Gather->getIndexType(),
50723                                Gather->getExtensionType());
50724   }
50725   auto *Scatter = cast<MaskedScatterSDNode>(GorS);
50726   SDValue Ops[] = { Scatter->getChain(), Scatter->getValue(),
50727                     Scatter->getMask(), Base, Index, Scale };
50728   return DAG.getMaskedScatter(Scatter->getVTList(),
50729                               Scatter->getMemoryVT(), DL,
50730                               Ops, Scatter->getMemOperand(),
50731                               Scatter->getIndexType(),
50732                               Scatter->isTruncatingStore());
50733 }
50734 
50735 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
50736                                     TargetLowering::DAGCombinerInfo &DCI) {
50737   SDLoc DL(N);
50738   auto *GorS = cast<MaskedGatherScatterSDNode>(N);
50739   SDValue Index = GorS->getIndex();
50740   SDValue Base = GorS->getBasePtr();
50741   SDValue Scale = GorS->getScale();
50742 
50743   if (DCI.isBeforeLegalize()) {
50744     unsigned IndexWidth = Index.getScalarValueSizeInBits();
50745 
50746     // Shrink constant indices if they are larger than 32-bits.
50747     // Only do this before legalize types since v2i64 could become v2i32.
50748     // FIXME: We could check that the type is legal if we're after legalize
50749     // types, but then we would need to construct test cases where that happens.
50750     // FIXME: We could support more than just constant vectors, but we need to
50751     // careful with costing. A truncate that can be optimized out would be fine.
50752     // Otherwise we might only want to create a truncate if it avoids a split.
50753     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
50754       if (BV->isConstant() && IndexWidth > 32 &&
50755           DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
50756         EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
50757         Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
50758         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
50759       }
50760     }
50761 
50762     // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
50763     // there are sufficient sign bits. Only do this before legalize types to
50764     // avoid creating illegal types in truncate.
50765     if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
50766          Index.getOpcode() == ISD::ZERO_EXTEND) &&
50767         IndexWidth > 32 &&
50768         Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
50769         DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
50770       EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
50771       Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
50772       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
50773     }
50774   }
50775 
50776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50777   EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
50778   // Try to move splat constant adders from the index operand to the base
50779   // pointer operand. Taking care to multiply by the scale. We can only do
50780   // this when index element type is the same as the pointer type.
50781   // Otherwise we need to be sure the math doesn't wrap before the scale.
50782   if (Index.getOpcode() == ISD::ADD &&
50783       Index.getValueType().getVectorElementType() == PtrVT &&
50784       isa<ConstantSDNode>(Scale)) {
50785     uint64_t ScaleAmt = cast<ConstantSDNode>(Scale)->getZExtValue();
50786     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index.getOperand(1))) {
50787       BitVector UndefElts;
50788       if (ConstantSDNode *C = BV->getConstantSplatNode(&UndefElts)) {
50789         // FIXME: Allow non-constant?
50790         if (UndefElts.none()) {
50791           // Apply the scale.
50792           APInt Adder = C->getAPIntValue() * ScaleAmt;
50793           // Add it to the existing base.
50794           Base = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
50795                              DAG.getConstant(Adder, DL, PtrVT));
50796           Index = Index.getOperand(0);
50797           return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
50798         }
50799       }
50800 
50801       // It's also possible base is just a constant. In that case, just
50802       // replace it with 0 and move the displacement into the index.
50803       if (BV->isConstant() && isa<ConstantSDNode>(Base) &&
50804           isOneConstant(Scale)) {
50805         SDValue Splat = DAG.getSplatBuildVector(Index.getValueType(), DL, Base);
50806         // Combine the constant build_vector and the constant base.
50807         Splat = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
50808                             Index.getOperand(1), Splat);
50809         // Add to the LHS of the original Index add.
50810         Index = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
50811                             Index.getOperand(0), Splat);
50812         Base = DAG.getConstant(0, DL, Base.getValueType());
50813         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
50814       }
50815     }
50816   }
50817 
50818   if (DCI.isBeforeLegalizeOps()) {
50819     unsigned IndexWidth = Index.getScalarValueSizeInBits();
50820 
50821     // Make sure the index is either i32 or i64
50822     if (IndexWidth != 32 && IndexWidth != 64) {
50823       MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
50824       EVT IndexVT = Index.getValueType().changeVectorElementType(EltVT);
50825       Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
50826       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
50827     }
50828   }
50829 
50830   // With vector masks we only demand the upper bit of the mask.
50831   SDValue Mask = GorS->getMask();
50832   if (Mask.getScalarValueSizeInBits() != 1) {
50833     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50834     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
50835     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
50836       if (N->getOpcode() != ISD::DELETED_NODE)
50837         DCI.AddToWorklist(N);
50838       return SDValue(N, 0);
50839     }
50840   }
50841 
50842   return SDValue();
50843 }
50844 
50845 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
50846 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
50847                                const X86Subtarget &Subtarget) {
50848   SDLoc DL(N);
50849   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
50850   SDValue EFLAGS = N->getOperand(1);
50851 
50852   // Try to simplify the EFLAGS and condition code operands.
50853   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
50854     return getSETCC(CC, Flags, DL, DAG);
50855 
50856   return SDValue();
50857 }
50858 
50859 /// Optimize branch condition evaluation.
50860 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
50861                              const X86Subtarget &Subtarget) {
50862   SDLoc DL(N);
50863   SDValue EFLAGS = N->getOperand(3);
50864   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
50865 
50866   // Try to simplify the EFLAGS and condition code operands.
50867   // Make sure to not keep references to operands, as combineSetCCEFLAGS can
50868   // RAUW them under us.
50869   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
50870     SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
50871     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
50872                        N->getOperand(1), Cond, Flags);
50873   }
50874 
50875   return SDValue();
50876 }
50877 
50878 // TODO: Could we move this to DAGCombine?
50879 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
50880                                                   SelectionDAG &DAG) {
50881   // Take advantage of vector comparisons (etc.) producing 0 or -1 in each lane
50882   // to optimize away operation when it's from a constant.
50883   //
50884   // The general transformation is:
50885   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
50886   //       AND(VECTOR_CMP(x,y), constant2)
50887   //    constant2 = UNARYOP(constant)
50888 
50889   // Early exit if this isn't a vector operation, the operand of the
50890   // unary operation isn't a bitwise AND, or if the sizes of the operations
50891   // aren't the same.
50892   EVT VT = N->getValueType(0);
50893   bool IsStrict = N->isStrictFPOpcode();
50894   unsigned NumEltBits = VT.getScalarSizeInBits();
50895   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
50896   if (!VT.isVector() || Op0.getOpcode() != ISD::AND ||
50897       DAG.ComputeNumSignBits(Op0.getOperand(0)) != NumEltBits ||
50898       VT.getSizeInBits() != Op0.getValueSizeInBits())
50899     return SDValue();
50900 
50901   // Now check that the other operand of the AND is a constant. We could
50902   // make the transformation for non-constant splats as well, but it's unclear
50903   // that would be a benefit as it would not eliminate any operations, just
50904   // perform one more step in scalar code before moving to the vector unit.
50905   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
50906     // Bail out if the vector isn't a constant.
50907     if (!BV->isConstant())
50908       return SDValue();
50909 
50910     // Everything checks out. Build up the new and improved node.
50911     SDLoc DL(N);
50912     EVT IntVT = BV->getValueType(0);
50913     // Create a new constant of the appropriate type for the transformed
50914     // DAG.
50915     SDValue SourceConst;
50916     if (IsStrict)
50917       SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
50918                                 {N->getOperand(0), SDValue(BV, 0)});
50919     else
50920       SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
50921     // The AND node needs bitcasts to/from an integer vector type around it.
50922     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
50923     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
50924                                  MaskConst);
50925     SDValue Res = DAG.getBitcast(VT, NewAnd);
50926     if (IsStrict)
50927       return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
50928     return Res;
50929   }
50930 
50931   return SDValue();
50932 }
50933 
50934 /// If we are converting a value to floating-point, try to replace scalar
50935 /// truncate of an extracted vector element with a bitcast. This tries to keep
50936 /// the sequence on XMM registers rather than moving between vector and GPRs.
50937 static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
50938   // TODO: This is currently only used by combineSIntToFP, but it is generalized
50939   //       to allow being called by any similar cast opcode.
50940   // TODO: Consider merging this into lowering: vectorizeExtractedCast().
50941   SDValue Trunc = N->getOperand(0);
50942   if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
50943     return SDValue();
50944 
50945   SDValue ExtElt = Trunc.getOperand(0);
50946   if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
50947       !isNullConstant(ExtElt.getOperand(1)))
50948     return SDValue();
50949 
50950   EVT TruncVT = Trunc.getValueType();
50951   EVT SrcVT = ExtElt.getValueType();
50952   unsigned DestWidth = TruncVT.getSizeInBits();
50953   unsigned SrcWidth = SrcVT.getSizeInBits();
50954   if (SrcWidth % DestWidth != 0)
50955     return SDValue();
50956 
50957   // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
50958   EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
50959   unsigned VecWidth = SrcVecVT.getSizeInBits();
50960   unsigned NumElts = VecWidth / DestWidth;
50961   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
50962   SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
50963   SDLoc DL(N);
50964   SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
50965                                   BitcastVec, ExtElt.getOperand(1));
50966   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
50967 }
50968 
50969 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
50970                                const X86Subtarget &Subtarget) {
50971   bool IsStrict = N->isStrictFPOpcode();
50972   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
50973   EVT VT = N->getValueType(0);
50974   EVT InVT = Op0.getValueType();
50975 
50976   // UINT_TO_FP(vXi1~15)  -> UINT_TO_FP(ZEXT(vXi1~15  to vXi16))
50977   // UINT_TO_FP(vXi17~31) -> UINT_TO_FP(ZEXT(vXi17~31 to vXi32))
50978   // UINT_TO_FP(vXi33~63) -> UINT_TO_FP(ZEXT(vXi33~63 to vXi64))
50979   if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
50980     unsigned ScalarSize = InVT.getScalarSizeInBits();
50981     if (ScalarSize == 16 || ScalarSize == 32 || ScalarSize >= 64)
50982       return SDValue();
50983     SDLoc dl(N);
50984     EVT DstVT = EVT::getVectorVT(*DAG.getContext(),
50985                                  ScalarSize < 16   ? MVT::i16
50986                                  : ScalarSize < 32 ? MVT::i32
50987                                                    : MVT::i64,
50988                                  InVT.getVectorNumElements());
50989     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
50990     if (IsStrict)
50991       return DAG.getNode(ISD::STRICT_UINT_TO_FP, dl, {VT, MVT::Other},
50992                          {N->getOperand(0), P});
50993     return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
50994   }
50995 
50996   // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
50997   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
50998   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
50999   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
51000       VT.getScalarType() != MVT::f16) {
51001     SDLoc dl(N);
51002     EVT DstVT = InVT.changeVectorElementType(MVT::i32);
51003     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
51004 
51005     // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
51006     if (IsStrict)
51007       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
51008                          {N->getOperand(0), P});
51009     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
51010   }
51011 
51012   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
51013   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
51014   // the optimization here.
51015   if (DAG.SignBitIsZero(Op0)) {
51016     if (IsStrict)
51017       return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
51018                          {N->getOperand(0), Op0});
51019     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
51020   }
51021 
51022   return SDValue();
51023 }
51024 
51025 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
51026                                TargetLowering::DAGCombinerInfo &DCI,
51027                                const X86Subtarget &Subtarget) {
51028   // First try to optimize away the conversion entirely when it's
51029   // conditionally from a constant. Vectors only.
51030   bool IsStrict = N->isStrictFPOpcode();
51031   if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
51032     return Res;
51033 
51034   // Now move on to more general possibilities.
51035   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
51036   EVT VT = N->getValueType(0);
51037   EVT InVT = Op0.getValueType();
51038 
51039   // SINT_TO_FP(vXi1~15)  -> SINT_TO_FP(SEXT(vXi1~15  to vXi16))
51040   // SINT_TO_FP(vXi17~31) -> SINT_TO_FP(SEXT(vXi17~31 to vXi32))
51041   // SINT_TO_FP(vXi33~63) -> SINT_TO_FP(SEXT(vXi33~63 to vXi64))
51042   if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
51043     unsigned ScalarSize = InVT.getScalarSizeInBits();
51044     if (ScalarSize == 16 || ScalarSize == 32 || ScalarSize >= 64)
51045       return SDValue();
51046     SDLoc dl(N);
51047     EVT DstVT = EVT::getVectorVT(*DAG.getContext(),
51048                                  ScalarSize < 16   ? MVT::i16
51049                                  : ScalarSize < 32 ? MVT::i32
51050                                                    : MVT::i64,
51051                                  InVT.getVectorNumElements());
51052     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
51053     if (IsStrict)
51054       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
51055                          {N->getOperand(0), P});
51056     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
51057   }
51058 
51059   // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
51060   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
51061   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
51062   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
51063       VT.getScalarType() != MVT::f16) {
51064     SDLoc dl(N);
51065     EVT DstVT = InVT.changeVectorElementType(MVT::i32);
51066     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
51067     if (IsStrict)
51068       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
51069                          {N->getOperand(0), P});
51070     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
51071   }
51072 
51073   // Without AVX512DQ we only support i64 to float scalar conversion. For both
51074   // vectors and scalars, see if we know that the upper bits are all the sign
51075   // bit, in which case we can truncate the input to i32 and convert from that.
51076   if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
51077     unsigned BitWidth = InVT.getScalarSizeInBits();
51078     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
51079     if (NumSignBits >= (BitWidth - 31)) {
51080       EVT TruncVT = MVT::i32;
51081       if (InVT.isVector())
51082         TruncVT = InVT.changeVectorElementType(TruncVT);
51083       SDLoc dl(N);
51084       if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
51085         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
51086         if (IsStrict)
51087           return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
51088                              {N->getOperand(0), Trunc});
51089         return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
51090       }
51091       // If we're after legalize and the type is v2i32 we need to shuffle and
51092       // use CVTSI2P.
51093       assert(InVT == MVT::v2i64 && "Unexpected VT!");
51094       SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
51095       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
51096                                           { 0, 2, -1, -1 });
51097       if (IsStrict)
51098         return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
51099                            {N->getOperand(0), Shuf});
51100       return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
51101     }
51102   }
51103 
51104   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
51105   // a 32-bit target where SSE doesn't support i64->FP operations.
51106   if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
51107       Op0.getOpcode() == ISD::LOAD) {
51108     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
51109 
51110     // This transformation is not supported if the result type is f16 or f128.
51111     if (VT == MVT::f16 || VT == MVT::f128)
51112       return SDValue();
51113 
51114     // If we have AVX512DQ we can use packed conversion instructions unless
51115     // the VT is f80.
51116     if (Subtarget.hasDQI() && VT != MVT::f80)
51117       return SDValue();
51118 
51119     if (Ld->isSimple() && !VT.isVector() && ISD::isNormalLoad(Op0.getNode()) &&
51120         Op0.hasOneUse() && !Subtarget.is64Bit() && InVT == MVT::i64) {
51121       std::pair<SDValue, SDValue> Tmp =
51122           Subtarget.getTargetLowering()->BuildFILD(
51123               VT, InVT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(),
51124               Ld->getPointerInfo(), Ld->getOriginalAlign(), DAG);
51125       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
51126       return Tmp.first;
51127     }
51128   }
51129 
51130   if (IsStrict)
51131     return SDValue();
51132 
51133   if (SDValue V = combineToFPTruncExtElt(N, DAG))
51134     return V;
51135 
51136   return SDValue();
51137 }
51138 
51139 static bool needCarryOrOverflowFlag(SDValue Flags) {
51140   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
51141 
51142   for (const SDNode *User : Flags->uses()) {
51143     X86::CondCode CC;
51144     switch (User->getOpcode()) {
51145     default:
51146       // Be conservative.
51147       return true;
51148     case X86ISD::SETCC:
51149     case X86ISD::SETCC_CARRY:
51150       CC = (X86::CondCode)User->getConstantOperandVal(0);
51151       break;
51152     case X86ISD::BRCOND:
51153       CC = (X86::CondCode)User->getConstantOperandVal(2);
51154       break;
51155     case X86ISD::CMOV:
51156       CC = (X86::CondCode)User->getConstantOperandVal(2);
51157       break;
51158     }
51159 
51160     switch (CC) {
51161     default: break;
51162     case X86::COND_A: case X86::COND_AE:
51163     case X86::COND_B: case X86::COND_BE:
51164     case X86::COND_O: case X86::COND_NO:
51165     case X86::COND_G: case X86::COND_GE:
51166     case X86::COND_L: case X86::COND_LE:
51167       return true;
51168     }
51169   }
51170 
51171   return false;
51172 }
51173 
51174 static bool onlyZeroFlagUsed(SDValue Flags) {
51175   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
51176 
51177   for (const SDNode *User : Flags->uses()) {
51178     unsigned CCOpNo;
51179     switch (User->getOpcode()) {
51180     default:
51181       // Be conservative.
51182       return false;
51183     case X86ISD::SETCC:       CCOpNo = 0; break;
51184     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
51185     case X86ISD::BRCOND:      CCOpNo = 2; break;
51186     case X86ISD::CMOV:        CCOpNo = 2; break;
51187     }
51188 
51189     X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
51190     if (CC != X86::COND_E && CC != X86::COND_NE)
51191       return false;
51192   }
51193 
51194   return true;
51195 }
51196 
51197 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
51198   // Only handle test patterns.
51199   if (!isNullConstant(N->getOperand(1)))
51200     return SDValue();
51201 
51202   // If we have a CMP of a truncated binop, see if we can make a smaller binop
51203   // and use its flags directly.
51204   // TODO: Maybe we should try promoting compares that only use the zero flag
51205   // first if we can prove the upper bits with computeKnownBits?
51206   SDLoc dl(N);
51207   SDValue Op = N->getOperand(0);
51208   EVT VT = Op.getValueType();
51209 
51210   // If we have a constant logical shift that's only used in a comparison
51211   // against zero turn it into an equivalent AND. This allows turning it into
51212   // a TEST instruction later.
51213   if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
51214       Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
51215       onlyZeroFlagUsed(SDValue(N, 0))) {
51216     unsigned BitWidth = VT.getSizeInBits();
51217     const APInt &ShAmt = Op.getConstantOperandAPInt(1);
51218     if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
51219       unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
51220       APInt Mask = Op.getOpcode() == ISD::SRL
51221                        ? APInt::getHighBitsSet(BitWidth, MaskBits)
51222                        : APInt::getLowBitsSet(BitWidth, MaskBits);
51223       if (Mask.isSignedIntN(32)) {
51224         Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
51225                          DAG.getConstant(Mask, dl, VT));
51226         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
51227                            DAG.getConstant(0, dl, VT));
51228       }
51229     }
51230   }
51231 
51232   // Look for a truncate.
51233   if (Op.getOpcode() != ISD::TRUNCATE)
51234     return SDValue();
51235 
51236   SDValue Trunc = Op;
51237   Op = Op.getOperand(0);
51238 
51239   // See if we can compare with zero against the truncation source,
51240   // which should help using the Z flag from many ops. Only do this for
51241   // i32 truncated op to prevent partial-reg compares of promoted ops.
51242   EVT OpVT = Op.getValueType();
51243   APInt UpperBits =
51244       APInt::getBitsSetFrom(OpVT.getSizeInBits(), VT.getSizeInBits());
51245   if (OpVT == MVT::i32 && DAG.MaskedValueIsZero(Op, UpperBits) &&
51246       onlyZeroFlagUsed(SDValue(N, 0))) {
51247     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
51248                        DAG.getConstant(0, dl, OpVT));
51249   }
51250 
51251   // After this the truncate and arithmetic op must have a single use.
51252   if (!Trunc.hasOneUse() || !Op.hasOneUse())
51253       return SDValue();
51254 
51255   unsigned NewOpc;
51256   switch (Op.getOpcode()) {
51257   default: return SDValue();
51258   case ISD::AND:
51259     // Skip and with constant. We have special handling for and with immediate
51260     // during isel to generate test instructions.
51261     if (isa<ConstantSDNode>(Op.getOperand(1)))
51262       return SDValue();
51263     NewOpc = X86ISD::AND;
51264     break;
51265   case ISD::OR:  NewOpc = X86ISD::OR;  break;
51266   case ISD::XOR: NewOpc = X86ISD::XOR; break;
51267   case ISD::ADD:
51268     // If the carry or overflow flag is used, we can't truncate.
51269     if (needCarryOrOverflowFlag(SDValue(N, 0)))
51270       return SDValue();
51271     NewOpc = X86ISD::ADD;
51272     break;
51273   case ISD::SUB:
51274     // If the carry or overflow flag is used, we can't truncate.
51275     if (needCarryOrOverflowFlag(SDValue(N, 0)))
51276       return SDValue();
51277     NewOpc = X86ISD::SUB;
51278     break;
51279   }
51280 
51281   // We found an op we can narrow. Truncate its inputs.
51282   SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
51283   SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
51284 
51285   // Use a X86 specific opcode to avoid DAG combine messing with it.
51286   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
51287   Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
51288 
51289   // For AND, keep a CMP so that we can match the test pattern.
51290   if (NewOpc == X86ISD::AND)
51291     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
51292                        DAG.getConstant(0, dl, VT));
51293 
51294   // Return the flags.
51295   return Op.getValue(1);
51296 }
51297 
51298 static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
51299                                 TargetLowering::DAGCombinerInfo &DCI) {
51300   assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&
51301          "Expected X86ISD::ADD or X86ISD::SUB");
51302 
51303   SDLoc DL(N);
51304   SDValue LHS = N->getOperand(0);
51305   SDValue RHS = N->getOperand(1);
51306   MVT VT = LHS.getSimpleValueType();
51307   unsigned GenericOpc = X86ISD::ADD == N->getOpcode() ? ISD::ADD : ISD::SUB;
51308 
51309   // If we don't use the flag result, simplify back to a generic ADD/SUB.
51310   if (!N->hasAnyUseOfValue(1)) {
51311     SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
51312     return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
51313   }
51314 
51315   // Fold any similar generic ADD/SUB opcodes to reuse this node.
51316   auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
51317     SDValue Ops[] = {N0, N1};
51318     SDVTList VTs = DAG.getVTList(N->getValueType(0));
51319     if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
51320       SDValue Op(N, 0);
51321       if (Negate)
51322         Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
51323       DCI.CombineTo(GenericAddSub, Op);
51324     }
51325   };
51326   MatchGeneric(LHS, RHS, false);
51327   MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
51328 
51329   return SDValue();
51330 }
51331 
51332 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
51333   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
51334     MVT VT = N->getSimpleValueType(0);
51335     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
51336     return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs,
51337                        N->getOperand(0), N->getOperand(1),
51338                        Flags);
51339   }
51340 
51341   // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
51342   // iff the flag result is dead.
51343   SDValue Op0 = N->getOperand(0);
51344   SDValue Op1 = N->getOperand(1);
51345   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op1) &&
51346       !N->hasAnyUseOfValue(1))
51347     return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), Op0.getOperand(0),
51348                        Op0.getOperand(1), N->getOperand(2));
51349 
51350   return SDValue();
51351 }
51352 
51353 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
51354 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
51355                           TargetLowering::DAGCombinerInfo &DCI) {
51356   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
51357   // the result is either zero or one (depending on the input carry bit).
51358   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
51359   if (X86::isZeroNode(N->getOperand(0)) &&
51360       X86::isZeroNode(N->getOperand(1)) &&
51361       // We don't have a good way to replace an EFLAGS use, so only do this when
51362       // dead right now.
51363       SDValue(N, 1).use_empty()) {
51364     SDLoc DL(N);
51365     EVT VT = N->getValueType(0);
51366     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
51367     SDValue Res1 =
51368         DAG.getNode(ISD::AND, DL, VT,
51369                     DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51370                                 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51371                                 N->getOperand(2)),
51372                     DAG.getConstant(1, DL, VT));
51373     return DCI.CombineTo(N, Res1, CarryOut);
51374   }
51375 
51376   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
51377     MVT VT = N->getSimpleValueType(0);
51378     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
51379     return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs,
51380                        N->getOperand(0), N->getOperand(1),
51381                        Flags);
51382   }
51383 
51384   return SDValue();
51385 }
51386 
51387 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
51388 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
51389 /// with CMP+{ADC, SBB}.
51390 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
51391   bool IsSub = N->getOpcode() == ISD::SUB;
51392   SDValue X = N->getOperand(0);
51393   SDValue Y = N->getOperand(1);
51394 
51395   // If this is an add, canonicalize a zext operand to the RHS.
51396   // TODO: Incomplete? What if both sides are zexts?
51397   if (!IsSub && X.getOpcode() == ISD::ZERO_EXTEND &&
51398       Y.getOpcode() != ISD::ZERO_EXTEND)
51399     std::swap(X, Y);
51400 
51401   // Look through a one-use zext.
51402   bool PeekedThroughZext = false;
51403   if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse()) {
51404     Y = Y.getOperand(0);
51405     PeekedThroughZext = true;
51406   }
51407 
51408   // If this is an add, canonicalize a setcc operand to the RHS.
51409   // TODO: Incomplete? What if both sides are setcc?
51410   // TODO: Should we allow peeking through a zext of the other operand?
51411   if (!IsSub && !PeekedThroughZext && X.getOpcode() == X86ISD::SETCC &&
51412       Y.getOpcode() != X86ISD::SETCC)
51413     std::swap(X, Y);
51414 
51415   if (Y.getOpcode() != X86ISD::SETCC || !Y.hasOneUse())
51416     return SDValue();
51417 
51418   SDLoc DL(N);
51419   EVT VT = N->getValueType(0);
51420   X86::CondCode CC = (X86::CondCode)Y.getConstantOperandVal(0);
51421 
51422   // If X is -1 or 0, then we have an opportunity to avoid constants required in
51423   // the general case below.
51424   auto *ConstantX = dyn_cast<ConstantSDNode>(X);
51425   if (ConstantX) {
51426     if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnes()) ||
51427         (IsSub && CC == X86::COND_B && ConstantX->isZero())) {
51428       // This is a complicated way to get -1 or 0 from the carry flag:
51429       // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
51430       //  0 - SETB  -->  0 -  (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
51431       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51432                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51433                          Y.getOperand(1));
51434     }
51435 
51436     if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnes()) ||
51437         (IsSub && CC == X86::COND_A && ConstantX->isZero())) {
51438       SDValue EFLAGS = Y->getOperand(1);
51439       if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
51440           EFLAGS.getValueType().isInteger() &&
51441           !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51442         // Swap the operands of a SUB, and we have the same pattern as above.
51443         // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
51444         //  0 - SETA  (SUB A, B) -->  0 - SETB  (SUB B, A) --> SUB + SBB
51445         SDValue NewSub = DAG.getNode(
51446             X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
51447             EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51448         SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
51449         return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51450                            DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51451                            NewEFLAGS);
51452       }
51453     }
51454   }
51455 
51456   if (CC == X86::COND_B) {
51457     // X + SETB Z --> adc X, 0
51458     // X - SETB Z --> sbb X, 0
51459     return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
51460                        DAG.getVTList(VT, MVT::i32), X,
51461                        DAG.getConstant(0, DL, VT), Y.getOperand(1));
51462   }
51463 
51464   if (CC == X86::COND_A) {
51465     SDValue EFLAGS = Y.getOperand(1);
51466     // Try to convert COND_A into COND_B in an attempt to facilitate
51467     // materializing "setb reg".
51468     //
51469     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
51470     // cannot take an immediate as its first operand.
51471     //
51472     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
51473         EFLAGS.getValueType().isInteger() &&
51474         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51475       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
51476                                    EFLAGS.getNode()->getVTList(),
51477                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51478       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
51479       return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
51480                          DAG.getVTList(VT, MVT::i32), X,
51481                          DAG.getConstant(0, DL, VT), NewEFLAGS);
51482     }
51483   }
51484 
51485   if (CC == X86::COND_AE) {
51486     // X + SETAE --> sbb X, -1
51487     // X - SETAE --> adc X, -1
51488     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
51489                        DAG.getVTList(VT, MVT::i32), X,
51490                        DAG.getConstant(-1, DL, VT), Y.getOperand(1));
51491   }
51492 
51493   if (CC == X86::COND_BE) {
51494     // X + SETBE --> sbb X, -1
51495     // X - SETBE --> adc X, -1
51496     SDValue EFLAGS = Y.getOperand(1);
51497     // Try to convert COND_BE into COND_AE in an attempt to facilitate
51498     // materializing "setae reg".
51499     //
51500     // Do not flip "e <= c", where "c" is a constant, because Cmp instruction
51501     // cannot take an immediate as its first operand.
51502     //
51503     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
51504         EFLAGS.getValueType().isInteger() &&
51505         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51506       SDValue NewSub = DAG.getNode(
51507           X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
51508           EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51509       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
51510       return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
51511                          DAG.getVTList(VT, MVT::i32), X,
51512                          DAG.getConstant(-1, DL, VT), NewEFLAGS);
51513     }
51514   }
51515 
51516   if (CC != X86::COND_E && CC != X86::COND_NE)
51517     return SDValue();
51518 
51519   SDValue Cmp = Y.getOperand(1);
51520   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
51521       !X86::isZeroNode(Cmp.getOperand(1)) ||
51522       !Cmp.getOperand(0).getValueType().isInteger())
51523     return SDValue();
51524 
51525   SDValue Z = Cmp.getOperand(0);
51526   EVT ZVT = Z.getValueType();
51527 
51528   // If X is -1 or 0, then we have an opportunity to avoid constants required in
51529   // the general case below.
51530   if (ConstantX) {
51531     // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
51532     // fake operands:
51533     //  0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
51534     // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
51535     if ((IsSub && CC == X86::COND_NE && ConstantX->isZero()) ||
51536         (!IsSub && CC == X86::COND_E && ConstantX->isAllOnes())) {
51537       SDValue Zero = DAG.getConstant(0, DL, ZVT);
51538       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51539       SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
51540       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51541                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51542                          SDValue(Neg.getNode(), 1));
51543     }
51544 
51545     // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
51546     // with fake operands:
51547     //  0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
51548     // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
51549     if ((IsSub && CC == X86::COND_E && ConstantX->isZero()) ||
51550         (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnes())) {
51551       SDValue One = DAG.getConstant(1, DL, ZVT);
51552       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51553       SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
51554       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51555                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51556                          Cmp1.getValue(1));
51557     }
51558   }
51559 
51560   // (cmp Z, 1) sets the carry flag if Z is 0.
51561   SDValue One = DAG.getConstant(1, DL, ZVT);
51562   SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51563   SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
51564 
51565   // Add the flags type for ADC/SBB nodes.
51566   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
51567 
51568   // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
51569   // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
51570   if (CC == X86::COND_NE)
51571     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
51572                        DAG.getConstant(-1ULL, DL, VT), Cmp1.getValue(1));
51573 
51574   // X - (Z == 0) --> sub X, (zext(sete  Z, 0)) --> sbb X, 0, (cmp Z, 1)
51575   // X + (Z == 0) --> add X, (zext(sete  Z, 0)) --> adc X, 0, (cmp Z, 1)
51576   return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
51577                      DAG.getConstant(0, DL, VT), Cmp1.getValue(1));
51578 }
51579 
51580 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
51581                             const SDLoc &DL, EVT VT,
51582                             const X86Subtarget &Subtarget) {
51583   // Example of pattern we try to detect:
51584   // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
51585   //(add (build_vector (extract_elt t, 0),
51586   //                   (extract_elt t, 2),
51587   //                   (extract_elt t, 4),
51588   //                   (extract_elt t, 6)),
51589   //     (build_vector (extract_elt t, 1),
51590   //                   (extract_elt t, 3),
51591   //                   (extract_elt t, 5),
51592   //                   (extract_elt t, 7)))
51593 
51594   if (!Subtarget.hasSSE2())
51595     return SDValue();
51596 
51597   if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
51598       Op1.getOpcode() != ISD::BUILD_VECTOR)
51599     return SDValue();
51600 
51601   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
51602       VT.getVectorNumElements() < 4 ||
51603       !isPowerOf2_32(VT.getVectorNumElements()))
51604     return SDValue();
51605 
51606   // Check if one of Op0,Op1 is of the form:
51607   // (build_vector (extract_elt Mul, 0),
51608   //               (extract_elt Mul, 2),
51609   //               (extract_elt Mul, 4),
51610   //                   ...
51611   // the other is of the form:
51612   // (build_vector (extract_elt Mul, 1),
51613   //               (extract_elt Mul, 3),
51614   //               (extract_elt Mul, 5),
51615   //                   ...
51616   // and identify Mul.
51617   SDValue Mul;
51618   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
51619     SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
51620             Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
51621     // TODO: Be more tolerant to undefs.
51622     if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51623         Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51624         Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51625         Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
51626       return SDValue();
51627     auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
51628     auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
51629     auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
51630     auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
51631     if (!Const0L || !Const1L || !Const0H || !Const1H)
51632       return SDValue();
51633     unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
51634              Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
51635     // Commutativity of mul allows factors of a product to reorder.
51636     if (Idx0L > Idx1L)
51637       std::swap(Idx0L, Idx1L);
51638     if (Idx0H > Idx1H)
51639       std::swap(Idx0H, Idx1H);
51640     // Commutativity of add allows pairs of factors to reorder.
51641     if (Idx0L > Idx0H) {
51642       std::swap(Idx0L, Idx0H);
51643       std::swap(Idx1L, Idx1H);
51644     }
51645     if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
51646         Idx1H != 2 * i + 3)
51647       return SDValue();
51648     if (!Mul) {
51649       // First time an extract_elt's source vector is visited. Must be a MUL
51650       // with 2X number of vector elements than the BUILD_VECTOR.
51651       // Both extracts must be from same MUL.
51652       Mul = Op0L->getOperand(0);
51653       if (Mul->getOpcode() != ISD::MUL ||
51654           Mul.getValueType().getVectorNumElements() != 2 * e)
51655         return SDValue();
51656     }
51657     // Check that the extract is from the same MUL previously seen.
51658     if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
51659         Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
51660       return SDValue();
51661   }
51662 
51663   // Check if the Mul source can be safely shrunk.
51664   ShrinkMode Mode;
51665   if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
51666       Mode == ShrinkMode::MULU16)
51667     return SDValue();
51668 
51669   EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
51670                                  VT.getVectorNumElements() * 2);
51671   SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(0));
51672   SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(1));
51673 
51674   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
51675                          ArrayRef<SDValue> Ops) {
51676     EVT InVT = Ops[0].getValueType();
51677     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
51678     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
51679                                  InVT.getVectorNumElements() / 2);
51680     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
51681   };
51682   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { N0, N1 }, PMADDBuilder);
51683 }
51684 
51685 // Attempt to turn this pattern into PMADDWD.
51686 // (add (mul (sext (build_vector)), (sext (build_vector))),
51687 //      (mul (sext (build_vector)), (sext (build_vector)))
51688 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
51689                               const SDLoc &DL, EVT VT,
51690                               const X86Subtarget &Subtarget) {
51691   if (!Subtarget.hasSSE2())
51692     return SDValue();
51693 
51694   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
51695     return SDValue();
51696 
51697   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
51698       VT.getVectorNumElements() < 4 ||
51699       !isPowerOf2_32(VT.getVectorNumElements()))
51700     return SDValue();
51701 
51702   SDValue N00 = N0.getOperand(0);
51703   SDValue N01 = N0.getOperand(1);
51704   SDValue N10 = N1.getOperand(0);
51705   SDValue N11 = N1.getOperand(1);
51706 
51707   // All inputs need to be sign extends.
51708   // TODO: Support ZERO_EXTEND from known positive?
51709   if (N00.getOpcode() != ISD::SIGN_EXTEND ||
51710       N01.getOpcode() != ISD::SIGN_EXTEND ||
51711       N10.getOpcode() != ISD::SIGN_EXTEND ||
51712       N11.getOpcode() != ISD::SIGN_EXTEND)
51713     return SDValue();
51714 
51715   // Peek through the extends.
51716   N00 = N00.getOperand(0);
51717   N01 = N01.getOperand(0);
51718   N10 = N10.getOperand(0);
51719   N11 = N11.getOperand(0);
51720 
51721   // Must be extending from vXi16.
51722   EVT InVT = N00.getValueType();
51723   if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
51724       N10.getValueType() != InVT || N11.getValueType() != InVT)
51725     return SDValue();
51726 
51727   // All inputs should be build_vectors.
51728   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
51729       N01.getOpcode() != ISD::BUILD_VECTOR ||
51730       N10.getOpcode() != ISD::BUILD_VECTOR ||
51731       N11.getOpcode() != ISD::BUILD_VECTOR)
51732     return SDValue();
51733 
51734   // For each element, we need to ensure we have an odd element from one vector
51735   // multiplied by the odd element of another vector and the even element from
51736   // one of the same vectors being multiplied by the even element from the
51737   // other vector. So we need to make sure for each element i, this operator
51738   // is being performed:
51739   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
51740   SDValue In0, In1;
51741   for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
51742     SDValue N00Elt = N00.getOperand(i);
51743     SDValue N01Elt = N01.getOperand(i);
51744     SDValue N10Elt = N10.getOperand(i);
51745     SDValue N11Elt = N11.getOperand(i);
51746     // TODO: Be more tolerant to undefs.
51747     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51748         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51749         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51750         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
51751       return SDValue();
51752     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
51753     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
51754     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
51755     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
51756     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
51757       return SDValue();
51758     unsigned IdxN00 = ConstN00Elt->getZExtValue();
51759     unsigned IdxN01 = ConstN01Elt->getZExtValue();
51760     unsigned IdxN10 = ConstN10Elt->getZExtValue();
51761     unsigned IdxN11 = ConstN11Elt->getZExtValue();
51762     // Add is commutative so indices can be reordered.
51763     if (IdxN00 > IdxN10) {
51764       std::swap(IdxN00, IdxN10);
51765       std::swap(IdxN01, IdxN11);
51766     }
51767     // N0 indices be the even element. N1 indices must be the next odd element.
51768     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
51769         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
51770       return SDValue();
51771     SDValue N00In = N00Elt.getOperand(0);
51772     SDValue N01In = N01Elt.getOperand(0);
51773     SDValue N10In = N10Elt.getOperand(0);
51774     SDValue N11In = N11Elt.getOperand(0);
51775 
51776     // First time we find an input capture it.
51777     if (!In0) {
51778       In0 = N00In;
51779       In1 = N01In;
51780 
51781       // The input vectors must be at least as wide as the output.
51782       // If they are larger than the output, we extract subvector below.
51783       if (In0.getValueSizeInBits() < VT.getSizeInBits() ||
51784           In1.getValueSizeInBits() < VT.getSizeInBits())
51785         return SDValue();
51786     }
51787     // Mul is commutative so the input vectors can be in any order.
51788     // Canonicalize to make the compares easier.
51789     if (In0 != N00In)
51790       std::swap(N00In, N01In);
51791     if (In0 != N10In)
51792       std::swap(N10In, N11In);
51793     if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
51794       return SDValue();
51795   }
51796 
51797   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
51798                          ArrayRef<SDValue> Ops) {
51799     EVT OpVT = Ops[0].getValueType();
51800     assert(OpVT.getScalarType() == MVT::i16 &&
51801            "Unexpected scalar element type");
51802     assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch");
51803     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
51804                                  OpVT.getVectorNumElements() / 2);
51805     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
51806   };
51807 
51808   // If the output is narrower than an input, extract the low part of the input
51809   // vector.
51810   EVT OutVT16 = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
51811                                VT.getVectorNumElements() * 2);
51812   if (OutVT16.bitsLT(In0.getValueType())) {
51813     In0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In0,
51814                       DAG.getIntPtrConstant(0, DL));
51815   }
51816   if (OutVT16.bitsLT(In1.getValueType())) {
51817     In1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In1,
51818                       DAG.getIntPtrConstant(0, DL));
51819   }
51820   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
51821                           PMADDBuilder);
51822 }
51823 
51824 // ADD(VPMADDWD(X,Y),VPMADDWD(Z,W)) -> VPMADDWD(SHUFFLE(X,Z), SHUFFLE(Y,W))
51825 // If upper element in each pair of both VPMADDWD are zero then we can merge
51826 // the operand elements and use the implicit add of VPMADDWD.
51827 // TODO: Add support for VPMADDUBSW (which isn't commutable).
51828 static SDValue combineAddOfPMADDWD(SelectionDAG &DAG, SDValue N0, SDValue N1,
51829                                    const SDLoc &DL, EVT VT) {
51830   if (N0.getOpcode() != N1.getOpcode() || N0.getOpcode() != X86ISD::VPMADDWD)
51831     return SDValue();
51832 
51833   // TODO: Add 256/512-bit support once VPMADDWD combines with shuffles.
51834   if (VT.getSizeInBits() > 128)
51835     return SDValue();
51836 
51837   unsigned NumElts = VT.getVectorNumElements();
51838   MVT OpVT = N0.getOperand(0).getSimpleValueType();
51839   APInt DemandedBits = APInt::getAllOnes(OpVT.getScalarSizeInBits());
51840   APInt DemandedHiElts = APInt::getSplat(2 * NumElts, APInt(2, 2));
51841 
51842   bool Op0HiZero =
51843       DAG.MaskedValueIsZero(N0.getOperand(0), DemandedBits, DemandedHiElts) ||
51844       DAG.MaskedValueIsZero(N0.getOperand(1), DemandedBits, DemandedHiElts);
51845   bool Op1HiZero =
51846       DAG.MaskedValueIsZero(N1.getOperand(0), DemandedBits, DemandedHiElts) ||
51847       DAG.MaskedValueIsZero(N1.getOperand(1), DemandedBits, DemandedHiElts);
51848 
51849   // TODO: Check for zero lower elements once we have actual codegen that
51850   // creates them.
51851   if (!Op0HiZero || !Op1HiZero)
51852     return SDValue();
51853 
51854   // Create a shuffle mask packing the lower elements from each VPMADDWD.
51855   SmallVector<int> Mask;
51856   for (int i = 0; i != (int)NumElts; ++i) {
51857     Mask.push_back(2 * i);
51858     Mask.push_back(2 * (i + NumElts));
51859   }
51860 
51861   SDValue LHS =
51862       DAG.getVectorShuffle(OpVT, DL, N0.getOperand(0), N1.getOperand(0), Mask);
51863   SDValue RHS =
51864       DAG.getVectorShuffle(OpVT, DL, N0.getOperand(1), N1.getOperand(1), Mask);
51865   return DAG.getNode(X86ISD::VPMADDWD, DL, VT, LHS, RHS);
51866 }
51867 
51868 /// CMOV of constants requires materializing constant operands in registers.
51869 /// Try to fold those constants into an 'add' instruction to reduce instruction
51870 /// count. We do this with CMOV rather the generic 'select' because there are
51871 /// earlier folds that may be used to turn select-of-constants into logic hacks.
51872 static SDValue pushAddIntoCmovOfConsts(SDNode *N, SelectionDAG &DAG) {
51873   // If an operand is zero, add-of-0 gets simplified away, so that's clearly
51874   // better because we eliminate 1-2 instructions. This transform is still
51875   // an improvement without zero operands because we trade 2 move constants and
51876   // 1 add for 2 adds (LEA) as long as the constants can be represented as
51877   // immediate asm operands (fit in 32-bits).
51878   auto isSuitableCmov = [](SDValue V) {
51879     if (V.getOpcode() != X86ISD::CMOV || !V.hasOneUse())
51880       return false;
51881     if (!isa<ConstantSDNode>(V.getOperand(0)) ||
51882         !isa<ConstantSDNode>(V.getOperand(1)))
51883       return false;
51884     return isNullConstant(V.getOperand(0)) || isNullConstant(V.getOperand(1)) ||
51885            (V.getConstantOperandAPInt(0).isSignedIntN(32) &&
51886             V.getConstantOperandAPInt(1).isSignedIntN(32));
51887   };
51888 
51889   // Match an appropriate CMOV as the first operand of the add.
51890   SDValue Cmov = N->getOperand(0);
51891   SDValue OtherOp = N->getOperand(1);
51892   if (!isSuitableCmov(Cmov))
51893     std::swap(Cmov, OtherOp);
51894   if (!isSuitableCmov(Cmov))
51895     return SDValue();
51896 
51897   EVT VT = N->getValueType(0);
51898   SDLoc DL(N);
51899   SDValue FalseOp = Cmov.getOperand(0);
51900   SDValue TrueOp = Cmov.getOperand(1);
51901 
51902   // We will push the add through the select, but we can potentially do better
51903   // if we know there is another add in the sequence and this is pointer math.
51904   // In that case, we can absorb an add into the trailing memory op and avoid
51905   // a 3-operand LEA which is likely slower than a 2-operand LEA.
51906   // TODO: If target has "slow3OpsLEA", do this even without the trailing memop?
51907   if (OtherOp.getOpcode() == ISD::ADD && OtherOp.hasOneUse() &&
51908       !isa<ConstantSDNode>(OtherOp.getOperand(0)) &&
51909       all_of(N->uses(), [&](SDNode *Use) {
51910         auto *MemNode = dyn_cast<MemSDNode>(Use);
51911         return MemNode && MemNode->getBasePtr().getNode() == N;
51912       })) {
51913     // add (cmov C1, C2), add (X, Y) --> add (cmov (add X, C1), (add X, C2)), Y
51914     // TODO: We are arbitrarily choosing op0 as the 1st piece of the sum, but
51915     //       it is possible that choosing op1 might be better.
51916     SDValue X = OtherOp.getOperand(0), Y = OtherOp.getOperand(1);
51917     FalseOp = DAG.getNode(ISD::ADD, DL, VT, X, FalseOp);
51918     TrueOp = DAG.getNode(ISD::ADD, DL, VT, X, TrueOp);
51919     Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp,
51920                        Cmov.getOperand(2), Cmov.getOperand(3));
51921     return DAG.getNode(ISD::ADD, DL, VT, Cmov, Y);
51922   }
51923 
51924   // add (cmov C1, C2), OtherOp --> cmov (add OtherOp, C1), (add OtherOp, C2)
51925   FalseOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, FalseOp);
51926   TrueOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, TrueOp);
51927   return DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp, Cmov.getOperand(2),
51928                      Cmov.getOperand(3));
51929 }
51930 
51931 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
51932                           TargetLowering::DAGCombinerInfo &DCI,
51933                           const X86Subtarget &Subtarget) {
51934   EVT VT = N->getValueType(0);
51935   SDValue Op0 = N->getOperand(0);
51936   SDValue Op1 = N->getOperand(1);
51937   SDLoc DL(N);
51938 
51939   if (SDValue Select = pushAddIntoCmovOfConsts(N, DAG))
51940     return Select;
51941 
51942   if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, DL, VT, Subtarget))
51943     return MAdd;
51944   if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, DL, VT, Subtarget))
51945     return MAdd;
51946   if (SDValue MAdd = combineAddOfPMADDWD(DAG, Op0, Op1, DL, VT))
51947     return MAdd;
51948 
51949   // Try to synthesize horizontal adds from adds of shuffles.
51950   if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
51951     return V;
51952 
51953   // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
51954   // (sub Y, (sext (vXi1 X))).
51955   // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
51956   // generic DAG combine without a legal type check, but adding this there
51957   // caused regressions.
51958   if (VT.isVector()) {
51959     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51960     if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
51961         Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
51962         TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
51963       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
51964       return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
51965     }
51966 
51967     if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
51968         Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
51969         TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
51970       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
51971       return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
51972     }
51973   }
51974 
51975   return combineAddOrSubToADCOrSBB(N, DAG);
51976 }
51977 
51978 // Try to fold (sub Y, cmovns X, -X) -> (add Y, cmovns -X, X) if the cmov
51979 // condition comes from the subtract node that produced -X. This matches the
51980 // cmov expansion for absolute value. By swapping the operands we convert abs
51981 // to nabs.
51982 static SDValue combineSubABS(SDNode *N, SelectionDAG &DAG) {
51983   SDValue N0 = N->getOperand(0);
51984   SDValue N1 = N->getOperand(1);
51985 
51986   if (N1.getOpcode() != X86ISD::CMOV || !N1.hasOneUse())
51987     return SDValue();
51988 
51989   X86::CondCode CC = (X86::CondCode)N1.getConstantOperandVal(2);
51990   if (CC != X86::COND_S && CC != X86::COND_NS)
51991     return SDValue();
51992 
51993   // Condition should come from a negate operation.
51994   SDValue Cond = N1.getOperand(3);
51995   if (Cond.getOpcode() != X86ISD::SUB || !isNullConstant(Cond.getOperand(0)))
51996     return SDValue();
51997   assert(Cond.getResNo() == 1 && "Unexpected result number");
51998 
51999   // Get the X and -X from the negate.
52000   SDValue NegX = Cond.getValue(0);
52001   SDValue X = Cond.getOperand(1);
52002 
52003   SDValue FalseOp = N1.getOperand(0);
52004   SDValue TrueOp = N1.getOperand(1);
52005 
52006   // Cmov operands should be X and NegX. Order doesn't matter.
52007   if (!(TrueOp == X && FalseOp == NegX) && !(TrueOp == NegX && FalseOp == X))
52008     return SDValue();
52009 
52010   // Build a new CMOV with the operands swapped.
52011   SDLoc DL(N);
52012   MVT VT = N->getSimpleValueType(0);
52013   SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, TrueOp, FalseOp,
52014                              N1.getOperand(2), Cond);
52015   // Convert sub to add.
52016   return DAG.getNode(ISD::ADD, DL, VT, N0, Cmov);
52017 }
52018 
52019 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
52020                           TargetLowering::DAGCombinerInfo &DCI,
52021                           const X86Subtarget &Subtarget) {
52022   SDValue Op0 = N->getOperand(0);
52023   SDValue Op1 = N->getOperand(1);
52024 
52025   // TODO: Add NoOpaque handling to isConstantIntBuildVectorOrConstantInt.
52026   auto IsNonOpaqueConstant = [&](SDValue Op) {
52027     if (SDNode *C = DAG.isConstantIntBuildVectorOrConstantInt(Op)) {
52028       if (auto *Cst = dyn_cast<ConstantSDNode>(C))
52029         return !Cst->isOpaque();
52030       return true;
52031     }
52032     return false;
52033   };
52034 
52035   // X86 can't encode an immediate LHS of a sub. See if we can push the
52036   // negation into a preceding instruction. If the RHS of the sub is a XOR with
52037   // one use and a constant, invert the immediate, saving one register.
52038   // sub(C1, xor(X, C2)) -> add(xor(X, ~C2), C1+1)
52039   if (Op1.getOpcode() == ISD::XOR && IsNonOpaqueConstant(Op0) &&
52040       IsNonOpaqueConstant(Op1.getOperand(1)) && Op1->hasOneUse()) {
52041     SDLoc DL(N);
52042     EVT VT = Op0.getValueType();
52043     SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT, Op1.getOperand(0),
52044                                  DAG.getNOT(SDLoc(Op1), Op1.getOperand(1), VT));
52045     SDValue NewAdd =
52046         DAG.getNode(ISD::ADD, DL, VT, Op0, DAG.getConstant(1, DL, VT));
52047     return DAG.getNode(ISD::ADD, DL, VT, NewXor, NewAdd);
52048   }
52049 
52050   if (SDValue V = combineSubABS(N, DAG))
52051     return V;
52052 
52053   // Try to synthesize horizontal subs from subs of shuffles.
52054   if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
52055     return V;
52056 
52057   return combineAddOrSubToADCOrSBB(N, DAG);
52058 }
52059 
52060 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
52061                                     const X86Subtarget &Subtarget) {
52062   MVT VT = N->getSimpleValueType(0);
52063   SDLoc DL(N);
52064 
52065   if (N->getOperand(0) == N->getOperand(1)) {
52066     if (N->getOpcode() == X86ISD::PCMPEQ)
52067       return DAG.getConstant(-1, DL, VT);
52068     if (N->getOpcode() == X86ISD::PCMPGT)
52069       return DAG.getConstant(0, DL, VT);
52070   }
52071 
52072   return SDValue();
52073 }
52074 
52075 /// Helper that combines an array of subvector ops as if they were the operands
52076 /// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
52077 /// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
52078 static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
52079                                       ArrayRef<SDValue> Ops, SelectionDAG &DAG,
52080                                       TargetLowering::DAGCombinerInfo &DCI,
52081                                       const X86Subtarget &Subtarget) {
52082   assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors");
52083   unsigned EltSizeInBits = VT.getScalarSizeInBits();
52084 
52085   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
52086     return DAG.getUNDEF(VT);
52087 
52088   if (llvm::all_of(Ops, [](SDValue Op) {
52089         return ISD::isBuildVectorAllZeros(Op.getNode());
52090       }))
52091     return getZeroVector(VT, Subtarget, DAG, DL);
52092 
52093   SDValue Op0 = Ops[0];
52094   bool IsSplat = llvm::all_of(Ops, [&Op0](SDValue Op) { return Op == Op0; });
52095 
52096   // Repeated subvectors.
52097   if (IsSplat &&
52098       (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
52099     // If this broadcast is inserted into both halves, use a larger broadcast.
52100     if (Op0.getOpcode() == X86ISD::VBROADCAST)
52101       return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
52102 
52103     // If this simple subvector or scalar/subvector broadcast_load is inserted
52104     // into both halves, use a larger broadcast_load. Update other uses to use
52105     // an extracted subvector.
52106     if (ISD::isNormalLoad(Op0.getNode()) ||
52107         Op0.getOpcode() == X86ISD::VBROADCAST_LOAD ||
52108         Op0.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
52109       auto *Mem = cast<MemSDNode>(Op0);
52110       unsigned Opc = Op0.getOpcode() == X86ISD::VBROADCAST_LOAD
52111                          ? X86ISD::VBROADCAST_LOAD
52112                          : X86ISD::SUBV_BROADCAST_LOAD;
52113       if (SDValue BcastLd =
52114               getBROADCAST_LOAD(Opc, DL, VT, Mem->getMemoryVT(), Mem, 0, DAG)) {
52115         SDValue BcastSrc =
52116             extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits());
52117         DAG.ReplaceAllUsesOfValueWith(Op0, BcastSrc);
52118         return BcastLd;
52119       }
52120     }
52121 
52122     // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
52123     if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
52124         (Subtarget.hasAVX2() ||
52125          X86::mayFoldLoadIntoBroadcastFromMem(Op0.getOperand(0),
52126                                               VT.getScalarType(), Subtarget)))
52127       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
52128                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
52129                                      Op0.getOperand(0),
52130                                      DAG.getIntPtrConstant(0, DL)));
52131 
52132     // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
52133     if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
52134         (Subtarget.hasAVX2() ||
52135          (EltSizeInBits >= 32 &&
52136           X86::mayFoldLoad(Op0.getOperand(0), Subtarget))) &&
52137         Op0.getOperand(0).getValueType() == VT.getScalarType())
52138       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
52139 
52140     // concat_vectors(extract_subvector(broadcast(x)),
52141     //                extract_subvector(broadcast(x))) -> broadcast(x)
52142     if (Op0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
52143         Op0.getOperand(0).getValueType() == VT) {
52144       if (Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST ||
52145           Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST_LOAD)
52146         return Op0.getOperand(0);
52147     }
52148   }
52149 
52150   // concat(extract_subvector(v0,c0), extract_subvector(v1,c1)) -> vperm2x128.
52151   // Only concat of subvector high halves which vperm2x128 is best at.
52152   // TODO: This should go in combineX86ShufflesRecursively eventually.
52153   if (VT.is256BitVector() && Ops.size() == 2) {
52154     SDValue Src0 = peekThroughBitcasts(Ops[0]);
52155     SDValue Src1 = peekThroughBitcasts(Ops[1]);
52156     if (Src0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
52157         Src1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
52158       EVT SrcVT0 = Src0.getOperand(0).getValueType();
52159       EVT SrcVT1 = Src1.getOperand(0).getValueType();
52160       unsigned NumSrcElts0 = SrcVT0.getVectorNumElements();
52161       unsigned NumSrcElts1 = SrcVT1.getVectorNumElements();
52162       if (SrcVT0.is256BitVector() && SrcVT1.is256BitVector() &&
52163           Src0.getConstantOperandAPInt(1) == (NumSrcElts0 / 2) &&
52164           Src1.getConstantOperandAPInt(1) == (NumSrcElts1 / 2)) {
52165         return DAG.getNode(X86ISD::VPERM2X128, DL, VT,
52166                            DAG.getBitcast(VT, Src0.getOperand(0)),
52167                            DAG.getBitcast(VT, Src1.getOperand(0)),
52168                            DAG.getTargetConstant(0x31, DL, MVT::i8));
52169       }
52170     }
52171   }
52172 
52173   // Repeated opcode.
52174   // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
52175   // but it currently struggles with different vector widths.
52176   if (llvm::all_of(Ops, [Op0](SDValue Op) {
52177         return Op.getOpcode() == Op0.getOpcode();
52178       })) {
52179     auto ConcatSubOperand = [&](MVT VT, ArrayRef<SDValue> SubOps, unsigned I) {
52180       SmallVector<SDValue> Subs;
52181       for (SDValue SubOp : SubOps)
52182         Subs.push_back(SubOp.getOperand(I));
52183       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
52184     };
52185 
52186     unsigned NumOps = Ops.size();
52187     switch (Op0.getOpcode()) {
52188     case X86ISD::SHUFP: {
52189       // Add SHUFPD support if/when necessary.
52190       if (!IsSplat && VT.getScalarType() == MVT::f32 &&
52191           llvm::all_of(Ops, [Op0](SDValue Op) {
52192             return Op.getOperand(2) == Op0.getOperand(2);
52193           })) {
52194         return DAG.getNode(Op0.getOpcode(), DL, VT,
52195                            ConcatSubOperand(VT, Ops, 0),
52196                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
52197       }
52198       break;
52199     }
52200     case X86ISD::PSHUFHW:
52201     case X86ISD::PSHUFLW:
52202     case X86ISD::PSHUFD:
52203       if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
52204           Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
52205         return DAG.getNode(Op0.getOpcode(), DL, VT,
52206                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
52207       }
52208       LLVM_FALLTHROUGH;
52209     case X86ISD::VPERMILPI:
52210       // TODO - add support for vXf64/vXi64 shuffles.
52211       if (!IsSplat && NumOps == 2 && (VT == MVT::v8f32 || VT == MVT::v8i32) &&
52212           Subtarget.hasAVX() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
52213         SDValue Res = DAG.getBitcast(MVT::v8f32, ConcatSubOperand(VT, Ops, 0));
52214         Res = DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, Res,
52215                           Op0.getOperand(1));
52216         return DAG.getBitcast(VT, Res);
52217       }
52218       break;
52219     case X86ISD::VPERMV3:
52220       if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
52221         MVT OpVT = Op0.getSimpleValueType();
52222         int NumSrcElts = OpVT.getVectorNumElements();
52223         SmallVector<int, 64> ConcatMask;
52224         for (unsigned i = 0; i != NumOps; ++i) {
52225           SmallVector<int, 64> SubMask;
52226           SmallVector<SDValue, 2> SubOps;
52227           if (!getTargetShuffleMask(Ops[i].getNode(), OpVT, false, SubOps,
52228                                     SubMask))
52229             break;
52230           for (int M : SubMask) {
52231             if (0 <= M) {
52232               M += M < NumSrcElts ? 0 : NumSrcElts;
52233               M += i * NumSrcElts;
52234             }
52235             ConcatMask.push_back(M);
52236           }
52237         }
52238         if (ConcatMask.size() == (NumOps * NumSrcElts)) {
52239           SDValue Src0 = concatSubVectors(Ops[0].getOperand(0),
52240                                           Ops[1].getOperand(0), DAG, DL);
52241           SDValue Src1 = concatSubVectors(Ops[0].getOperand(2),
52242                                           Ops[1].getOperand(2), DAG, DL);
52243           MVT IntMaskSVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
52244           MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
52245           SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
52246           return DAG.getNode(X86ISD::VPERMV3, DL, VT, Src0, Mask, Src1);
52247         }
52248       }
52249       break;
52250     case X86ISD::VSHLI:
52251     case X86ISD::VSRLI:
52252       // Special case: SHL/SRL AVX1 V4i64 by 32-bits can lower as a shuffle.
52253       // TODO: Move this to LowerShiftByScalarImmediate?
52254       if (VT == MVT::v4i64 && !Subtarget.hasInt256() &&
52255           llvm::all_of(Ops, [](SDValue Op) {
52256             return Op.getConstantOperandAPInt(1) == 32;
52257           })) {
52258         SDValue Res = DAG.getBitcast(MVT::v8i32, ConcatSubOperand(VT, Ops, 0));
52259         SDValue Zero = getZeroVector(MVT::v8i32, Subtarget, DAG, DL);
52260         if (Op0.getOpcode() == X86ISD::VSHLI) {
52261           Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
52262                                      {8, 0, 8, 2, 8, 4, 8, 6});
52263         } else {
52264           Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
52265                                      {1, 8, 3, 8, 5, 8, 7, 8});
52266         }
52267         return DAG.getBitcast(VT, Res);
52268       }
52269       LLVM_FALLTHROUGH;
52270     case X86ISD::VSRAI:
52271       if (((VT.is256BitVector() && Subtarget.hasInt256()) ||
52272            (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
52273             (EltSizeInBits >= 32 || Subtarget.useBWIRegs()))) &&
52274           llvm::all_of(Ops, [Op0](SDValue Op) {
52275             return Op0.getOperand(1) == Op.getOperand(1);
52276           })) {
52277         return DAG.getNode(Op0.getOpcode(), DL, VT,
52278                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
52279       }
52280       break;
52281     case X86ISD::VPERMI:
52282     case X86ISD::VROTLI:
52283     case X86ISD::VROTRI:
52284       if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
52285           llvm::all_of(Ops, [Op0](SDValue Op) {
52286             return Op0.getOperand(1) == Op.getOperand(1);
52287           })) {
52288         return DAG.getNode(Op0.getOpcode(), DL, VT,
52289                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
52290       }
52291       break;
52292     case ISD::AND:
52293     case ISD::OR:
52294     case ISD::XOR:
52295     case X86ISD::ANDNP:
52296       // TODO: Add 256-bit support.
52297       if (!IsSplat && VT.is512BitVector()) {
52298         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
52299         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
52300                                  NumOps * SrcVT.getVectorNumElements());
52301         return DAG.getNode(Op0.getOpcode(), DL, VT,
52302                            ConcatSubOperand(SrcVT, Ops, 0),
52303                            ConcatSubOperand(SrcVT, Ops, 1));
52304       }
52305       break;
52306     case X86ISD::HADD:
52307     case X86ISD::HSUB:
52308     case X86ISD::FHADD:
52309     case X86ISD::FHSUB:
52310     case X86ISD::PACKSS:
52311     case X86ISD::PACKUS:
52312       if (!IsSplat && VT.is256BitVector() &&
52313           (VT.isFloatingPoint() || Subtarget.hasInt256())) {
52314         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
52315         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
52316                                  NumOps * SrcVT.getVectorNumElements());
52317         return DAG.getNode(Op0.getOpcode(), DL, VT,
52318                            ConcatSubOperand(SrcVT, Ops, 0),
52319                            ConcatSubOperand(SrcVT, Ops, 1));
52320       }
52321       break;
52322     case X86ISD::PALIGNR:
52323       if (!IsSplat &&
52324           ((VT.is256BitVector() && Subtarget.hasInt256()) ||
52325            (VT.is512BitVector() && Subtarget.useBWIRegs())) &&
52326           llvm::all_of(Ops, [Op0](SDValue Op) {
52327             return Op0.getOperand(2) == Op.getOperand(2);
52328           })) {
52329         return DAG.getNode(Op0.getOpcode(), DL, VT,
52330                            ConcatSubOperand(VT, Ops, 0),
52331                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
52332       }
52333       break;
52334     }
52335   }
52336 
52337   // Fold subvector loads into one.
52338   // If needed, look through bitcasts to get to the load.
52339   if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
52340     bool Fast;
52341     const X86TargetLowering *TLI = Subtarget.getTargetLowering();
52342     if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
52343                                 *FirstLd->getMemOperand(), &Fast) &&
52344         Fast) {
52345       if (SDValue Ld =
52346               EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
52347         return Ld;
52348     }
52349   }
52350 
52351   return SDValue();
52352 }
52353 
52354 static SDValue combineConcatVectors(SDNode *N, SelectionDAG &DAG,
52355                                     TargetLowering::DAGCombinerInfo &DCI,
52356                                     const X86Subtarget &Subtarget) {
52357   EVT VT = N->getValueType(0);
52358   EVT SrcVT = N->getOperand(0).getValueType();
52359   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52360 
52361   // Don't do anything for i1 vectors.
52362   if (VT.getVectorElementType() == MVT::i1)
52363     return SDValue();
52364 
52365   if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
52366     SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
52367     if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
52368                                            DCI, Subtarget))
52369       return R;
52370   }
52371 
52372   return SDValue();
52373 }
52374 
52375 static SDValue combineInsertSubvector(SDNode *N, SelectionDAG &DAG,
52376                                       TargetLowering::DAGCombinerInfo &DCI,
52377                                       const X86Subtarget &Subtarget) {
52378   if (DCI.isBeforeLegalizeOps())
52379     return SDValue();
52380 
52381   MVT OpVT = N->getSimpleValueType(0);
52382 
52383   bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
52384 
52385   SDLoc dl(N);
52386   SDValue Vec = N->getOperand(0);
52387   SDValue SubVec = N->getOperand(1);
52388 
52389   uint64_t IdxVal = N->getConstantOperandVal(2);
52390   MVT SubVecVT = SubVec.getSimpleValueType();
52391 
52392   if (Vec.isUndef() && SubVec.isUndef())
52393     return DAG.getUNDEF(OpVT);
52394 
52395   // Inserting undefs/zeros into zeros/undefs is a zero vector.
52396   if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
52397       (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
52398     return getZeroVector(OpVT, Subtarget, DAG, dl);
52399 
52400   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
52401     // If we're inserting into a zero vector and then into a larger zero vector,
52402     // just insert into the larger zero vector directly.
52403     if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
52404         ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
52405       uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
52406       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
52407                          getZeroVector(OpVT, Subtarget, DAG, dl),
52408                          SubVec.getOperand(1),
52409                          DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
52410     }
52411 
52412     // If we're inserting into a zero vector and our input was extracted from an
52413     // insert into a zero vector of the same type and the extraction was at
52414     // least as large as the original insertion. Just insert the original
52415     // subvector into a zero vector.
52416     if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
52417         isNullConstant(SubVec.getOperand(1)) &&
52418         SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
52419       SDValue Ins = SubVec.getOperand(0);
52420       if (isNullConstant(Ins.getOperand(2)) &&
52421           ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
52422           Ins.getOperand(1).getValueSizeInBits().getFixedSize() <=
52423               SubVecVT.getFixedSizeInBits())
52424         return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
52425                            getZeroVector(OpVT, Subtarget, DAG, dl),
52426                            Ins.getOperand(1), N->getOperand(2));
52427     }
52428   }
52429 
52430   // Stop here if this is an i1 vector.
52431   if (IsI1Vector)
52432     return SDValue();
52433 
52434   // If this is an insert of an extract, combine to a shuffle. Don't do this
52435   // if the insert or extract can be represented with a subregister operation.
52436   if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
52437       SubVec.getOperand(0).getSimpleValueType() == OpVT &&
52438       (IdxVal != 0 ||
52439        !(Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())))) {
52440     int ExtIdxVal = SubVec.getConstantOperandVal(1);
52441     if (ExtIdxVal != 0) {
52442       int VecNumElts = OpVT.getVectorNumElements();
52443       int SubVecNumElts = SubVecVT.getVectorNumElements();
52444       SmallVector<int, 64> Mask(VecNumElts);
52445       // First create an identity shuffle mask.
52446       for (int i = 0; i != VecNumElts; ++i)
52447         Mask[i] = i;
52448       // Now insert the extracted portion.
52449       for (int i = 0; i != SubVecNumElts; ++i)
52450         Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
52451 
52452       return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
52453     }
52454   }
52455 
52456   // Match concat_vector style patterns.
52457   SmallVector<SDValue, 2> SubVectorOps;
52458   if (collectConcatOps(N, SubVectorOps)) {
52459     if (SDValue Fold =
52460             combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
52461       return Fold;
52462 
52463     // If we're inserting all zeros into the upper half, change this to
52464     // a concat with zero. We will match this to a move
52465     // with implicit upper bit zeroing during isel.
52466     // We do this here because we don't want combineConcatVectorOps to
52467     // create INSERT_SUBVECTOR from CONCAT_VECTORS.
52468     if (SubVectorOps.size() == 2 &&
52469         ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
52470       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
52471                          getZeroVector(OpVT, Subtarget, DAG, dl),
52472                          SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
52473   }
52474 
52475   // If this is a broadcast insert into an upper undef, use a larger broadcast.
52476   if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
52477     return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
52478 
52479   // If this is a broadcast load inserted into an upper undef, use a larger
52480   // broadcast load.
52481   if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
52482       SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
52483     auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
52484     SDVTList Tys = DAG.getVTList(OpVT, MVT::Other);
52485     SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
52486     SDValue BcastLd =
52487         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
52488                                 MemIntr->getMemoryVT(),
52489                                 MemIntr->getMemOperand());
52490     DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
52491     return BcastLd;
52492   }
52493 
52494   // If we're splatting the lower half subvector of a full vector load into the
52495   // upper half, attempt to create a subvector broadcast.
52496   if (IdxVal == (OpVT.getVectorNumElements() / 2) && SubVec.hasOneUse() &&
52497       Vec.getValueSizeInBits() == (2 * SubVec.getValueSizeInBits())) {
52498     auto *VecLd = dyn_cast<LoadSDNode>(Vec);
52499     auto *SubLd = dyn_cast<LoadSDNode>(SubVec);
52500     if (VecLd && SubLd &&
52501         DAG.areNonVolatileConsecutiveLoads(SubLd, VecLd,
52502                                            SubVec.getValueSizeInBits() / 8, 0))
52503       return getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, dl, OpVT, SubVecVT,
52504                                SubLd, 0, DAG);
52505   }
52506 
52507   return SDValue();
52508 }
52509 
52510 /// If we are extracting a subvector of a vector select and the select condition
52511 /// is composed of concatenated vectors, try to narrow the select width. This
52512 /// is a common pattern for AVX1 integer code because 256-bit selects may be
52513 /// legal, but there is almost no integer math/logic available for 256-bit.
52514 /// This function should only be called with legal types (otherwise, the calls
52515 /// to get simple value types will assert).
52516 static SDValue narrowExtractedVectorSelect(SDNode *Ext, SelectionDAG &DAG) {
52517   SDValue Sel = peekThroughBitcasts(Ext->getOperand(0));
52518   SmallVector<SDValue, 4> CatOps;
52519   if (Sel.getOpcode() != ISD::VSELECT ||
52520       !collectConcatOps(Sel.getOperand(0).getNode(), CatOps))
52521     return SDValue();
52522 
52523   // Note: We assume simple value types because this should only be called with
52524   //       legal operations/types.
52525   // TODO: This can be extended to handle extraction to 256-bits.
52526   MVT VT = Ext->getSimpleValueType(0);
52527   if (!VT.is128BitVector())
52528     return SDValue();
52529 
52530   MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
52531   if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
52532     return SDValue();
52533 
52534   MVT WideVT = Ext->getOperand(0).getSimpleValueType();
52535   MVT SelVT = Sel.getSimpleValueType();
52536   assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&
52537          "Unexpected vector type with legal operations");
52538 
52539   unsigned SelElts = SelVT.getVectorNumElements();
52540   unsigned CastedElts = WideVT.getVectorNumElements();
52541   unsigned ExtIdx = Ext->getConstantOperandVal(1);
52542   if (SelElts % CastedElts == 0) {
52543     // The select has the same or more (narrower) elements than the extract
52544     // operand. The extraction index gets scaled by that factor.
52545     ExtIdx *= (SelElts / CastedElts);
52546   } else if (CastedElts % SelElts == 0) {
52547     // The select has less (wider) elements than the extract operand. Make sure
52548     // that the extraction index can be divided evenly.
52549     unsigned IndexDivisor = CastedElts / SelElts;
52550     if (ExtIdx % IndexDivisor != 0)
52551       return SDValue();
52552     ExtIdx /= IndexDivisor;
52553   } else {
52554     llvm_unreachable("Element count of simple vector types are not divisible?");
52555   }
52556 
52557   unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
52558   unsigned NarrowElts = SelElts / NarrowingFactor;
52559   MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
52560   SDLoc DL(Ext);
52561   SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
52562   SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
52563   SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
52564   SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
52565   return DAG.getBitcast(VT, NarrowSel);
52566 }
52567 
52568 static SDValue combineExtractSubvector(SDNode *N, SelectionDAG &DAG,
52569                                        TargetLowering::DAGCombinerInfo &DCI,
52570                                        const X86Subtarget &Subtarget) {
52571   // For AVX1 only, if we are extracting from a 256-bit and+not (which will
52572   // eventually get combined/lowered into ANDNP) with a concatenated operand,
52573   // split the 'and' into 128-bit ops to avoid the concatenate and extract.
52574   // We let generic combining take over from there to simplify the
52575   // insert/extract and 'not'.
52576   // This pattern emerges during AVX1 legalization. We handle it before lowering
52577   // to avoid complications like splitting constant vector loads.
52578 
52579   // Capture the original wide type in the likely case that we need to bitcast
52580   // back to this type.
52581   if (!N->getValueType(0).isSimple())
52582     return SDValue();
52583 
52584   MVT VT = N->getSimpleValueType(0);
52585   SDValue InVec = N->getOperand(0);
52586   unsigned IdxVal = N->getConstantOperandVal(1);
52587   SDValue InVecBC = peekThroughBitcasts(InVec);
52588   EVT InVecVT = InVec.getValueType();
52589   unsigned SizeInBits = VT.getSizeInBits();
52590   unsigned InSizeInBits = InVecVT.getSizeInBits();
52591   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52592 
52593   if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
52594       TLI.isTypeLegal(InVecVT) &&
52595       InSizeInBits == 256 && InVecBC.getOpcode() == ISD::AND) {
52596     auto isConcatenatedNot = [](SDValue V) {
52597       V = peekThroughBitcasts(V);
52598       if (!isBitwiseNot(V))
52599         return false;
52600       SDValue NotOp = V->getOperand(0);
52601       return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
52602     };
52603     if (isConcatenatedNot(InVecBC.getOperand(0)) ||
52604         isConcatenatedNot(InVecBC.getOperand(1))) {
52605       // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
52606       SDValue Concat = splitVectorIntBinary(InVecBC, DAG);
52607       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
52608                          DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
52609     }
52610   }
52611 
52612   if (DCI.isBeforeLegalizeOps())
52613     return SDValue();
52614 
52615   if (SDValue V = narrowExtractedVectorSelect(N, DAG))
52616     return V;
52617 
52618   if (ISD::isBuildVectorAllZeros(InVec.getNode()))
52619     return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
52620 
52621   if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
52622     if (VT.getScalarType() == MVT::i1)
52623       return DAG.getConstant(1, SDLoc(N), VT);
52624     return getOnesVector(VT, DAG, SDLoc(N));
52625   }
52626 
52627   if (InVec.getOpcode() == ISD::BUILD_VECTOR)
52628     return DAG.getBuildVector(
52629         VT, SDLoc(N),
52630         InVec.getNode()->ops().slice(IdxVal, VT.getVectorNumElements()));
52631 
52632   // If we are extracting from an insert into a zero vector, replace with a
52633   // smaller insert into zero if we don't access less than the original
52634   // subvector. Don't do this for i1 vectors.
52635   if (VT.getVectorElementType() != MVT::i1 &&
52636       InVec.getOpcode() == ISD::INSERT_SUBVECTOR && IdxVal == 0 &&
52637       InVec.hasOneUse() && isNullConstant(InVec.getOperand(2)) &&
52638       ISD::isBuildVectorAllZeros(InVec.getOperand(0).getNode()) &&
52639       InVec.getOperand(1).getValueSizeInBits() <= SizeInBits) {
52640     SDLoc DL(N);
52641     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
52642                        getZeroVector(VT, Subtarget, DAG, DL),
52643                        InVec.getOperand(1), InVec.getOperand(2));
52644   }
52645 
52646   // If we're extracting an upper subvector from a broadcast we should just
52647   // extract the lowest subvector instead which should allow
52648   // SimplifyDemandedVectorElts do more simplifications.
52649   if (IdxVal != 0 && (InVec.getOpcode() == X86ISD::VBROADCAST ||
52650                       InVec.getOpcode() == X86ISD::VBROADCAST_LOAD ||
52651                       DAG.isSplatValue(InVec, /*AllowUndefs*/ false)))
52652     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
52653 
52654   // If we're extracting a broadcasted subvector, just use the lowest subvector.
52655   if (IdxVal != 0 && InVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
52656       cast<MemIntrinsicSDNode>(InVec)->getMemoryVT() == VT)
52657     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
52658 
52659   // Attempt to extract from the source of a shuffle vector.
52660   if ((InSizeInBits % SizeInBits) == 0 &&
52661       (IdxVal % VT.getVectorNumElements()) == 0) {
52662     SmallVector<int, 32> ShuffleMask;
52663     SmallVector<int, 32> ScaledMask;
52664     SmallVector<SDValue, 2> ShuffleInputs;
52665     unsigned NumSubVecs = InSizeInBits / SizeInBits;
52666     // Decode the shuffle mask and scale it so its shuffling subvectors.
52667     if (getTargetShuffleInputs(InVecBC, ShuffleInputs, ShuffleMask, DAG) &&
52668         scaleShuffleElements(ShuffleMask, NumSubVecs, ScaledMask)) {
52669       unsigned SubVecIdx = IdxVal / VT.getVectorNumElements();
52670       if (ScaledMask[SubVecIdx] == SM_SentinelUndef)
52671         return DAG.getUNDEF(VT);
52672       if (ScaledMask[SubVecIdx] == SM_SentinelZero)
52673         return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
52674       SDValue Src = ShuffleInputs[ScaledMask[SubVecIdx] / NumSubVecs];
52675       if (Src.getValueSizeInBits() == InSizeInBits) {
52676         unsigned SrcSubVecIdx = ScaledMask[SubVecIdx] % NumSubVecs;
52677         unsigned SrcEltIdx = SrcSubVecIdx * VT.getVectorNumElements();
52678         return extractSubVector(DAG.getBitcast(InVecVT, Src), SrcEltIdx, DAG,
52679                                 SDLoc(N), SizeInBits);
52680       }
52681     }
52682   }
52683 
52684   // If we're extracting the lowest subvector and we're the only user,
52685   // we may be able to perform this with a smaller vector width.
52686   unsigned InOpcode = InVec.getOpcode();
52687   if (IdxVal == 0 && InVec.hasOneUse()) {
52688     if (VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
52689       // v2f64 CVTDQ2PD(v4i32).
52690       if (InOpcode == ISD::SINT_TO_FP &&
52691           InVec.getOperand(0).getValueType() == MVT::v4i32) {
52692         return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
52693       }
52694       // v2f64 CVTUDQ2PD(v4i32).
52695       if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
52696           InVec.getOperand(0).getValueType() == MVT::v4i32) {
52697         return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
52698       }
52699       // v2f64 CVTPS2PD(v4f32).
52700       if (InOpcode == ISD::FP_EXTEND &&
52701           InVec.getOperand(0).getValueType() == MVT::v4f32) {
52702         return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
52703       }
52704     }
52705     if ((InOpcode == ISD::ANY_EXTEND ||
52706          InOpcode == ISD::ANY_EXTEND_VECTOR_INREG ||
52707          InOpcode == ISD::ZERO_EXTEND ||
52708          InOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
52709          InOpcode == ISD::SIGN_EXTEND ||
52710          InOpcode == ISD::SIGN_EXTEND_VECTOR_INREG) &&
52711         (SizeInBits == 128 || SizeInBits == 256) &&
52712         InVec.getOperand(0).getValueSizeInBits() >= SizeInBits) {
52713       SDLoc DL(N);
52714       SDValue Ext = InVec.getOperand(0);
52715       if (Ext.getValueSizeInBits() > SizeInBits)
52716         Ext = extractSubVector(Ext, 0, DAG, DL, SizeInBits);
52717       unsigned ExtOp = getOpcode_EXTEND_VECTOR_INREG(InOpcode);
52718       return DAG.getNode(ExtOp, DL, VT, Ext);
52719     }
52720     if (InOpcode == ISD::VSELECT &&
52721         InVec.getOperand(0).getValueType().is256BitVector() &&
52722         InVec.getOperand(1).getValueType().is256BitVector() &&
52723         InVec.getOperand(2).getValueType().is256BitVector()) {
52724       SDLoc DL(N);
52725       SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
52726       SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
52727       SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
52728       return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
52729     }
52730     if (InOpcode == ISD::TRUNCATE && Subtarget.hasVLX() &&
52731         (VT.is128BitVector() || VT.is256BitVector())) {
52732       SDLoc DL(N);
52733       SDValue InVecSrc = InVec.getOperand(0);
52734       unsigned Scale = InVecSrc.getValueSizeInBits() / InSizeInBits;
52735       SDValue Ext = extractSubVector(InVecSrc, 0, DAG, DL, Scale * SizeInBits);
52736       return DAG.getNode(InOpcode, DL, VT, Ext);
52737     }
52738   }
52739 
52740   // Always split vXi64 logical shifts where we're extracting the upper 32-bits
52741   // as this is very likely to fold into a shuffle/truncation.
52742   if ((InOpcode == X86ISD::VSHLI || InOpcode == X86ISD::VSRLI) &&
52743       InVecVT.getScalarSizeInBits() == 64 &&
52744       InVec.getConstantOperandAPInt(1) == 32) {
52745     SDLoc DL(N);
52746     SDValue Ext =
52747         extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
52748     return DAG.getNode(InOpcode, DL, VT, Ext, InVec.getOperand(1));
52749   }
52750 
52751   return SDValue();
52752 }
52753 
52754 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
52755   EVT VT = N->getValueType(0);
52756   SDValue Src = N->getOperand(0);
52757   SDLoc DL(N);
52758 
52759   // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
52760   // This occurs frequently in our masked scalar intrinsic code and our
52761   // floating point select lowering with AVX512.
52762   // TODO: SimplifyDemandedBits instead?
52763   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse())
52764     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
52765       if (C->getAPIntValue().isOne())
52766         return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1,
52767                            Src.getOperand(0));
52768 
52769   // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
52770   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
52771       Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
52772       Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
52773     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
52774       if (C->isZero())
52775         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
52776                            Src.getOperand(1));
52777 
52778   // Reduce v2i64 to v4i32 if we don't need the upper bits.
52779   // TODO: Move to DAGCombine/SimplifyDemandedBits?
52780   if (VT == MVT::v2i64 || VT == MVT::v2f64) {
52781     auto IsAnyExt64 = [](SDValue Op) {
52782       if (Op.getValueType() != MVT::i64 || !Op.hasOneUse())
52783         return SDValue();
52784       if (Op.getOpcode() == ISD::ANY_EXTEND &&
52785           Op.getOperand(0).getScalarValueSizeInBits() <= 32)
52786         return Op.getOperand(0);
52787       if (auto *Ld = dyn_cast<LoadSDNode>(Op))
52788         if (Ld->getExtensionType() == ISD::EXTLOAD &&
52789             Ld->getMemoryVT().getScalarSizeInBits() <= 32)
52790           return Op;
52791       return SDValue();
52792     };
52793     if (SDValue ExtSrc = IsAnyExt64(peekThroughOneUseBitcasts(Src)))
52794       return DAG.getBitcast(
52795           VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
52796                           DAG.getAnyExtOrTrunc(ExtSrc, DL, MVT::i32)));
52797   }
52798 
52799   // Combine (v2i64 (scalar_to_vector (i64 (bitconvert (mmx))))) to MOVQ2DQ.
52800   if (VT == MVT::v2i64 && Src.getOpcode() == ISD::BITCAST &&
52801       Src.getOperand(0).getValueType() == MVT::x86mmx)
52802     return DAG.getNode(X86ISD::MOVQ2DQ, DL, VT, Src.getOperand(0));
52803 
52804   // See if we're broadcasting the scalar value, in which case just reuse that.
52805   // Ensure the same SDValue from the SDNode use is being used.
52806   if (VT.getScalarType() == Src.getValueType())
52807     for (SDNode *User : Src->uses())
52808       if (User->getOpcode() == X86ISD::VBROADCAST &&
52809           Src == User->getOperand(0)) {
52810         unsigned SizeInBits = VT.getFixedSizeInBits();
52811         unsigned BroadcastSizeInBits =
52812             User->getValueSizeInBits(0).getFixedSize();
52813         if (BroadcastSizeInBits == SizeInBits)
52814           return SDValue(User, 0);
52815         if (BroadcastSizeInBits > SizeInBits)
52816           return extractSubVector(SDValue(User, 0), 0, DAG, DL, SizeInBits);
52817         // TODO: Handle BroadcastSizeInBits < SizeInBits when we have test
52818         // coverage.
52819       }
52820 
52821   return SDValue();
52822 }
52823 
52824 // Simplify PMULDQ and PMULUDQ operations.
52825 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
52826                              TargetLowering::DAGCombinerInfo &DCI,
52827                              const X86Subtarget &Subtarget) {
52828   SDValue LHS = N->getOperand(0);
52829   SDValue RHS = N->getOperand(1);
52830 
52831   // Canonicalize constant to RHS.
52832   if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
52833       !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
52834     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
52835 
52836   // Multiply by zero.
52837   // Don't return RHS as it may contain UNDEFs.
52838   if (ISD::isBuildVectorAllZeros(RHS.getNode()))
52839     return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
52840 
52841   // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
52842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52843   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(64), DCI))
52844     return SDValue(N, 0);
52845 
52846   // If the input is an extend_invec and the SimplifyDemandedBits call didn't
52847   // convert it to any_extend_invec, due to the LegalOperations check, do the
52848   // conversion directly to a vector shuffle manually. This exposes combine
52849   // opportunities missed by combineEXTEND_VECTOR_INREG not calling
52850   // combineX86ShufflesRecursively on SSE4.1 targets.
52851   // FIXME: This is basically a hack around several other issues related to
52852   // ANY_EXTEND_VECTOR_INREG.
52853   if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
52854       (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
52855        LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
52856       LHS.getOperand(0).getValueType() == MVT::v4i32) {
52857     SDLoc dl(N);
52858     LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
52859                                LHS.getOperand(0), { 0, -1, 1, -1 });
52860     LHS = DAG.getBitcast(MVT::v2i64, LHS);
52861     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
52862   }
52863   if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
52864       (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
52865        RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
52866       RHS.getOperand(0).getValueType() == MVT::v4i32) {
52867     SDLoc dl(N);
52868     RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
52869                                RHS.getOperand(0), { 0, -1, 1, -1 });
52870     RHS = DAG.getBitcast(MVT::v2i64, RHS);
52871     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
52872   }
52873 
52874   return SDValue();
52875 }
52876 
52877 // Simplify VPMADDUBSW/VPMADDWD operations.
52878 static SDValue combineVPMADD(SDNode *N, SelectionDAG &DAG,
52879                              TargetLowering::DAGCombinerInfo &DCI) {
52880   EVT VT = N->getValueType(0);
52881   SDValue LHS = N->getOperand(0);
52882   SDValue RHS = N->getOperand(1);
52883 
52884   // Multiply by zero.
52885   // Don't return LHS/RHS as it may contain UNDEFs.
52886   if (ISD::isBuildVectorAllZeros(LHS.getNode()) ||
52887       ISD::isBuildVectorAllZeros(RHS.getNode()))
52888     return DAG.getConstant(0, SDLoc(N), VT);
52889 
52890   APInt KnownUndef, KnownZero;
52891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52892   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
52893   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
52894                                      KnownZero, DCI))
52895     return SDValue(N, 0);
52896 
52897   return SDValue();
52898 }
52899 
52900 static SDValue combineEXTEND_VECTOR_INREG(SDNode *N, SelectionDAG &DAG,
52901                                           TargetLowering::DAGCombinerInfo &DCI,
52902                                           const X86Subtarget &Subtarget) {
52903   EVT VT = N->getValueType(0);
52904   SDValue In = N->getOperand(0);
52905   unsigned Opcode = N->getOpcode();
52906   unsigned InOpcode = In.getOpcode();
52907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52908 
52909   // Try to merge vector loads and extend_inreg to an extload.
52910   if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
52911       In.hasOneUse()) {
52912     auto *Ld = cast<LoadSDNode>(In);
52913     if (Ld->isSimple()) {
52914       MVT SVT = In.getSimpleValueType().getVectorElementType();
52915       ISD::LoadExtType Ext = Opcode == ISD::SIGN_EXTEND_VECTOR_INREG
52916                                  ? ISD::SEXTLOAD
52917                                  : ISD::ZEXTLOAD;
52918       EVT MemVT = VT.changeVectorElementType(SVT);
52919       if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
52920         SDValue Load =
52921             DAG.getExtLoad(Ext, SDLoc(N), VT, Ld->getChain(), Ld->getBasePtr(),
52922                            Ld->getPointerInfo(), MemVT, Ld->getOriginalAlign(),
52923                            Ld->getMemOperand()->getFlags());
52924         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
52925         return Load;
52926       }
52927     }
52928   }
52929 
52930   // Fold EXTEND_VECTOR_INREG(EXTEND_VECTOR_INREG(X)) -> EXTEND_VECTOR_INREG(X).
52931   if (Opcode == InOpcode)
52932     return DAG.getNode(Opcode, SDLoc(N), VT, In.getOperand(0));
52933 
52934   // Fold EXTEND_VECTOR_INREG(EXTRACT_SUBVECTOR(EXTEND(X),0))
52935   // -> EXTEND_VECTOR_INREG(X).
52936   // TODO: Handle non-zero subvector indices.
52937   if (InOpcode == ISD::EXTRACT_SUBVECTOR && In.getConstantOperandVal(1) == 0 &&
52938       In.getOperand(0).getOpcode() == getOpcode_EXTEND(Opcode) &&
52939       In.getOperand(0).getOperand(0).getValueSizeInBits() ==
52940           In.getValueSizeInBits())
52941     return DAG.getNode(Opcode, SDLoc(N), VT, In.getOperand(0).getOperand(0));
52942 
52943   // Attempt to combine as a shuffle.
52944   // TODO: General ZERO_EXTEND_VECTOR_INREG support.
52945   if (Opcode == ISD::ANY_EXTEND_VECTOR_INREG ||
52946       (Opcode == ISD::ZERO_EXTEND_VECTOR_INREG && Subtarget.hasSSE41())) {
52947     SDValue Op(N, 0);
52948     if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
52949       if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
52950         return Res;
52951   }
52952 
52953   return SDValue();
52954 }
52955 
52956 static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
52957                              TargetLowering::DAGCombinerInfo &DCI) {
52958   EVT VT = N->getValueType(0);
52959 
52960   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
52961     return DAG.getConstant(0, SDLoc(N), VT);
52962 
52963   APInt KnownUndef, KnownZero;
52964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52965   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
52966   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
52967                                      KnownZero, DCI))
52968     return SDValue(N, 0);
52969 
52970   return SDValue();
52971 }
52972 
52973 // Optimize (fp16_to_fp (fp_to_fp16 X)) to VCVTPS2PH followed by VCVTPH2PS.
52974 // Done as a combine because the lowering for fp16_to_fp and fp_to_fp16 produce
52975 // extra instructions between the conversion due to going to scalar and back.
52976 static SDValue combineFP16_TO_FP(SDNode *N, SelectionDAG &DAG,
52977                                  const X86Subtarget &Subtarget) {
52978   if (Subtarget.useSoftFloat() || !Subtarget.hasF16C())
52979     return SDValue();
52980 
52981   if (N->getOperand(0).getOpcode() != ISD::FP_TO_FP16)
52982     return SDValue();
52983 
52984   if (N->getValueType(0) != MVT::f32 ||
52985       N->getOperand(0).getOperand(0).getValueType() != MVT::f32)
52986     return SDValue();
52987 
52988   SDLoc dl(N);
52989   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32,
52990                             N->getOperand(0).getOperand(0));
52991   Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
52992                     DAG.getTargetConstant(4, dl, MVT::i32));
52993   Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
52994   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
52995                      DAG.getIntPtrConstant(0, dl));
52996 }
52997 
52998 static SDValue combineFP_EXTEND(SDNode *N, SelectionDAG &DAG,
52999                                 const X86Subtarget &Subtarget) {
53000   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
53001     return SDValue();
53002 
53003   if (Subtarget.hasFP16())
53004     return SDValue();
53005 
53006   bool IsStrict = N->isStrictFPOpcode();
53007   EVT VT = N->getValueType(0);
53008   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
53009   EVT SrcVT = Src.getValueType();
53010 
53011   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::f16)
53012     return SDValue();
53013 
53014   if (VT.getVectorElementType() != MVT::f32 &&
53015       VT.getVectorElementType() != MVT::f64)
53016     return SDValue();
53017 
53018   unsigned NumElts = VT.getVectorNumElements();
53019   if (NumElts == 1 || !isPowerOf2_32(NumElts))
53020     return SDValue();
53021 
53022   SDLoc dl(N);
53023 
53024   // Convert the input to vXi16.
53025   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
53026   Src = DAG.getBitcast(IntVT, Src);
53027 
53028   // Widen to at least 8 input elements.
53029   if (NumElts < 8) {
53030     unsigned NumConcats = 8 / NumElts;
53031     SDValue Fill = NumElts == 4 ? DAG.getUNDEF(IntVT)
53032                                 : DAG.getConstant(0, dl, IntVT);
53033     SmallVector<SDValue, 4> Ops(NumConcats, Fill);
53034     Ops[0] = Src;
53035     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, Ops);
53036   }
53037 
53038   // Destination is vXf32 with at least 4 elements.
53039   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32,
53040                                std::max(4U, NumElts));
53041   SDValue Cvt, Chain;
53042   if (IsStrict) {
53043     Cvt = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {CvtVT, MVT::Other},
53044                       {N->getOperand(0), Src});
53045     Chain = Cvt.getValue(1);
53046   } else {
53047     Cvt = DAG.getNode(X86ISD::CVTPH2PS, dl, CvtVT, Src);
53048   }
53049 
53050   if (NumElts < 4) {
53051     assert(NumElts == 2 && "Unexpected size");
53052     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Cvt,
53053                       DAG.getIntPtrConstant(0, dl));
53054   }
53055 
53056   if (IsStrict) {
53057     // Extend to the original VT if necessary.
53058     if (Cvt.getValueType() != VT) {
53059       Cvt = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {VT, MVT::Other},
53060                         {Chain, Cvt});
53061       Chain = Cvt.getValue(1);
53062     }
53063     return DAG.getMergeValues({Cvt, Chain}, dl);
53064   }
53065 
53066   // Extend to the original VT if necessary.
53067   return DAG.getNode(ISD::FP_EXTEND, dl, VT, Cvt);
53068 }
53069 
53070 // Try to find a larger VBROADCAST_LOAD/SUBV_BROADCAST_LOAD that we can extract
53071 // from. Limit this to cases where the loads have the same input chain and the
53072 // output chains are unused. This avoids any memory ordering issues.
53073 static SDValue combineBROADCAST_LOAD(SDNode *N, SelectionDAG &DAG,
53074                                      TargetLowering::DAGCombinerInfo &DCI) {
53075   assert((N->getOpcode() == X86ISD::VBROADCAST_LOAD ||
53076           N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
53077          "Unknown broadcast load type");
53078 
53079   // Only do this if the chain result is unused.
53080   if (N->hasAnyUseOfValue(1))
53081     return SDValue();
53082 
53083   auto *MemIntrin = cast<MemIntrinsicSDNode>(N);
53084 
53085   SDValue Ptr = MemIntrin->getBasePtr();
53086   SDValue Chain = MemIntrin->getChain();
53087   EVT VT = N->getSimpleValueType(0);
53088   EVT MemVT = MemIntrin->getMemoryVT();
53089 
53090   // Look at other users of our base pointer and try to find a wider broadcast.
53091   // The input chain and the size of the memory VT must match.
53092   for (SDNode *User : Ptr->uses())
53093     if (User != N && User->getOpcode() == N->getOpcode() &&
53094         cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
53095         cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
53096         cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
53097             MemVT.getSizeInBits() &&
53098         !User->hasAnyUseOfValue(1) &&
53099         User->getValueSizeInBits(0).getFixedSize() > VT.getFixedSizeInBits()) {
53100       SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
53101                                          VT.getSizeInBits());
53102       Extract = DAG.getBitcast(VT, Extract);
53103       return DCI.CombineTo(N, Extract, SDValue(User, 1));
53104     }
53105 
53106   return SDValue();
53107 }
53108 
53109 static SDValue combineFP_ROUND(SDNode *N, SelectionDAG &DAG,
53110                                const X86Subtarget &Subtarget) {
53111   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
53112     return SDValue();
53113 
53114   if (Subtarget.hasFP16())
53115     return SDValue();
53116 
53117   EVT VT = N->getValueType(0);
53118   SDValue Src = N->getOperand(0);
53119   EVT SrcVT = Src.getValueType();
53120 
53121   if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
53122       SrcVT.getVectorElementType() != MVT::f32)
53123     return SDValue();
53124 
53125   unsigned NumElts = VT.getVectorNumElements();
53126   if (NumElts == 1 || !isPowerOf2_32(NumElts))
53127     return SDValue();
53128 
53129   SDLoc dl(N);
53130 
53131   // Widen to at least 4 input elements.
53132   if (NumElts < 4)
53133     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
53134                       DAG.getConstantFP(0.0, dl, SrcVT));
53135 
53136   // Destination is v8i16 with at least 8 elements.
53137   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
53138                                std::max(8U, NumElts));
53139   SDValue Cvt = DAG.getNode(X86ISD::CVTPS2PH, dl, CvtVT, Src,
53140                             DAG.getTargetConstant(4, dl, MVT::i32));
53141 
53142   // Extract down to real number of elements.
53143   if (NumElts < 8) {
53144     EVT IntVT = VT.changeVectorElementTypeToInteger();
53145     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, IntVT, Cvt,
53146                       DAG.getIntPtrConstant(0, dl));
53147   }
53148 
53149   return DAG.getBitcast(VT, Cvt);
53150 }
53151 
53152 static SDValue combineMOVDQ2Q(SDNode *N, SelectionDAG &DAG) {
53153   SDValue Src = N->getOperand(0);
53154 
53155   // Turn MOVDQ2Q+simple_load into an mmx load.
53156   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
53157     LoadSDNode *LN = cast<LoadSDNode>(Src.getNode());
53158 
53159     if (LN->isSimple()) {
53160       SDValue NewLd = DAG.getLoad(MVT::x86mmx, SDLoc(N), LN->getChain(),
53161                                   LN->getBasePtr(),
53162                                   LN->getPointerInfo(),
53163                                   LN->getOriginalAlign(),
53164                                   LN->getMemOperand()->getFlags());
53165       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), NewLd.getValue(1));
53166       return NewLd;
53167     }
53168   }
53169 
53170   return SDValue();
53171 }
53172 
53173 static SDValue combinePDEP(SDNode *N, SelectionDAG &DAG,
53174                            TargetLowering::DAGCombinerInfo &DCI) {
53175   unsigned NumBits = N->getSimpleValueType(0).getSizeInBits();
53176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53177   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBits), DCI))
53178     return SDValue(N, 0);
53179 
53180   return SDValue();
53181 }
53182 
53183 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
53184                                              DAGCombinerInfo &DCI) const {
53185   SelectionDAG &DAG = DCI.DAG;
53186   switch (N->getOpcode()) {
53187   default: break;
53188   case ISD::SCALAR_TO_VECTOR:
53189     return combineScalarToVector(N, DAG);
53190   case ISD::EXTRACT_VECTOR_ELT:
53191   case X86ISD::PEXTRW:
53192   case X86ISD::PEXTRB:
53193     return combineExtractVectorElt(N, DAG, DCI, Subtarget);
53194   case ISD::CONCAT_VECTORS:
53195     return combineConcatVectors(N, DAG, DCI, Subtarget);
53196   case ISD::INSERT_SUBVECTOR:
53197     return combineInsertSubvector(N, DAG, DCI, Subtarget);
53198   case ISD::EXTRACT_SUBVECTOR:
53199     return combineExtractSubvector(N, DAG, DCI, Subtarget);
53200   case ISD::VSELECT:
53201   case ISD::SELECT:
53202   case X86ISD::BLENDV:      return combineSelect(N, DAG, DCI, Subtarget);
53203   case ISD::BITCAST:        return combineBitcast(N, DAG, DCI, Subtarget);
53204   case X86ISD::CMOV:        return combineCMov(N, DAG, DCI, Subtarget);
53205   case X86ISD::CMP:         return combineCMP(N, DAG);
53206   case ISD::ADD:            return combineAdd(N, DAG, DCI, Subtarget);
53207   case ISD::SUB:            return combineSub(N, DAG, DCI, Subtarget);
53208   case X86ISD::ADD:
53209   case X86ISD::SUB:         return combineX86AddSub(N, DAG, DCI);
53210   case X86ISD::SBB:         return combineSBB(N, DAG);
53211   case X86ISD::ADC:         return combineADC(N, DAG, DCI);
53212   case ISD::MUL:            return combineMul(N, DAG, DCI, Subtarget);
53213   case ISD::SHL:            return combineShiftLeft(N, DAG);
53214   case ISD::SRA:            return combineShiftRightArithmetic(N, DAG, Subtarget);
53215   case ISD::SRL:            return combineShiftRightLogical(N, DAG, DCI, Subtarget);
53216   case ISD::AND:            return combineAnd(N, DAG, DCI, Subtarget);
53217   case ISD::OR:             return combineOr(N, DAG, DCI, Subtarget);
53218   case ISD::XOR:            return combineXor(N, DAG, DCI, Subtarget);
53219   case X86ISD::BEXTR:
53220   case X86ISD::BEXTRI:      return combineBEXTR(N, DAG, DCI, Subtarget);
53221   case ISD::LOAD:           return combineLoad(N, DAG, DCI, Subtarget);
53222   case ISD::MLOAD:          return combineMaskedLoad(N, DAG, DCI, Subtarget);
53223   case ISD::STORE:          return combineStore(N, DAG, DCI, Subtarget);
53224   case ISD::MSTORE:         return combineMaskedStore(N, DAG, DCI, Subtarget);
53225   case X86ISD::VEXTRACT_STORE:
53226     return combineVEXTRACT_STORE(N, DAG, DCI, Subtarget);
53227   case ISD::SINT_TO_FP:
53228   case ISD::STRICT_SINT_TO_FP:
53229     return combineSIntToFP(N, DAG, DCI, Subtarget);
53230   case ISD::UINT_TO_FP:
53231   case ISD::STRICT_UINT_TO_FP:
53232     return combineUIntToFP(N, DAG, Subtarget);
53233   case ISD::FADD:
53234   case ISD::FSUB:           return combineFaddFsub(N, DAG, Subtarget);
53235   case X86ISD::VFCMULC:
53236   case X86ISD::VFMULC:      return combineFMulcFCMulc(N, DAG, Subtarget);
53237   case ISD::FNEG:           return combineFneg(N, DAG, DCI, Subtarget);
53238   case ISD::TRUNCATE:       return combineTruncate(N, DAG, Subtarget);
53239   case X86ISD::VTRUNC:      return combineVTRUNC(N, DAG, DCI);
53240   case X86ISD::ANDNP:       return combineAndnp(N, DAG, DCI, Subtarget);
53241   case X86ISD::FAND:        return combineFAnd(N, DAG, Subtarget);
53242   case X86ISD::FANDN:       return combineFAndn(N, DAG, Subtarget);
53243   case X86ISD::FXOR:
53244   case X86ISD::FOR:         return combineFOr(N, DAG, DCI, Subtarget);
53245   case X86ISD::FMIN:
53246   case X86ISD::FMAX:        return combineFMinFMax(N, DAG);
53247   case ISD::FMINNUM:
53248   case ISD::FMAXNUM:        return combineFMinNumFMaxNum(N, DAG, Subtarget);
53249   case X86ISD::CVTSI2P:
53250   case X86ISD::CVTUI2P:     return combineX86INT_TO_FP(N, DAG, DCI);
53251   case X86ISD::CVTP2SI:
53252   case X86ISD::CVTP2UI:
53253   case X86ISD::STRICT_CVTTP2SI:
53254   case X86ISD::CVTTP2SI:
53255   case X86ISD::STRICT_CVTTP2UI:
53256   case X86ISD::CVTTP2UI:
53257                             return combineCVTP2I_CVTTP2I(N, DAG, DCI);
53258   case X86ISD::STRICT_CVTPH2PS:
53259   case X86ISD::CVTPH2PS:    return combineCVTPH2PS(N, DAG, DCI);
53260   case X86ISD::BT:          return combineBT(N, DAG, DCI);
53261   case ISD::ANY_EXTEND:
53262   case ISD::ZERO_EXTEND:    return combineZext(N, DAG, DCI, Subtarget);
53263   case ISD::SIGN_EXTEND:    return combineSext(N, DAG, DCI, Subtarget);
53264   case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
53265   case ISD::ANY_EXTEND_VECTOR_INREG:
53266   case ISD::SIGN_EXTEND_VECTOR_INREG:
53267   case ISD::ZERO_EXTEND_VECTOR_INREG:
53268     return combineEXTEND_VECTOR_INREG(N, DAG, DCI, Subtarget);
53269   case ISD::SETCC:          return combineSetCC(N, DAG, DCI, Subtarget);
53270   case X86ISD::SETCC:       return combineX86SetCC(N, DAG, Subtarget);
53271   case X86ISD::BRCOND:      return combineBrCond(N, DAG, Subtarget);
53272   case X86ISD::PACKSS:
53273   case X86ISD::PACKUS:      return combineVectorPack(N, DAG, DCI, Subtarget);
53274   case X86ISD::HADD:
53275   case X86ISD::HSUB:
53276   case X86ISD::FHADD:
53277   case X86ISD::FHSUB:       return combineVectorHADDSUB(N, DAG, DCI, Subtarget);
53278   case X86ISD::VSHL:
53279   case X86ISD::VSRA:
53280   case X86ISD::VSRL:
53281     return combineVectorShiftVar(N, DAG, DCI, Subtarget);
53282   case X86ISD::VSHLI:
53283   case X86ISD::VSRAI:
53284   case X86ISD::VSRLI:
53285     return combineVectorShiftImm(N, DAG, DCI, Subtarget);
53286   case ISD::INSERT_VECTOR_ELT:
53287   case X86ISD::PINSRB:
53288   case X86ISD::PINSRW:      return combineVectorInsert(N, DAG, DCI, Subtarget);
53289   case X86ISD::SHUFP:       // Handle all target specific shuffles
53290   case X86ISD::INSERTPS:
53291   case X86ISD::EXTRQI:
53292   case X86ISD::INSERTQI:
53293   case X86ISD::VALIGN:
53294   case X86ISD::PALIGNR:
53295   case X86ISD::VSHLDQ:
53296   case X86ISD::VSRLDQ:
53297   case X86ISD::BLENDI:
53298   case X86ISD::UNPCKH:
53299   case X86ISD::UNPCKL:
53300   case X86ISD::MOVHLPS:
53301   case X86ISD::MOVLHPS:
53302   case X86ISD::PSHUFB:
53303   case X86ISD::PSHUFD:
53304   case X86ISD::PSHUFHW:
53305   case X86ISD::PSHUFLW:
53306   case X86ISD::MOVSHDUP:
53307   case X86ISD::MOVSLDUP:
53308   case X86ISD::MOVDDUP:
53309   case X86ISD::MOVSS:
53310   case X86ISD::MOVSD:
53311   case X86ISD::MOVSH:
53312   case X86ISD::VBROADCAST:
53313   case X86ISD::VPPERM:
53314   case X86ISD::VPERMI:
53315   case X86ISD::VPERMV:
53316   case X86ISD::VPERMV3:
53317   case X86ISD::VPERMIL2:
53318   case X86ISD::VPERMILPI:
53319   case X86ISD::VPERMILPV:
53320   case X86ISD::VPERM2X128:
53321   case X86ISD::SHUF128:
53322   case X86ISD::VZEXT_MOVL:
53323   case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
53324   case X86ISD::FMADD_RND:
53325   case X86ISD::FMSUB:
53326   case X86ISD::STRICT_FMSUB:
53327   case X86ISD::FMSUB_RND:
53328   case X86ISD::FNMADD:
53329   case X86ISD::STRICT_FNMADD:
53330   case X86ISD::FNMADD_RND:
53331   case X86ISD::FNMSUB:
53332   case X86ISD::STRICT_FNMSUB:
53333   case X86ISD::FNMSUB_RND:
53334   case ISD::FMA:
53335   case ISD::STRICT_FMA:     return combineFMA(N, DAG, DCI, Subtarget);
53336   case X86ISD::FMADDSUB_RND:
53337   case X86ISD::FMSUBADD_RND:
53338   case X86ISD::FMADDSUB:
53339   case X86ISD::FMSUBADD:    return combineFMADDSUB(N, DAG, DCI);
53340   case X86ISD::MOVMSK:      return combineMOVMSK(N, DAG, DCI, Subtarget);
53341   case X86ISD::MGATHER:
53342   case X86ISD::MSCATTER:
53343     return combineX86GatherScatter(N, DAG, DCI, Subtarget);
53344   case ISD::MGATHER:
53345   case ISD::MSCATTER:       return combineGatherScatter(N, DAG, DCI);
53346   case X86ISD::PCMPEQ:
53347   case X86ISD::PCMPGT:      return combineVectorCompare(N, DAG, Subtarget);
53348   case X86ISD::PMULDQ:
53349   case X86ISD::PMULUDQ:     return combinePMULDQ(N, DAG, DCI, Subtarget);
53350   case X86ISD::VPMADDUBSW:
53351   case X86ISD::VPMADDWD:    return combineVPMADD(N, DAG, DCI);
53352   case X86ISD::KSHIFTL:
53353   case X86ISD::KSHIFTR:     return combineKSHIFT(N, DAG, DCI);
53354   case ISD::FP16_TO_FP:     return combineFP16_TO_FP(N, DAG, Subtarget);
53355   case ISD::STRICT_FP_EXTEND:
53356   case ISD::FP_EXTEND:      return combineFP_EXTEND(N, DAG, Subtarget);
53357   case ISD::FP_ROUND:       return combineFP_ROUND(N, DAG, Subtarget);
53358   case X86ISD::VBROADCAST_LOAD:
53359   case X86ISD::SUBV_BROADCAST_LOAD: return combineBROADCAST_LOAD(N, DAG, DCI);
53360   case X86ISD::MOVDQ2Q:     return combineMOVDQ2Q(N, DAG);
53361   case X86ISD::PDEP:        return combinePDEP(N, DAG, DCI);
53362   }
53363 
53364   return SDValue();
53365 }
53366 
53367 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
53368   if (!isTypeLegal(VT))
53369     return false;
53370 
53371   // There are no vXi8 shifts.
53372   if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
53373     return false;
53374 
53375   // TODO: Almost no 8-bit ops are desirable because they have no actual
53376   //       size/speed advantages vs. 32-bit ops, but they do have a major
53377   //       potential disadvantage by causing partial register stalls.
53378   //
53379   // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
53380   // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
53381   // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
53382   // check for a constant operand to the multiply.
53383   if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
53384     return false;
53385 
53386   // i16 instruction encodings are longer and some i16 instructions are slow,
53387   // so those are not desirable.
53388   if (VT == MVT::i16) {
53389     switch (Opc) {
53390     default:
53391       break;
53392     case ISD::LOAD:
53393     case ISD::SIGN_EXTEND:
53394     case ISD::ZERO_EXTEND:
53395     case ISD::ANY_EXTEND:
53396     case ISD::SHL:
53397     case ISD::SRA:
53398     case ISD::SRL:
53399     case ISD::SUB:
53400     case ISD::ADD:
53401     case ISD::MUL:
53402     case ISD::AND:
53403     case ISD::OR:
53404     case ISD::XOR:
53405       return false;
53406     }
53407   }
53408 
53409   // Any legal type not explicitly accounted for above here is desirable.
53410   return true;
53411 }
53412 
53413 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
53414                                                   SDValue Value, SDValue Addr,
53415                                                   SelectionDAG &DAG) const {
53416   const Module *M = DAG.getMachineFunction().getMMI().getModule();
53417   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
53418   if (IsCFProtectionSupported) {
53419     // In case control-flow branch protection is enabled, we need to add
53420     // notrack prefix to the indirect branch.
53421     // In order to do that we create NT_BRIND SDNode.
53422     // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
53423     return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
53424   }
53425 
53426   return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
53427 }
53428 
53429 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
53430   EVT VT = Op.getValueType();
53431   bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
53432                              isa<ConstantSDNode>(Op.getOperand(1));
53433 
53434   // i16 is legal, but undesirable since i16 instruction encodings are longer
53435   // and some i16 instructions are slow.
53436   // 8-bit multiply-by-constant can usually be expanded to something cheaper
53437   // using LEA and/or other ALU ops.
53438   if (VT != MVT::i16 && !Is8BitMulByConstant)
53439     return false;
53440 
53441   auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
53442     if (!Op.hasOneUse())
53443       return false;
53444     SDNode *User = *Op->use_begin();
53445     if (!ISD::isNormalStore(User))
53446       return false;
53447     auto *Ld = cast<LoadSDNode>(Load);
53448     auto *St = cast<StoreSDNode>(User);
53449     return Ld->getBasePtr() == St->getBasePtr();
53450   };
53451 
53452   auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
53453     if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
53454       return false;
53455     if (!Op.hasOneUse())
53456       return false;
53457     SDNode *User = *Op->use_begin();
53458     if (User->getOpcode() != ISD::ATOMIC_STORE)
53459       return false;
53460     auto *Ld = cast<AtomicSDNode>(Load);
53461     auto *St = cast<AtomicSDNode>(User);
53462     return Ld->getBasePtr() == St->getBasePtr();
53463   };
53464 
53465   bool Commute = false;
53466   switch (Op.getOpcode()) {
53467   default: return false;
53468   case ISD::SIGN_EXTEND:
53469   case ISD::ZERO_EXTEND:
53470   case ISD::ANY_EXTEND:
53471     break;
53472   case ISD::SHL:
53473   case ISD::SRA:
53474   case ISD::SRL: {
53475     SDValue N0 = Op.getOperand(0);
53476     // Look out for (store (shl (load), x)).
53477     if (X86::mayFoldLoad(N0, Subtarget) && IsFoldableRMW(N0, Op))
53478       return false;
53479     break;
53480   }
53481   case ISD::ADD:
53482   case ISD::MUL:
53483   case ISD::AND:
53484   case ISD::OR:
53485   case ISD::XOR:
53486     Commute = true;
53487     LLVM_FALLTHROUGH;
53488   case ISD::SUB: {
53489     SDValue N0 = Op.getOperand(0);
53490     SDValue N1 = Op.getOperand(1);
53491     // Avoid disabling potential load folding opportunities.
53492     if (X86::mayFoldLoad(N1, Subtarget) &&
53493         (!Commute || !isa<ConstantSDNode>(N0) ||
53494          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
53495       return false;
53496     if (X86::mayFoldLoad(N0, Subtarget) &&
53497         ((Commute && !isa<ConstantSDNode>(N1)) ||
53498          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
53499       return false;
53500     if (IsFoldableAtomicRMW(N0, Op) ||
53501         (Commute && IsFoldableAtomicRMW(N1, Op)))
53502       return false;
53503   }
53504   }
53505 
53506   PVT = MVT::i32;
53507   return true;
53508 }
53509 
53510 //===----------------------------------------------------------------------===//
53511 //                           X86 Inline Assembly Support
53512 //===----------------------------------------------------------------------===//
53513 
53514 // Helper to match a string separated by whitespace.
53515 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
53516   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
53517 
53518   for (StringRef Piece : Pieces) {
53519     if (!S.startswith(Piece)) // Check if the piece matches.
53520       return false;
53521 
53522     S = S.substr(Piece.size());
53523     StringRef::size_type Pos = S.find_first_not_of(" \t");
53524     if (Pos == 0) // We matched a prefix.
53525       return false;
53526 
53527     S = S.substr(Pos);
53528   }
53529 
53530   return S.empty();
53531 }
53532 
53533 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
53534 
53535   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
53536     if (llvm::is_contained(AsmPieces, "~{cc}") &&
53537         llvm::is_contained(AsmPieces, "~{flags}") &&
53538         llvm::is_contained(AsmPieces, "~{fpsr}")) {
53539 
53540       if (AsmPieces.size() == 3)
53541         return true;
53542       else if (llvm::is_contained(AsmPieces, "~{dirflag}"))
53543         return true;
53544     }
53545   }
53546   return false;
53547 }
53548 
53549 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
53550   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
53551 
53552   const std::string &AsmStr = IA->getAsmString();
53553 
53554   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
53555   if (!Ty || Ty->getBitWidth() % 16 != 0)
53556     return false;
53557 
53558   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
53559   SmallVector<StringRef, 4> AsmPieces;
53560   SplitString(AsmStr, AsmPieces, ";\n");
53561 
53562   switch (AsmPieces.size()) {
53563   default: return false;
53564   case 1:
53565     // FIXME: this should verify that we are targeting a 486 or better.  If not,
53566     // we will turn this bswap into something that will be lowered to logical
53567     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
53568     // lower so don't worry about this.
53569     // bswap $0
53570     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
53571         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
53572         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
53573         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
53574         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
53575         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
53576       // No need to check constraints, nothing other than the equivalent of
53577       // "=r,0" would be valid here.
53578       return IntrinsicLowering::LowerToByteSwap(CI);
53579     }
53580 
53581     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
53582     if (CI->getType()->isIntegerTy(16) &&
53583         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
53584         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
53585          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
53586       AsmPieces.clear();
53587       StringRef ConstraintsStr = IA->getConstraintString();
53588       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
53589       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
53590       if (clobbersFlagRegisters(AsmPieces))
53591         return IntrinsicLowering::LowerToByteSwap(CI);
53592     }
53593     break;
53594   case 3:
53595     if (CI->getType()->isIntegerTy(32) &&
53596         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
53597         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
53598         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
53599         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
53600       AsmPieces.clear();
53601       StringRef ConstraintsStr = IA->getConstraintString();
53602       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
53603       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
53604       if (clobbersFlagRegisters(AsmPieces))
53605         return IntrinsicLowering::LowerToByteSwap(CI);
53606     }
53607 
53608     if (CI->getType()->isIntegerTy(64)) {
53609       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
53610       if (Constraints.size() >= 2 &&
53611           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
53612           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
53613         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
53614         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
53615             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
53616             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
53617           return IntrinsicLowering::LowerToByteSwap(CI);
53618       }
53619     }
53620     break;
53621   }
53622   return false;
53623 }
53624 
53625 static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
53626   X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
53627                            .Case("{@cca}", X86::COND_A)
53628                            .Case("{@ccae}", X86::COND_AE)
53629                            .Case("{@ccb}", X86::COND_B)
53630                            .Case("{@ccbe}", X86::COND_BE)
53631                            .Case("{@ccc}", X86::COND_B)
53632                            .Case("{@cce}", X86::COND_E)
53633                            .Case("{@ccz}", X86::COND_E)
53634                            .Case("{@ccg}", X86::COND_G)
53635                            .Case("{@ccge}", X86::COND_GE)
53636                            .Case("{@ccl}", X86::COND_L)
53637                            .Case("{@ccle}", X86::COND_LE)
53638                            .Case("{@ccna}", X86::COND_BE)
53639                            .Case("{@ccnae}", X86::COND_B)
53640                            .Case("{@ccnb}", X86::COND_AE)
53641                            .Case("{@ccnbe}", X86::COND_A)
53642                            .Case("{@ccnc}", X86::COND_AE)
53643                            .Case("{@ccne}", X86::COND_NE)
53644                            .Case("{@ccnz}", X86::COND_NE)
53645                            .Case("{@ccng}", X86::COND_LE)
53646                            .Case("{@ccnge}", X86::COND_L)
53647                            .Case("{@ccnl}", X86::COND_GE)
53648                            .Case("{@ccnle}", X86::COND_G)
53649                            .Case("{@ccno}", X86::COND_NO)
53650                            .Case("{@ccnp}", X86::COND_NP)
53651                            .Case("{@ccns}", X86::COND_NS)
53652                            .Case("{@cco}", X86::COND_O)
53653                            .Case("{@ccp}", X86::COND_P)
53654                            .Case("{@ccs}", X86::COND_S)
53655                            .Default(X86::COND_INVALID);
53656   return Cond;
53657 }
53658 
53659 /// Given a constraint letter, return the type of constraint for this target.
53660 X86TargetLowering::ConstraintType
53661 X86TargetLowering::getConstraintType(StringRef Constraint) const {
53662   if (Constraint.size() == 1) {
53663     switch (Constraint[0]) {
53664     case 'R':
53665     case 'q':
53666     case 'Q':
53667     case 'f':
53668     case 't':
53669     case 'u':
53670     case 'y':
53671     case 'x':
53672     case 'v':
53673     case 'l':
53674     case 'k': // AVX512 masking registers.
53675       return C_RegisterClass;
53676     case 'a':
53677     case 'b':
53678     case 'c':
53679     case 'd':
53680     case 'S':
53681     case 'D':
53682     case 'A':
53683       return C_Register;
53684     case 'I':
53685     case 'J':
53686     case 'K':
53687     case 'N':
53688     case 'G':
53689     case 'L':
53690     case 'M':
53691       return C_Immediate;
53692     case 'C':
53693     case 'e':
53694     case 'Z':
53695       return C_Other;
53696     default:
53697       break;
53698     }
53699   }
53700   else if (Constraint.size() == 2) {
53701     switch (Constraint[0]) {
53702     default:
53703       break;
53704     case 'Y':
53705       switch (Constraint[1]) {
53706       default:
53707         break;
53708       case 'z':
53709         return C_Register;
53710       case 'i':
53711       case 'm':
53712       case 'k':
53713       case 't':
53714       case '2':
53715         return C_RegisterClass;
53716       }
53717     }
53718   } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
53719     return C_Other;
53720   return TargetLowering::getConstraintType(Constraint);
53721 }
53722 
53723 /// Examine constraint type and operand type and determine a weight value.
53724 /// This object must already have been set up with the operand type
53725 /// and the current alternative constraint selected.
53726 TargetLowering::ConstraintWeight
53727   X86TargetLowering::getSingleConstraintMatchWeight(
53728     AsmOperandInfo &info, const char *constraint) const {
53729   ConstraintWeight weight = CW_Invalid;
53730   Value *CallOperandVal = info.CallOperandVal;
53731     // If we don't have a value, we can't do a match,
53732     // but allow it at the lowest weight.
53733   if (!CallOperandVal)
53734     return CW_Default;
53735   Type *type = CallOperandVal->getType();
53736   // Look at the constraint type.
53737   switch (*constraint) {
53738   default:
53739     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
53740     LLVM_FALLTHROUGH;
53741   case 'R':
53742   case 'q':
53743   case 'Q':
53744   case 'a':
53745   case 'b':
53746   case 'c':
53747   case 'd':
53748   case 'S':
53749   case 'D':
53750   case 'A':
53751     if (CallOperandVal->getType()->isIntegerTy())
53752       weight = CW_SpecificReg;
53753     break;
53754   case 'f':
53755   case 't':
53756   case 'u':
53757     if (type->isFloatingPointTy())
53758       weight = CW_SpecificReg;
53759     break;
53760   case 'y':
53761     if (type->isX86_MMXTy() && Subtarget.hasMMX())
53762       weight = CW_SpecificReg;
53763     break;
53764   case 'Y':
53765     if (StringRef(constraint).size() != 2)
53766       break;
53767     switch (constraint[1]) {
53768       default:
53769         return CW_Invalid;
53770       // XMM0
53771       case 'z':
53772         if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
53773             ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()) ||
53774             ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512()))
53775           return CW_SpecificReg;
53776         return CW_Invalid;
53777       // Conditional OpMask regs (AVX512)
53778       case 'k':
53779         if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
53780           return CW_Register;
53781         return CW_Invalid;
53782       // Any MMX reg
53783       case 'm':
53784         if (type->isX86_MMXTy() && Subtarget.hasMMX())
53785           return weight;
53786         return CW_Invalid;
53787       // Any SSE reg when ISA >= SSE2, same as 'x'
53788       case 'i':
53789       case 't':
53790       case '2':
53791         if (!Subtarget.hasSSE2())
53792           return CW_Invalid;
53793         break;
53794     }
53795     break;
53796   case 'v':
53797     if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
53798       weight = CW_Register;
53799     LLVM_FALLTHROUGH;
53800   case 'x':
53801     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
53802         ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
53803       weight = CW_Register;
53804     break;
53805   case 'k':
53806     // Enable conditional vector operations using %k<#> registers.
53807     if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
53808       weight = CW_Register;
53809     break;
53810   case 'I':
53811     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
53812       if (C->getZExtValue() <= 31)
53813         weight = CW_Constant;
53814     }
53815     break;
53816   case 'J':
53817     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
53818       if (C->getZExtValue() <= 63)
53819         weight = CW_Constant;
53820     }
53821     break;
53822   case 'K':
53823     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
53824       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
53825         weight = CW_Constant;
53826     }
53827     break;
53828   case 'L':
53829     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
53830       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
53831         weight = CW_Constant;
53832     }
53833     break;
53834   case 'M':
53835     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
53836       if (C->getZExtValue() <= 3)
53837         weight = CW_Constant;
53838     }
53839     break;
53840   case 'N':
53841     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
53842       if (C->getZExtValue() <= 0xff)
53843         weight = CW_Constant;
53844     }
53845     break;
53846   case 'G':
53847   case 'C':
53848     if (isa<ConstantFP>(CallOperandVal)) {
53849       weight = CW_Constant;
53850     }
53851     break;
53852   case 'e':
53853     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
53854       if ((C->getSExtValue() >= -0x80000000LL) &&
53855           (C->getSExtValue() <= 0x7fffffffLL))
53856         weight = CW_Constant;
53857     }
53858     break;
53859   case 'Z':
53860     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
53861       if (C->getZExtValue() <= 0xffffffff)
53862         weight = CW_Constant;
53863     }
53864     break;
53865   }
53866   return weight;
53867 }
53868 
53869 /// Try to replace an X constraint, which matches anything, with another that
53870 /// has more specific requirements based on the type of the corresponding
53871 /// operand.
53872 const char *X86TargetLowering::
53873 LowerXConstraint(EVT ConstraintVT) const {
53874   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
53875   // 'f' like normal targets.
53876   if (ConstraintVT.isFloatingPoint()) {
53877     if (Subtarget.hasSSE1())
53878       return "x";
53879   }
53880 
53881   return TargetLowering::LowerXConstraint(ConstraintVT);
53882 }
53883 
53884 // Lower @cc targets via setcc.
53885 SDValue X86TargetLowering::LowerAsmOutputForConstraint(
53886     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
53887     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
53888   X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
53889   if (Cond == X86::COND_INVALID)
53890     return SDValue();
53891   // Check that return type is valid.
53892   if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
53893       OpInfo.ConstraintVT.getSizeInBits() < 8)
53894     report_fatal_error("Flag output operand is of invalid type");
53895 
53896   // Get EFLAGS register. Only update chain when copyfrom is glued.
53897   if (Flag.getNode()) {
53898     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Flag);
53899     Chain = Flag.getValue(1);
53900   } else
53901     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
53902   // Extract CC code.
53903   SDValue CC = getSETCC(Cond, Flag, DL, DAG);
53904   // Extend to 32-bits
53905   SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
53906 
53907   return Result;
53908 }
53909 
53910 /// Lower the specified operand into the Ops vector.
53911 /// If it is invalid, don't add anything to Ops.
53912 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
53913                                                      std::string &Constraint,
53914                                                      std::vector<SDValue>&Ops,
53915                                                      SelectionDAG &DAG) const {
53916   SDValue Result;
53917 
53918   // Only support length 1 constraints for now.
53919   if (Constraint.length() > 1) return;
53920 
53921   char ConstraintLetter = Constraint[0];
53922   switch (ConstraintLetter) {
53923   default: break;
53924   case 'I':
53925     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
53926       if (C->getZExtValue() <= 31) {
53927         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
53928                                        Op.getValueType());
53929         break;
53930       }
53931     }
53932     return;
53933   case 'J':
53934     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
53935       if (C->getZExtValue() <= 63) {
53936         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
53937                                        Op.getValueType());
53938         break;
53939       }
53940     }
53941     return;
53942   case 'K':
53943     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
53944       if (isInt<8>(C->getSExtValue())) {
53945         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
53946                                        Op.getValueType());
53947         break;
53948       }
53949     }
53950     return;
53951   case 'L':
53952     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
53953       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
53954           (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
53955         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
53956                                        Op.getValueType());
53957         break;
53958       }
53959     }
53960     return;
53961   case 'M':
53962     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
53963       if (C->getZExtValue() <= 3) {
53964         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
53965                                        Op.getValueType());
53966         break;
53967       }
53968     }
53969     return;
53970   case 'N':
53971     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
53972       if (C->getZExtValue() <= 255) {
53973         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
53974                                        Op.getValueType());
53975         break;
53976       }
53977     }
53978     return;
53979   case 'O':
53980     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
53981       if (C->getZExtValue() <= 127) {
53982         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
53983                                        Op.getValueType());
53984         break;
53985       }
53986     }
53987     return;
53988   case 'e': {
53989     // 32-bit signed value
53990     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
53991       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
53992                                            C->getSExtValue())) {
53993         // Widen to 64 bits here to get it sign extended.
53994         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
53995         break;
53996       }
53997     // FIXME gcc accepts some relocatable values here too, but only in certain
53998     // memory models; it's complicated.
53999     }
54000     return;
54001   }
54002   case 'Z': {
54003     // 32-bit unsigned value
54004     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
54005       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
54006                                            C->getZExtValue())) {
54007         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
54008                                        Op.getValueType());
54009         break;
54010       }
54011     }
54012     // FIXME gcc accepts some relocatable values here too, but only in certain
54013     // memory models; it's complicated.
54014     return;
54015   }
54016   case 'i': {
54017     // Literal immediates are always ok.
54018     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
54019       bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
54020       BooleanContent BCont = getBooleanContents(MVT::i64);
54021       ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
54022                                     : ISD::SIGN_EXTEND;
54023       int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
54024                                                   : CST->getSExtValue();
54025       Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
54026       break;
54027     }
54028 
54029     // In any sort of PIC mode addresses need to be computed at runtime by
54030     // adding in a register or some sort of table lookup.  These can't
54031     // be used as immediates.
54032     if (Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC())
54033       return;
54034 
54035     // If we are in non-pic codegen mode, we allow the address of a global (with
54036     // an optional displacement) to be used with 'i'.
54037     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
54038       // If we require an extra load to get this address, as in PIC mode, we
54039       // can't accept it.
54040       if (isGlobalStubReference(
54041               Subtarget.classifyGlobalReference(GA->getGlobal())))
54042         return;
54043     break;
54044   }
54045   }
54046 
54047   if (Result.getNode()) {
54048     Ops.push_back(Result);
54049     return;
54050   }
54051   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
54052 }
54053 
54054 /// Check if \p RC is a general purpose register class.
54055 /// I.e., GR* or one of their variant.
54056 static bool isGRClass(const TargetRegisterClass &RC) {
54057   return RC.hasSuperClassEq(&X86::GR8RegClass) ||
54058          RC.hasSuperClassEq(&X86::GR16RegClass) ||
54059          RC.hasSuperClassEq(&X86::GR32RegClass) ||
54060          RC.hasSuperClassEq(&X86::GR64RegClass) ||
54061          RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
54062 }
54063 
54064 /// Check if \p RC is a vector register class.
54065 /// I.e., FR* / VR* or one of their variant.
54066 static bool isFRClass(const TargetRegisterClass &RC) {
54067   return RC.hasSuperClassEq(&X86::FR16XRegClass) ||
54068          RC.hasSuperClassEq(&X86::FR32XRegClass) ||
54069          RC.hasSuperClassEq(&X86::FR64XRegClass) ||
54070          RC.hasSuperClassEq(&X86::VR128XRegClass) ||
54071          RC.hasSuperClassEq(&X86::VR256XRegClass) ||
54072          RC.hasSuperClassEq(&X86::VR512RegClass);
54073 }
54074 
54075 /// Check if \p RC is a mask register class.
54076 /// I.e., VK* or one of their variant.
54077 static bool isVKClass(const TargetRegisterClass &RC) {
54078   return RC.hasSuperClassEq(&X86::VK1RegClass) ||
54079          RC.hasSuperClassEq(&X86::VK2RegClass) ||
54080          RC.hasSuperClassEq(&X86::VK4RegClass) ||
54081          RC.hasSuperClassEq(&X86::VK8RegClass) ||
54082          RC.hasSuperClassEq(&X86::VK16RegClass) ||
54083          RC.hasSuperClassEq(&X86::VK32RegClass) ||
54084          RC.hasSuperClassEq(&X86::VK64RegClass);
54085 }
54086 
54087 std::pair<unsigned, const TargetRegisterClass *>
54088 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
54089                                                 StringRef Constraint,
54090                                                 MVT VT) const {
54091   // First, see if this is a constraint that directly corresponds to an LLVM
54092   // register class.
54093   if (Constraint.size() == 1) {
54094     // GCC Constraint Letters
54095     switch (Constraint[0]) {
54096     default: break;
54097     // 'A' means [ER]AX + [ER]DX.
54098     case 'A':
54099       if (Subtarget.is64Bit())
54100         return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
54101       assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
54102              "Expecting 64, 32 or 16 bit subtarget");
54103       return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
54104 
54105       // TODO: Slight differences here in allocation order and leaving
54106       // RIP in the class. Do they matter any more here than they do
54107       // in the normal allocation?
54108     case 'k':
54109       if (Subtarget.hasAVX512()) {
54110         if (VT == MVT::i1)
54111           return std::make_pair(0U, &X86::VK1RegClass);
54112         if (VT == MVT::i8)
54113           return std::make_pair(0U, &X86::VK8RegClass);
54114         if (VT == MVT::i16)
54115           return std::make_pair(0U, &X86::VK16RegClass);
54116       }
54117       if (Subtarget.hasBWI()) {
54118         if (VT == MVT::i32)
54119           return std::make_pair(0U, &X86::VK32RegClass);
54120         if (VT == MVT::i64)
54121           return std::make_pair(0U, &X86::VK64RegClass);
54122       }
54123       break;
54124     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
54125       if (Subtarget.is64Bit()) {
54126         if (VT == MVT::i8 || VT == MVT::i1)
54127           return std::make_pair(0U, &X86::GR8RegClass);
54128         if (VT == MVT::i16)
54129           return std::make_pair(0U, &X86::GR16RegClass);
54130         if (VT == MVT::i32 || VT == MVT::f32)
54131           return std::make_pair(0U, &X86::GR32RegClass);
54132         if (VT != MVT::f80 && !VT.isVector())
54133           return std::make_pair(0U, &X86::GR64RegClass);
54134         break;
54135       }
54136       LLVM_FALLTHROUGH;
54137       // 32-bit fallthrough
54138     case 'Q':   // Q_REGS
54139       if (VT == MVT::i8 || VT == MVT::i1)
54140         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
54141       if (VT == MVT::i16)
54142         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
54143       if (VT == MVT::i32 || VT == MVT::f32 ||
54144           (!VT.isVector() && !Subtarget.is64Bit()))
54145         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
54146       if (VT != MVT::f80 && !VT.isVector())
54147         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
54148       break;
54149     case 'r':   // GENERAL_REGS
54150     case 'l':   // INDEX_REGS
54151       if (VT == MVT::i8 || VT == MVT::i1)
54152         return std::make_pair(0U, &X86::GR8RegClass);
54153       if (VT == MVT::i16)
54154         return std::make_pair(0U, &X86::GR16RegClass);
54155       if (VT == MVT::i32 || VT == MVT::f32 ||
54156           (!VT.isVector() && !Subtarget.is64Bit()))
54157         return std::make_pair(0U, &X86::GR32RegClass);
54158       if (VT != MVT::f80 && !VT.isVector())
54159         return std::make_pair(0U, &X86::GR64RegClass);
54160       break;
54161     case 'R':   // LEGACY_REGS
54162       if (VT == MVT::i8 || VT == MVT::i1)
54163         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
54164       if (VT == MVT::i16)
54165         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
54166       if (VT == MVT::i32 || VT == MVT::f32 ||
54167           (!VT.isVector() && !Subtarget.is64Bit()))
54168         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
54169       if (VT != MVT::f80 && !VT.isVector())
54170         return std::make_pair(0U, &X86::GR64_NOREXRegClass);
54171       break;
54172     case 'f':  // FP Stack registers.
54173       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
54174       // value to the correct fpstack register class.
54175       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
54176         return std::make_pair(0U, &X86::RFP32RegClass);
54177       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
54178         return std::make_pair(0U, &X86::RFP64RegClass);
54179       if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80)
54180         return std::make_pair(0U, &X86::RFP80RegClass);
54181       break;
54182     case 'y':   // MMX_REGS if MMX allowed.
54183       if (!Subtarget.hasMMX()) break;
54184       return std::make_pair(0U, &X86::VR64RegClass);
54185     case 'v':
54186     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
54187       if (!Subtarget.hasSSE1()) break;
54188       bool VConstraint = (Constraint[0] == 'v');
54189 
54190       switch (VT.SimpleTy) {
54191       default: break;
54192       // Scalar SSE types.
54193       case MVT::f16:
54194         if (VConstraint && Subtarget.hasFP16())
54195           return std::make_pair(0U, &X86::FR16XRegClass);
54196         break;
54197       case MVT::f32:
54198       case MVT::i32:
54199         if (VConstraint && Subtarget.hasVLX())
54200           return std::make_pair(0U, &X86::FR32XRegClass);
54201         return std::make_pair(0U, &X86::FR32RegClass);
54202       case MVT::f64:
54203       case MVT::i64:
54204         if (VConstraint && Subtarget.hasVLX())
54205           return std::make_pair(0U, &X86::FR64XRegClass);
54206         return std::make_pair(0U, &X86::FR64RegClass);
54207       case MVT::i128:
54208         if (Subtarget.is64Bit()) {
54209           if (VConstraint && Subtarget.hasVLX())
54210             return std::make_pair(0U, &X86::VR128XRegClass);
54211           return std::make_pair(0U, &X86::VR128RegClass);
54212         }
54213         break;
54214       // Vector types and fp128.
54215       case MVT::v8f16:
54216         if (!Subtarget.hasFP16())
54217           break;
54218         LLVM_FALLTHROUGH;
54219       case MVT::f128:
54220       case MVT::v16i8:
54221       case MVT::v8i16:
54222       case MVT::v4i32:
54223       case MVT::v2i64:
54224       case MVT::v4f32:
54225       case MVT::v2f64:
54226         if (VConstraint && Subtarget.hasVLX())
54227           return std::make_pair(0U, &X86::VR128XRegClass);
54228         return std::make_pair(0U, &X86::VR128RegClass);
54229       // AVX types.
54230       case MVT::v16f16:
54231         if (!Subtarget.hasFP16())
54232           break;
54233         LLVM_FALLTHROUGH;
54234       case MVT::v32i8:
54235       case MVT::v16i16:
54236       case MVT::v8i32:
54237       case MVT::v4i64:
54238       case MVT::v8f32:
54239       case MVT::v4f64:
54240         if (VConstraint && Subtarget.hasVLX())
54241           return std::make_pair(0U, &X86::VR256XRegClass);
54242         if (Subtarget.hasAVX())
54243           return std::make_pair(0U, &X86::VR256RegClass);
54244         break;
54245       case MVT::v32f16:
54246         if (!Subtarget.hasFP16())
54247           break;
54248         LLVM_FALLTHROUGH;
54249       case MVT::v64i8:
54250       case MVT::v32i16:
54251       case MVT::v8f64:
54252       case MVT::v16f32:
54253       case MVT::v16i32:
54254       case MVT::v8i64:
54255         if (!Subtarget.hasAVX512()) break;
54256         if (VConstraint)
54257           return std::make_pair(0U, &X86::VR512RegClass);
54258         return std::make_pair(0U, &X86::VR512_0_15RegClass);
54259       }
54260       break;
54261     }
54262   } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
54263     switch (Constraint[1]) {
54264     default:
54265       break;
54266     case 'i':
54267     case 't':
54268     case '2':
54269       return getRegForInlineAsmConstraint(TRI, "x", VT);
54270     case 'm':
54271       if (!Subtarget.hasMMX()) break;
54272       return std::make_pair(0U, &X86::VR64RegClass);
54273     case 'z':
54274       if (!Subtarget.hasSSE1()) break;
54275       switch (VT.SimpleTy) {
54276       default: break;
54277       // Scalar SSE types.
54278       case MVT::f16:
54279         if (!Subtarget.hasFP16())
54280           break;
54281         return std::make_pair(X86::XMM0, &X86::FR16XRegClass);
54282       case MVT::f32:
54283       case MVT::i32:
54284         return std::make_pair(X86::XMM0, &X86::FR32RegClass);
54285       case MVT::f64:
54286       case MVT::i64:
54287         return std::make_pair(X86::XMM0, &X86::FR64RegClass);
54288       case MVT::v8f16:
54289         if (!Subtarget.hasFP16())
54290           break;
54291         LLVM_FALLTHROUGH;
54292       case MVT::f128:
54293       case MVT::v16i8:
54294       case MVT::v8i16:
54295       case MVT::v4i32:
54296       case MVT::v2i64:
54297       case MVT::v4f32:
54298       case MVT::v2f64:
54299         return std::make_pair(X86::XMM0, &X86::VR128RegClass);
54300       // AVX types.
54301       case MVT::v16f16:
54302         if (!Subtarget.hasFP16())
54303           break;
54304         LLVM_FALLTHROUGH;
54305       case MVT::v32i8:
54306       case MVT::v16i16:
54307       case MVT::v8i32:
54308       case MVT::v4i64:
54309       case MVT::v8f32:
54310       case MVT::v4f64:
54311         if (Subtarget.hasAVX())
54312           return std::make_pair(X86::YMM0, &X86::VR256RegClass);
54313         break;
54314       case MVT::v32f16:
54315         if (!Subtarget.hasFP16())
54316           break;
54317         LLVM_FALLTHROUGH;
54318       case MVT::v64i8:
54319       case MVT::v32i16:
54320       case MVT::v8f64:
54321       case MVT::v16f32:
54322       case MVT::v16i32:
54323       case MVT::v8i64:
54324         if (Subtarget.hasAVX512())
54325           return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
54326         break;
54327       }
54328       break;
54329     case 'k':
54330       // This register class doesn't allocate k0 for masked vector operation.
54331       if (Subtarget.hasAVX512()) {
54332         if (VT == MVT::i1)
54333           return std::make_pair(0U, &X86::VK1WMRegClass);
54334         if (VT == MVT::i8)
54335           return std::make_pair(0U, &X86::VK8WMRegClass);
54336         if (VT == MVT::i16)
54337           return std::make_pair(0U, &X86::VK16WMRegClass);
54338       }
54339       if (Subtarget.hasBWI()) {
54340         if (VT == MVT::i32)
54341           return std::make_pair(0U, &X86::VK32WMRegClass);
54342         if (VT == MVT::i64)
54343           return std::make_pair(0U, &X86::VK64WMRegClass);
54344       }
54345       break;
54346     }
54347   }
54348 
54349   if (parseConstraintCode(Constraint) != X86::COND_INVALID)
54350     return std::make_pair(0U, &X86::GR32RegClass);
54351 
54352   // Use the default implementation in TargetLowering to convert the register
54353   // constraint into a member of a register class.
54354   std::pair<Register, const TargetRegisterClass*> Res;
54355   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
54356 
54357   // Not found as a standard register?
54358   if (!Res.second) {
54359     // Only match x87 registers if the VT is one SelectionDAGBuilder can convert
54360     // to/from f80.
54361     if (VT == MVT::Other || VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80) {
54362       // Map st(0) -> st(7) -> ST0
54363       if (Constraint.size() == 7 && Constraint[0] == '{' &&
54364           tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
54365           Constraint[3] == '(' &&
54366           (Constraint[4] >= '0' && Constraint[4] <= '7') &&
54367           Constraint[5] == ')' && Constraint[6] == '}') {
54368         // st(7) is not allocatable and thus not a member of RFP80. Return
54369         // singleton class in cases where we have a reference to it.
54370         if (Constraint[4] == '7')
54371           return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
54372         return std::make_pair(X86::FP0 + Constraint[4] - '0',
54373                               &X86::RFP80RegClass);
54374       }
54375 
54376       // GCC allows "st(0)" to be called just plain "st".
54377       if (StringRef("{st}").equals_insensitive(Constraint))
54378         return std::make_pair(X86::FP0, &X86::RFP80RegClass);
54379     }
54380 
54381     // flags -> EFLAGS
54382     if (StringRef("{flags}").equals_insensitive(Constraint))
54383       return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
54384 
54385     // dirflag -> DF
54386     // Only allow for clobber.
54387     if (StringRef("{dirflag}").equals_insensitive(Constraint) &&
54388         VT == MVT::Other)
54389       return std::make_pair(X86::DF, &X86::DFCCRRegClass);
54390 
54391     // fpsr -> FPSW
54392     if (StringRef("{fpsr}").equals_insensitive(Constraint))
54393       return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
54394 
54395     return Res;
54396   }
54397 
54398   // Make sure it isn't a register that requires 64-bit mode.
54399   if (!Subtarget.is64Bit() &&
54400       (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
54401       TRI->getEncodingValue(Res.first) >= 8) {
54402     // Register requires REX prefix, but we're in 32-bit mode.
54403     return std::make_pair(0, nullptr);
54404   }
54405 
54406   // Make sure it isn't a register that requires AVX512.
54407   if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
54408       TRI->getEncodingValue(Res.first) & 0x10) {
54409     // Register requires EVEX prefix.
54410     return std::make_pair(0, nullptr);
54411   }
54412 
54413   // Otherwise, check to see if this is a register class of the wrong value
54414   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
54415   // turn into {ax},{dx}.
54416   // MVT::Other is used to specify clobber names.
54417   if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
54418     return Res;   // Correct type already, nothing to do.
54419 
54420   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
54421   // return "eax". This should even work for things like getting 64bit integer
54422   // registers when given an f64 type.
54423   const TargetRegisterClass *Class = Res.second;
54424   // The generic code will match the first register class that contains the
54425   // given register. Thus, based on the ordering of the tablegened file,
54426   // the "plain" GR classes might not come first.
54427   // Therefore, use a helper method.
54428   if (isGRClass(*Class)) {
54429     unsigned Size = VT.getSizeInBits();
54430     if (Size == 1) Size = 8;
54431     Register DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
54432     if (DestReg > 0) {
54433       bool is64Bit = Subtarget.is64Bit();
54434       const TargetRegisterClass *RC =
54435           Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
54436         : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
54437         : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
54438         : Size == 64 ? (is64Bit ? &X86::GR64RegClass : nullptr)
54439         : nullptr;
54440       if (Size == 64 && !is64Bit) {
54441         // Model GCC's behavior here and select a fixed pair of 32-bit
54442         // registers.
54443         switch (DestReg) {
54444         case X86::RAX:
54445           return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
54446         case X86::RDX:
54447           return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
54448         case X86::RCX:
54449           return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
54450         case X86::RBX:
54451           return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
54452         case X86::RSI:
54453           return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
54454         case X86::RDI:
54455           return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
54456         case X86::RBP:
54457           return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
54458         default:
54459           return std::make_pair(0, nullptr);
54460         }
54461       }
54462       if (RC && RC->contains(DestReg))
54463         return std::make_pair(DestReg, RC);
54464       return Res;
54465     }
54466     // No register found/type mismatch.
54467     return std::make_pair(0, nullptr);
54468   } else if (isFRClass(*Class)) {
54469     // Handle references to XMM physical registers that got mapped into the
54470     // wrong class.  This can happen with constraints like {xmm0} where the
54471     // target independent register mapper will just pick the first match it can
54472     // find, ignoring the required type.
54473 
54474     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
54475     if (VT == MVT::f16)
54476       Res.second = &X86::FR16XRegClass;
54477     else if (VT == MVT::f32 || VT == MVT::i32)
54478       Res.second = &X86::FR32XRegClass;
54479     else if (VT == MVT::f64 || VT == MVT::i64)
54480       Res.second = &X86::FR64XRegClass;
54481     else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
54482       Res.second = &X86::VR128XRegClass;
54483     else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
54484       Res.second = &X86::VR256XRegClass;
54485     else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
54486       Res.second = &X86::VR512RegClass;
54487     else {
54488       // Type mismatch and not a clobber: Return an error;
54489       Res.first = 0;
54490       Res.second = nullptr;
54491     }
54492   } else if (isVKClass(*Class)) {
54493     if (VT == MVT::i1)
54494       Res.second = &X86::VK1RegClass;
54495     else if (VT == MVT::i8)
54496       Res.second = &X86::VK8RegClass;
54497     else if (VT == MVT::i16)
54498       Res.second = &X86::VK16RegClass;
54499     else if (VT == MVT::i32)
54500       Res.second = &X86::VK32RegClass;
54501     else if (VT == MVT::i64)
54502       Res.second = &X86::VK64RegClass;
54503     else {
54504       // Type mismatch and not a clobber: Return an error;
54505       Res.first = 0;
54506       Res.second = nullptr;
54507     }
54508   }
54509 
54510   return Res;
54511 }
54512 
54513 InstructionCost X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
54514                                                         const AddrMode &AM,
54515                                                         Type *Ty,
54516                                                         unsigned AS) const {
54517   // Scaling factors are not free at all.
54518   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
54519   // will take 2 allocations in the out of order engine instead of 1
54520   // for plain addressing mode, i.e. inst (reg1).
54521   // E.g.,
54522   // vaddps (%rsi,%rdx), %ymm0, %ymm1
54523   // Requires two allocations (one for the load, one for the computation)
54524   // whereas:
54525   // vaddps (%rsi), %ymm0, %ymm1
54526   // Requires just 1 allocation, i.e., freeing allocations for other operations
54527   // and having less micro operations to execute.
54528   //
54529   // For some X86 architectures, this is even worse because for instance for
54530   // stores, the complex addressing mode forces the instruction to use the
54531   // "load" ports instead of the dedicated "store" port.
54532   // E.g., on Haswell:
54533   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
54534   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
54535   if (isLegalAddressingMode(DL, AM, Ty, AS))
54536     // Scale represents reg2 * scale, thus account for 1
54537     // as soon as we use a second register.
54538     return AM.Scale != 0;
54539   return -1;
54540 }
54541 
54542 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
54543   // Integer division on x86 is expensive. However, when aggressively optimizing
54544   // for code size, we prefer to use a div instruction, as it is usually smaller
54545   // than the alternative sequence.
54546   // The exception to this is vector division. Since x86 doesn't have vector
54547   // integer division, leaving the division as-is is a loss even in terms of
54548   // size, because it will have to be scalarized, while the alternative code
54549   // sequence can be performed in vector form.
54550   bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
54551   return OptSize && !VT.isVector();
54552 }
54553 
54554 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
54555   if (!Subtarget.is64Bit())
54556     return;
54557 
54558   // Update IsSplitCSR in X86MachineFunctionInfo.
54559   X86MachineFunctionInfo *AFI =
54560       Entry->getParent()->getInfo<X86MachineFunctionInfo>();
54561   AFI->setIsSplitCSR(true);
54562 }
54563 
54564 void X86TargetLowering::insertCopiesSplitCSR(
54565     MachineBasicBlock *Entry,
54566     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
54567   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
54568   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
54569   if (!IStart)
54570     return;
54571 
54572   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
54573   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
54574   MachineBasicBlock::iterator MBBI = Entry->begin();
54575   for (const MCPhysReg *I = IStart; *I; ++I) {
54576     const TargetRegisterClass *RC = nullptr;
54577     if (X86::GR64RegClass.contains(*I))
54578       RC = &X86::GR64RegClass;
54579     else
54580       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
54581 
54582     Register NewVR = MRI->createVirtualRegister(RC);
54583     // Create copy from CSR to a virtual register.
54584     // FIXME: this currently does not emit CFI pseudo-instructions, it works
54585     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
54586     // nounwind. If we want to generalize this later, we may need to emit
54587     // CFI pseudo-instructions.
54588     assert(
54589         Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&
54590         "Function should be nounwind in insertCopiesSplitCSR!");
54591     Entry->addLiveIn(*I);
54592     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
54593         .addReg(*I);
54594 
54595     // Insert the copy-back instructions right before the terminator.
54596     for (auto *Exit : Exits)
54597       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
54598               TII->get(TargetOpcode::COPY), *I)
54599           .addReg(NewVR);
54600   }
54601 }
54602 
54603 bool X86TargetLowering::supportSwiftError() const {
54604   return Subtarget.is64Bit();
54605 }
54606 
54607 /// Returns true if stack probing through a function call is requested.
54608 bool X86TargetLowering::hasStackProbeSymbol(MachineFunction &MF) const {
54609   return !getStackProbeSymbolName(MF).empty();
54610 }
54611 
54612 /// Returns true if stack probing through inline assembly is requested.
54613 bool X86TargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
54614 
54615   // No inline stack probe for Windows, they have their own mechanism.
54616   if (Subtarget.isOSWindows() ||
54617       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
54618     return false;
54619 
54620   // If the function specifically requests inline stack probes, emit them.
54621   if (MF.getFunction().hasFnAttribute("probe-stack"))
54622     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
54623            "inline-asm";
54624 
54625   return false;
54626 }
54627 
54628 /// Returns the name of the symbol used to emit stack probes or the empty
54629 /// string if not applicable.
54630 StringRef
54631 X86TargetLowering::getStackProbeSymbolName(MachineFunction &MF) const {
54632   // Inline Stack probes disable stack probe call
54633   if (hasInlineStackProbe(MF))
54634     return "";
54635 
54636   // If the function specifically requests stack probes, emit them.
54637   if (MF.getFunction().hasFnAttribute("probe-stack"))
54638     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
54639 
54640   // Generally, if we aren't on Windows, the platform ABI does not include
54641   // support for stack probes, so don't emit them.
54642   if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
54643       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
54644     return "";
54645 
54646   // We need a stack probe to conform to the Windows ABI. Choose the right
54647   // symbol.
54648   if (Subtarget.is64Bit())
54649     return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
54650   return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
54651 }
54652 
54653 unsigned
54654 X86TargetLowering::getStackProbeSize(MachineFunction &MF) const {
54655   // The default stack probe size is 4096 if the function has no stackprobesize
54656   // attribute.
54657   unsigned StackProbeSize = 4096;
54658   const Function &Fn = MF.getFunction();
54659   if (Fn.hasFnAttribute("stack-probe-size"))
54660     Fn.getFnAttribute("stack-probe-size")
54661         .getValueAsString()
54662         .getAsInteger(0, StackProbeSize);
54663   return StackProbeSize;
54664 }
54665 
54666 Align X86TargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
54667   if (ML->isInnermost() &&
54668       ExperimentalPrefInnermostLoopAlignment.getNumOccurrences())
54669     return Align(1ULL << ExperimentalPrefInnermostLoopAlignment);
54670   return TargetLowering::getPrefLoopAlignment();
54671 }
54672